So I am trying to store data to variables on the page when a button is clicked, there are multiple buttons and it needs to store data for that specific button. Each one of these buttons is nested inside a <form onsubmit></form> all the data I need to extra is within this form in different <input> and <div> tags. So using javascript or jquery how can I select the value of a specific and tag. So when the button is clicked on it adds this product to the cart, I want to take the productNumber, price, and quantity and store them to my own variables. When the button is clicked the forum calls onsubmit="ShoppingCartAddAJAX( this ); so I want to store this data in the ShoppingCartAddAJAX function.
Here is what one of the forms on the page looks like.
<form method="post" name="addtocart-501" onsubmit="ShoppingCartAddAJAX( this ); return false;">
<input type="hidden" name="formName" value="ShoppingCartAddAJAX" />
<input type="hidden" name="productNumber" value="758201" />
<input id="qtyproduct" type="hidden" class="hiddenqty" name="dmst_Qty_2805" value="1" />
<div class="price">
<div class="pricenew singleprice">
$7.99
</div>
</div>
</a>
</div>
</div>
</li>
</form>
So I have been trying to get this data by doing something like this.
var pn = $('input[name$="productNumber"]').val();
var qty = $('input[id$="qtyproduct"]').val();
In my javascript file the function looks something like this:
function ShoppingCartAddAJAX(formElement, productNumber) {
var pn = $('formElement.input[name$="productNumber"]').val();
var aa = $('formElement[name$="productNumber"]').val();
var qty = $('input[id$="qtyproduct"]').val();
}
But with alot more code... just showing that the function is passing in formElement and a productNumber.
But this is giving me the product number and quantity of the first product on the page, I need the data for which ever button the user decides to click on and there are multiple ones on the page not just one. I hope that when the button is clicked and that function is fired there is a way to look what forum it came from and then extract that data. I would also like to be able to get the price but it is stored in <div class="pricenew singleprice"> $7.99</div>.
Any help is greatly appreciated.
You are getting the product number and quantity of the first record since you have multiple input fields in the form with the name of productNumber(according to your description). So what basically happens here is when you call $('input[name="productNumber"]').val() jquery returns you the value of the first input field. Instead of that, do something like this inside your ShoppingCartAddAJAX function.
function ShoppingCartAddAJAX(form)
{
// Find child an element inside our form with the id of "qtyproduct"
// I used "find("#qtyproduct")" method so it searches anything nested inside your specific form element
// You can use "children("#qtyproduct")" method also
var qty = $(form).find("#qtyproduct").val();
var pn = $(form).find("input[name='productNumber']").val();
var pp = $(form).find(".pricenew.singleprice").text();
}
Related
My website has a bunch of rows (as many as the user needs) consisting of two fields. I want the user to fill in all the fields, and submit them. However, I believe this can all be handled client-side, since I want to use the field values in javascript code.
this is the html code:
<div class="players">
<div id="wrapper">
<span>Name: <input type="text"> Dex modifier: <input type="text"></span>
</div>
<input type="button" value="add player" onclick="add_fields()">
<input type="button" value="submit" onclick="submit()">
</div>
and my javascript function
function add_fields() {
document.getElementById("wrapper").innerHTML += '<br><span>Name: <input type="text"> Dex modifier: <input type="text"></span>\r\n'
}
I need a way to get all of the form values (right now with an unwritten function submit()) and store them as variables.
It is good practice to use a <form> element when handling multiple inputs simultaneously. The form element can access all of the inputs it has inside of it. This way you won't have to select each individual input but can select and process them all together.
So start with the form wrapping. Then instead of listening for the onclick on the <input type="button" value="submit" onclick="submit()">, listen for the submit event on the form element.
It is considered best practice to listen to events by using the .addEventListener() method. This way you can set multiple event handlers to a single event without overwriting the onclick or onsubmit property of an element. Chris Baker does an excellent job explaining it in this SO post.
So now that you have a form, how do we get the data out of it? You could use the modern class of FormData. FormData creates an iterable object, which means we can loop over it using for..of, that holds all the names and values of the inputs in a form. It also has methods to add, remove and get the keys or values from the object. The FormData constructor can take a <form> element as argument like so:
var formElement = document.querySelector('form'); // Select the form.
var formData = new FormData(form); // Pass the form into the FormData class.
Now the formData variable holds all of the names and values of the form.
I've added a working example for you to try out. Please read up on the documentation I provided you to understand what is going on and what you can do with it.
Quick sidenote: FormData and the for..of loop are relatively new and are not supported in IE. If that is a dealbreaker I would suggest you don't use the FormData constructor and simply loop over the elements within the form.
Edit: I changed to loop from formData.values() to formData to get both the name and value attributes of each input. This is identical to formData.entries() as show in the MDN documents.
// Create storage for the values.
var values = [];
// Get the form element.
var form = document.getElementById('form');
// Add the submit event listener to the form.
form.addEventListener('submit', submit);
function submit(event) {
// Get the data from the form.
// event.target represents the form that is being submitted.
var formData = new FormData(event.target);
// Loop over each pair (name and value) in the form and add it to the values array.
for (var pair of formData) {
values.push(pair);
}
// Log the values to see the result.
console.log(values);
// Prevent the form from default submitting.
event.preventDefault();
}
<div class="players">
<!-- Wrap a form around the inputs -->
<form id="form">
<div id="wrapper">
<span>Name: <input type="text" name="name"> Dex modifier: <input type="text" name="dex"></span>
</div>
<input type="button" value="add player" onclick="add_fields()">
<!-- Notice type="submit" instead of type="button". This is important -->
<input type="submit" value="submit">
</form>
</div>
You need to be able to get the values of the dynamically added input elements.
First, you need to add them in a way you can separate them. So, providing each pair an exclusive parent is necessary.
document.getElementById("wrapper").innerHTML += '<div id="aparent"><br><span>Name: <input type="text" id="name"> Dex modifier: <input type="text" id="dex"></span><div>\r\n'
Now, get all the parent elements and iterate through them to fill an array of "name" and "dex-modifier" pairs. Use a library like JQuery for easy DOM manipulation. This seems to be your "submit" function.
var userData = [];
//Iterate all the parents
$('#aprane').each(function() {
//Get the values of each pair and put them in an array
userData.push({name: $(this).children('#name').val(), dex: $(this).children('#dex').val()}
})
I am new to Angular js and I need to create a form where the input fields will be dynamically generated based on a loop and I need to send all the field's data to an API.
This is the string that I get from the backend
"Earth:planet,life,solar,global$##data_col.signal:gateway ox,gw ox,gateway all ox,all sig,,gw signal gain,gateway"
This is my part of the html below where I process the string
<div class="container-fluid synBox">
<span><b>Enter synonyms:</b></span>
<form enctype='application/json'>
<div class="form-group" name="syn" ng-repeat="n in message.expert_advice.split('$##')">
<span class="fonts" style="color:#487baa;"><b>{{n.split(":")[0]}}</b></span>
<input class="form-control" id="expert_advice_input" type="text" ng-model={{n.split(":")[1]}} placeholder="" name={{n.split(":")[0]}} value={{n.split(":")[1]}}>
</div>
<button type="submit" class="btn btn-primary center-block" ng-click="submit_synonyms()">Submit</button>
</form>
</div>
Here is my js for the function in onclick submit_synonyms()
$scope.submit_synonyms = function() {
var variable = document.getElementById('expert_advice_input').value;
console.log(variable)
}
Here is what it looks like in the UI
I was hoping that I would get the value for all input fields but when I click the button I only get the value of the first input field (as seen in the console).
planet,life,solar,global
I also followed other similar questions in stackoverflow like Ng-repeat submit form with generated fields but couldn't figure out how to apply it in my situtation. What am I doing wrong?
Do note that the number of input fields can be dynamic based on the string supplied to me.
ADDITIONAL INFO
Just for the sake of clarity, the reason I am doing the splits on the string is to get the heading and the remaining comma separated strings in the input fields to which a user can add more string and hit the submit button.
write the following in your controller
const param = <input> //"Earth:planet,life,solar,global$##data_col.signal:gateway ox,gw ox,gateway all ox,all sig,,gw signal gain,gateway";
$scope.param = param.split('$##').reduce((acc,val)=> {
const spl = val.split(':');
acc[spl[0]] = spl[1];
return acc;
},{});
and following in your template or html
<ul >
<li data-ng-repeat="(key,value) in param"><label for={{key}}>{{key}}</label><input type='text' value='{{value}}'</li>
</ul>
add styles and optimize code style.
The scenario is that, I want to design a Post form which is used to record what fruit I eat in one meal, include picture, content, many kind of fruit.
The model relationship is that,
Post has_many fruits
Fruit belong_to post
I usee Jquery-ui to make autocomplete in order to help user type their fruit. After they type there fruit tag, it will create a tag under the input field.
Like this
However how to I create this in form? I thought about dynamic nested form, but I don't want there're a lots of form, I wish there would be only one input and do the same thing with dynamic nested form.
Here is the github, please let me know if I need to provide more information.
$(document).on('click','#add_fruit',function(e){
e.preventDefault();
addFruitTag();
});
function addFruitTag(){
var content = $('#content').val().trim();
var fruit = $('#fruit').val().trim();
if(content.length <1 || fruit.length < 1){
alert("Please fill content and fruit");
}else{
$('#fruit_tags').append(
$('<input>')
.attr('type','checkbox')
.attr('name','fruits[]')
.attr('value',$('#fruit').val())
.prop('checked','true')
)
.append(
$('<label>')
.text($('#fruit').val())
)
.append($('<br>'));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET">
Content : <input type="text" id="content" name="content"><br/>
Fruit : <input type="text" id="fruit">
<button id="add_fruit">Add Fruit</button><br/>
<div id="fruit_tags">
</div>
<input type="submit" value="Create Post">
</form>
Note: I don't have much idea about auto complete plugin, so I have created the function addFruitTag(), call it where you are calling your function of adding hash tags of fruits.
And when you will submit the form to the server, you can retrieve the added fruits by accessing the fruits[] variable , which will be an array containing the selected fruits tags.
I am not a JavaScript person really, I write in ASP and use a SQL database in the backend. But our marketing director requested a change that will use JavaScript.
On our view cart page, we're currently displaying an input box with a modify button to allow customers to change the quantity of the listed item (in that row... there could be multiple products in their cart, each having their own quantity input).
<form method="post" action="updateitem.asp">
<input type="hidden" name="product_id" value="<%= PRODUCT_ID %>">
Quantity: <input type"text" name="quantity">
<input type="image" name="Submit" src="/graphics/modify.gif" align="middle" border="0" alt="Continue">
</form>
What I'd like to make work is something like this. Hrm, assuming I need to do my form/div name differently for each product? I can easily write the product_id into the id tags but then assuming I'd also need to loop through my function for each one. I've gotten this far in writing the replacement code:
Get Dataset from Database (items in cart) and loop through:
<form method="post" action="updateitem.asp" id="updateitems<%= PRODUCT_ID %>">
Quantity: <input type="text" name="qty<%= PRODUCT_ID %>" OnChange="Javascript:UpdateQty()")
<div id="showlink<%= PRODUCT_ID %>">
<br /><span class="BodyTiny">update</span>
</div>
</form>
END LOOP
So if the quantity changes, it displays the word "update" where they can click and it passes whatever quantity that is in the quantity field to the updateitem.asp (in a way I can then update it in the database in ASP/SQL). In the code above, if we could just insert the new # in the a href statement after quantity=, then I could fix it in the updateitems.asp page without a problem.
I'm not sure where to even begin honestly, I have this so far:
LOOP through dataset so each product has its own function
<script Language="JavaScript">
<!--
function UpdateQty(updateitems<%= PRODUCT_ID %>) {
Show div updateitems<%= PRODUCT_ID %>
Replace NEWQUANT within that div with the value in the input field qty<%= PRODUCT_ID %>
}
//-->
</script>
END LOOP
I'm having a few problems...
I am not sure how to write the function UpdateQty. It should A) display the stuff in div id=showlink, and B) add the # from the input named quantity quantity to the href so I can update it in the database on the next page
If they have JavaScript turned off, they should be able to enter a new quantity and just hit enter for it to submit the form. I believe this will work as its a form with 1 text input and 1 hidden one, so just hitting enter in the text input should submit it. But that should still work with whatever JavaScript is added to make the showlink div show if it changes.
Do I need to add a class to my CSS for showlink? If so, what do I need to put in it?
Any help would be greatly appreciated!
Mahalo!
so what you can do for updateQty is have one function that will be correct for all products in a list just by making a function that finds all the necessary elements by relative paths.
//in this function the context is the element, so the
//`this` variable can be used rather than a param
//for the product id
function updateQty() {
//show the update link
var parent = this.parentNode;
//assumes only the update text uses the class bodyTiny, and that there
//is only one element using it. obviously making this invariant true
//would be trivial by adding a different class name
var updateText = parent.getElementsByClassName("bodyTiny")[0];
updateText.style.display = 'block';
var updateLink = updateText.parentNode
, updateHref = updateLink.href;
//next we find the current quantity and replace it with the input
updateHref = updateHref.replace(/qty=(\d*)/, 'qty='+this.value);
//then we set the link element's attribute
updateLink.href = updateHref;
//now when you mouse over the link you should see the url has changed
}
You can also set your form to POST the equivalent data, and then I guess on the server side you will have your OnGetPage and OnPostback both delegate to the same method with the parameters either parsed out of the query string or out of the post data.
You can see it running on jsfiddle. Hopefully this helps!
How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.