I am updating a product, I am able to have the product info prefill the update form and update the product info using jQuery but I want to use JavaScript. How do I convert this jQuery code to JavaScript?
I am following a tutorial online and the person is using jQuery which is cool but I want to see how to do the same method using Javascript.
Javascript Code:
$(document).on('pagebeforeshow', '#updatedialog', function() {
$('#newName').val(currentProduct.name);
$('#newQuantity').val(currentProduct.quantity);
});
function updateProduct() {
var newName = $('#newName').val();
var newQuantity = $('#newQuantity').val();
productHandler.updateProduct(currentProduct.id, newName, newQuantity);
}
HTML update form
<form>
<div class="ui-field-contain">
<label for="newName"
class="ui-hidden- accessible">Name</label>
<input type="text"
id="newName"
data-clear-btn="true"
placeholder="New Name"/>
<br/>
<label for="newQuantity"
class="ui-hidden-accessible">Quantity</label>
<input type="number"
name="number"
pattern="[0-9}"
id="newQuantity"
value=""
data-clear-btn="true"
placeholder="New Quantity"/>
<br/>
<button class="ui-btn ui-icon-plus ui-btn-icon-left"
id="btnupdate"
onclick="updateProduct()">
Update
</button>
</div>
</form>
The update form should populate with the information from the product that was already entered and then it should update the changes made to the fields and save it as a new object. I can do it in jQuery but I want help with doing it in Javascript.
Seems all you're currently doing with jquery is getting the value of input elements by their ID. You can do this with javascript by selecting the form element by ID and getting the value property.
val value = document.getElementById("elemID").value;
Your code should look like this
function updateProduct(){
var newName= document.getElementById("newName").value;
var newQuantity = document.getElementById("newQuantity").value;
productHandler.updateProduct(currentProduct.id, newName, newQuantity);
}
you can get values of of the element by id using document try the following
function updateProduct(){
var newName=document.getElementById("newName").value;
var newQuantity=document.getElementById("newQuantity ").value;
productHandler.updateProduct(currentProduct.id, newName, newQuantity);
}
Related
I'm trying to take some js that pulls data from another web application and populates a form by clicking "Populate Contact Info" and then click a "Submit" button to push the fields to a new php that then processes them. So basically how do I pass populated form field to a second form on the same page that I can then submit? Or is there a better way?
<form action="#" name="data" id="data">
<input type='button' value='Populate Contact Info' onclick='popAllContactFields()' />
Contact Info:
First Name: <input type='text' readonly="readonly" id='cfname' name='cfname' />
Last Name:<input type='text' readonly="readonly" id='clname' name='clname' />
Email: <input type='text' readonly="readonly" id='cemail' name='cemail' />
</form>
<script type="text/javascript">
/* popAllContactFields()
Populates all the contact fields from the current contact.
*/
function popAllContactFields()
{
var c = window.external.Contact;
{
// populate the contact info fields
popContact();
}
}
/* popContact()
Populates the contact info fields from the current contact.
*/
function popContact()
{
var c = window.external.Contact;
// set the contact fields
data.cfname.value = c.FirstName;
data.clname.value = c.LastName;
data.cemail.value = c.EmailAddr;
}
</script>
<form action="ordertest.php" method="post">
<input name="cfname" id="cfname" type="hidden" >
<input name="clname" id="clname" type="hidden" >
<input name="cemail" id="cemail" type="hidden" >
<input type="submit" value="Submit">
</form>
If you can manage to receive the data with an AJAX call as a JSON then it's vary easy. With using jQuery ($) and Lodash (_ but you can try Underscore as well):
$.get('an-url-that-returns-the-json', function(parsedData) {
_.forEach(_.keys(parsedData), function(key) {
console.log('key:', key);
$('#'+key).val(parsedData[key]);
});
});
If it's tough at first sight read some about jQuery selectors, AJAX ($.get()) and $(...).val().
You can also make a list about the keys that you want to copy, e.g. var keysToCopy = ['cfname', 'clname', 'cemail'] and then _.forEach(keysToCopy, function(key) {...}), this gives you more control with the copied data.
If you cannot use AJAX but can control the output of the source PHP, then I'd rather create the data as a raw JS object. If you cannot control the generated stuff then you must use something like you wrote, that also can be helped by some jQuery based magic, e.g.
_.forEach(keysToCopy, function(key) {
var prop = $('#source-form #'+key).val();
$('#target-form #'+key).val(prop)
});
Based on these you can think how you can solve if the source and target IDs are not the same.
I am having difficulty with a javascript that I need some help with. I have a form which sends to a php the exact amount of inputs to be filled, now I want to create a preview using jQuery/javascript but how can I catch all the fields dynamically.
Here is a portion of my form for reference:
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i></span>
<input class="form-control" id="task" type="text" name="task" placeholder="Task Title">
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i>
</span>
<input class="form-control" id="description" type="text" name="description" placeholder="Task Description">
</div>
</td>
So, I added in PHP the name field + the number, this way I can get different names ie: task1, task2,...etc.
Now what I need to do is get the values using jQuery/javascript.
My thoughts so far is to declare the var (variable) inside a for() (loop)
var task = $('input[name=task]').val();
How can I get all values task1, task2. No one knows how many task fields the user will submit so I need to get the number of fields
Any help direction so I can figure this out
First of all, you don't need to give your input fields names like task1, task2, etc to distinguish among them on the server-side i.e on the PHP. You just need to give all of them a name attribute value like tasks[] And notice the brackets [] so you may have something like the following:
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
...
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
Like that automatically values in those fields will be posted as an array to the PHP and it is going to be received like the following in PHP script:
$tasks = $_POST['tasks'];
foreach ($tasks as $task){
echo $task;
}
Second By this way you will easily able to collect your inputs data using Javascript inorder to generate the preview by using getElementsByName method as follows:
function preview(){
output = "";
tasks = document.getElementsByName('tasks[]');
for (i=0; i < tasks.length; i++){
output += "<b>Title</b>: "+tasks[i].value+"<hr />";
}
panel = document.getElementById('panel');
panel.innerHTML = output;
}
Of course you can expand this solution to any number of fields in your form such as descriptions[].
A javascript DEMO: http://jsbin.com/kiyisi/1/
Using the Attribute Starts With Selector [name^="value"] and jQuery.each()
var tasks = $('input[name^=task]').val();
$.each(tasks,function(index, value){
//do something with the value
alert($(this).val());
});
edit
var tasks = $('input[name^=task]');
$.each(tasks,function(index, value){
//do something with the value
$('#Preview').append($(this).val());
});
Q: now I want to create a preview using jquery/javascript but how can I catch all the fields dinamically:
If you give them a class, you can get all fields with each:
$(".className").each(function() {
do something
Next, "catch" all fields... I'm assuming you may want the values of these fields too? Check this example for details, here is a snippet which loads the key:value pairs (form field name : value of field) into a map:
var map = {};
$(".activeInput").each(function() {
map[$(this).attr("name")] = $(this).val();
});
Print all values inside div (Here, I'm assuming you're talking about children values of div):
<div>
<span>Hi</span>
<span>Hello</span>
<span>Hi again</span>
</div>
$("div").children().each(function () {
console.log($(this).text());
});
OR
$("div span").each(function () {
console.log($(this).text());
});
I cannot find the accept answer on here.
Currently I have a simple html form, that allows the user to enter text, in this case a user name.
<form class="Find Friend">
<div class="error" style="display:none"></div>
<input type="text" id="friendsearch" placeholder="Find Friend" class="input-field" required/>
<button type="submit" class="btn btn-login">Find</button>
</form>
I want to capture that name in a variable for later use. Do I simply use ?
var findFriend = friendsearch;
To keep the var updating on each user input, you can use.
http://jsfiddle.net/gRZ7g/
var friendName;
$('#friendsearch').on('keyup', function(e) {
friendName = $(this).val();
});
$('.show-value').click(function(e) {
alert(friendName);
});
You can get it like this:
var findFriend = $('#friendsearch').val();
You have to use the jQuery selector to select the element by its id.
I have created a form with dynamic field. but i m getting confused that how should i post data into database. because there would be different field according to different users.
here is the basic code with one dynamic field
function add2(type) {
var element = document.createElement("textArea");
var label=prompt("Enter the name for lable","label");
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+label;
element.setAttribute("type", type);
element.setAttribute("name", type);
var col=prompt('Enter the no of columns');
element.setAttribute("cols",col);
var row=prompt('Enter the no of rows');
element.setAttribute("rows",row);
var rohit = document.getElementById("raj");
rohit.appendChild(element);
document.getElementById('raj').innerHTML=document.getElementById('raj').innerHTML+"<br/>";
}
here is the calling of this function.
<input type="button" value="Text Area" onclick="add2('textarea')"><br/>
</div>
<div id="content" style="height:200px;width:400px;float:left;">
<form action="#" method="post">
<span id="raj"> </span>
<input type="submit" value="submit"></div>
help me guys what should i do to store the dynamic elements into database
and what fields should i put into database
Store the field values separated in one hiddenfield, and get them from the serves side.
<input id="values" type="hidden" value="value1,value2,value3">
on submit:
var Valuearray = values.value.Split(',');
I want to retrieve textfield value using javascript. suppose i have a code like:
<input type='text' name='txt'>
And I want to retrieve it using javascript. I call a function when a button is clicked:
<input type='button' onclick='retrieve(txt)'>
What coding will the retrieve function consist of?
You can do this:
Markup:
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="retrieve('txt');"/>
JavaScript:
function retrieve(id) {
var txtbox = document.getElementById(id);
var value = txtbox.value;
}
Let's say you have an input on your page with an id of input1, like this:
<input type="text" id="input1" />
You first need to get the element, and if you know the Id, you can use document.getElementById('input1'). Then, just call .value to get the value of the input box:
var value = document.getElementById('input1').value;
Update
Based on your markup, I would suggest specifying an id for your text box. Incase you don't have control over the markup, you can use document.getElementsByName, like so:
var value = document.getElementsByName('txt')[0].value;
One of the way is already explained by Andrew Hare.
You can also do it by entering the value in the textbox and getting a prompt box with entered message when a user click the button.
Let's say, you have a textbox and a input button
<input type="text" name="myText" size="20" />
<input type="button" value="Alert Text" onclick="retrieve()" />
The function for retrieve()
function retrieve()
{
var text = document.simpleForm.myText.value;
alert(text);
}