How can I get user input with HTML to handle in JS? - javascript

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()}
})

Related

angular2 capture info from dynamically generated inputs - possible?

Working on an update form which I would like to generate and capture inputs for a variable sized array
The current unhappy version only supports the first three statically defined elements in the constituency array. So the inputs look like this...
<input #newConstituency1 class="form-control" value={{legislatorToDisplay?.constituency[0]}}>
<input #newConstituency2 class="form-control" value={{legislatorToDisplay?.constituency[1]}}>
<input #newConstituency3 class="form-control" value={{legislatorToDisplay?.constituency[2]}}>
and the function to update pulls the values of the form using the static octothorpe tags.
updateLegislator(newConstituency1.value, newConstituency2.value, newConstituency3.value)
But this doesn't allow for a variable sized Constituency array.
I am able to use *ngFor directive to dynamically create input fields for a theoretically infinitely sized constituency array:
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}}>
</div>
but have not successfully been able to capture that information thereafter. Any kind assistance would be greatly appreciated.
You just have to have a form object in your component that matches the HTML input components that were created.
Template
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}} formControlName="{{constit}}">
</div>
Component
/* create an empty form then loop through values and add control
fb is a FormBuilder object. */
let form = this.fb.group({});
for(let const of legislatorToDisplay.constituency) {
form.addControl(new FormControl(const))
}
Use two-way data binding:
<div *ngFor="constit of legislatorToDisplay?.constituency; let i = index">
<input [(ngModel)]="legislatorToDisplay?.constituency[i]">
</div>

Store data on page to variables using Javascript/JQuery

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();
}

Populate form field with javascript

I have a form with several fields populated by the user and before it is submitted some javascript gets called when a check button. It tries to set the value of the form fields to a variable that exists in the js function.
document.getElementById('var1').innerHTML = test;
alert(test);
I know the javascript is working as expected because I see the alert but the form boxes are not getting populated:
#helper.input(testForm("var1")) { (id,name,value,args) => <input type="text" name="#name" id="#id" #toHtmlArgs(args)> }
innerHTML is used to get/set the body of an html tag, so you're probably ending up with this in the html:
<input ...>test</input>
I think this may work for a <textarea>, but for your <input type="text"> you want to set the value attribute.
document.getElementById('var1').value = test;
If you want to programmatically set an html form field via JS there are many ways to do this and many libraries out there that make it really easy.
Such as various JS two-way component template binding libraries.
For instance, you can simply do the following:
HTML:
<div id="myapp">
<input id="var1"/>
<button>Submit</button>
</div>
JS:
mag.module('myapp',{
view : function(state){
var test= 'tester';
state.button= {
_onclick:function(){
state.var1=test
}
}
}
});
Here is working example of the above example:
http://jsbin.com/ciregogaso/edit?html,js,output
Hope that helps!

How to collect form atrribute "name" and "value" into array from specific part of form using javascript?

how to collect form atrribute "name" and "value" into array from specific part of form using javascript?
I have a part of form like this:
<div class="multiPickerForm">
<input type="text" name="Id" value="1">
<input type="text" name="OrderNumber" value="SK4569">
<span class="multiPickerItemAddBtn"></span>
</div>
i need to read that part of form using javascript and create array of objects like.
var obj = { name:'OrderNumber', value:'SK4569' }
or something like that so i could loop it and access data easily from formated objects for further development.
Any advice would be highly apreciated. Thanks
This ought to do it:
var obj = [];
$("div.multiPickerForm :input").each(function () {
var tmpPair new Object();
tmpPair['name'] = $(this).attr('name');
tmpPair['value'] = = $(this).val();
obj.push(tmpPair);
});
console.log(obj);
You could use serializeArray() and it does exactly what you need
<div class="multiPickerForm">
<input type="text" name="Id" value="1">
<input type="text" name="OrderNumber" value="SK4569">
<span class="multiPickerItemAddBtn"> </span>
</div>
$('.multiPickerForm :input').serializeArray()
EDIT - You can use it on a form or on a subset of form elements, i updated my example. Taken from the documentation
This method can act on a jQuery object that has selected individual
form elements, such as <input>, <textarea>, and <select>. However, it
is typically easier to select the tag itself for serialization:
fiddle here http://jsfiddle.net/yffr5/
The controls in a form can be accessed using the elements collection. You can iterate over them to test if they are descendents of a div with class multiPickerForm.
If they are and they are sucessful, put them in the array as an object.

How can I create a dynamic form using jQuery

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.

Categories

Resources