Submit value of dynamically created checkboxes, with ajax - javascript

I've got about twenty checkboxes that are dynamically created with the following pattern:
<input type="checkbox" id="cb01" name="vehicle" />
I give it an ID of cb + index and a name attribute that corresponds to a database entry.
So over to my question:
Whats the best way to loop through the checkboxes performance wise? I need to send both the name and the value of the checkbox.
I would prefer the data as a jsonstring..

First, I'd give them all a common class. Let's say cb.
Then:
var json = {};
var checkboxes = document.querySelectorAll('.cb');
for ( var i = 0, l = checkboxes.length; i < l; i++ )
json[ checkboxes[i].name ] = checkboxes[i].checked;
Or with jQuery:
var json = {};
$('.cb').each(function(){
json[ this.name ] = this.checked;
});

Related

Accessing an element using id (JavaScript)

Scenario: I have a form element with id = "shipping_address"
Will all of the following work:
var i = document.shipping_address;
var i = window.shipping_address;
var i = shipping_address;
var i = document.forms.shipping_address;
var i = windows.forms.shipping_address;
var i = forms.shipping_address:
Thank you in advance!
Here is a running example:
var i = document.shipping_address;
console.log(i);
var i = window.shipping_address;
console.log(i);
var i = shipping_address;
console.log(i);
var i = document.forms.shipping_address;
console.log(i);
var i = windows.forms.shipping_address;
console.log(i);
var i = forms.shipping_address;
console.log(i);
<form id="shipping_address">
<input type='text'/>
</form>
Also I created a JSFiddle to help you.
https://jsfiddle.net/hszknwn9/1/
please notice you have what I think is a typo in the last line:var i =
forms.shipping_address:
the : should be a ;
I corrrected it in jsFiddle
You can try all of them on Codepen.io, but I would use only:
var i = document.getElementById("shipping_address");
And then access all the properties listed here according to what you need.
Those will not work.
If you are trying to assign the reference of your element with id="shipping_address", the correct way would be:
var i = document.getElementById("shipping_address");
To access the individual fields (and their respective contents) of that element, you need to first access the array of elements in your <form> element, and then iterate through:
var fields = i.elements;
var responses = [];
for(var j = 0; j < fields.length; j++) {
//perform actions on or with fields[j],
// such as responses.push(fields[j].value);
// which would put the value of each field
// of the form into the responses array.
}
The <form> element is a special container for grouping individual <input> elements, each of which should specify its input type. For example,
<form id="shipping_address">
<input type="text" placeholder="Street Address/P.O. box"></input>
<input type="text" placeholder="Town/City Name"></input>
<input type="text" placeholder="State/Country Name"></input>
<input type="text" placeholder="Zip Code (if applicable)"></input>
</form>
Which would create 4 input simple text fields from which inputs could be gathered. Putting all of this together, we can create a function that returns an array containing all of the values of the input fields in your shipping_address form element:
function getAddress() {
var i = document.getElementById("shipping_address");
var fields = i.elements;
var responses = [];
for(var j = 0; j < fields.length; j++) {
responses.push(fields[j].value);
return responses;
}
And from there on you can handle that data however you wish.
There are many more input types, I suggest you read the reference documentation at the w3schools html form reference, which provides acceptable documentation for most of the elements.
Hope this helps!
Use this to get value of a element by referencing ID of the element:
document.getElementById('shipping_address').value;

JavaScript creating array with input name and values

I was formulating this question:
Is it possible to make an array automatically from the .name and .value data used in all the inputs type text?
This is the reference doing manually:
var foo = [];
foo['bar'] = 'foo data';
foo['foo'] = 'bar data';
I got this idea... And it works...
var foo[];
for (var i = 0; i < document.getElementsByTagName('input').length; i++)
{
foo[document.getElementsByTagName("input")[i].name] = document.getElementsByTagName("input")[i].value;
};
The mission was to make it work automatically.
Get the .name of the input and get the .value of that input.
I was editing the question to post it here... When I figured out how to make it. I decided to leave here the reference, it'll be useful for someone, I guess.
Feedback is welcome.
Your code is reasonable enough, except for two things:
Use an object instead of an array.
Create the list of inputs only once.
So you could do:
var values = {};
var inputs = document.getElementsByTagName('input');
for( var i = 0; i < inputs.length; i++ ) {
values[inputs[i].name] = inputs[i].value;
}

Passing array of array elements to a function

I've been searching for an answer of this concept for a whole day and finally gave up and decided to ask it here.
Here's the concept:
I have a set of fields which are arrayed, I want that set of fields to be inside of array so that I can use a standard function for saving a module based on the fields involved and another param to check which to save.
Sample code:
module1.php
<?php
$i=0;
while($i<5){
?>
<input type="text" name="field1[$i]" />
<input type="text" name="field2[$i]" />
<input type="text" name="field3[$i]" />
<?php
$i++;
}
?>
<input type="button" name="process"
onclick="checkFields(['field1', 'field2', 'field3'], 'module1');" />
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn); //Output is 3
for(i=0; i<fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn); //Output should be 5
}
}
</script>
So, that part with comment is the thing I can't figure how to do, I tried using getElementById, getElementsByName but it's not working.
Or is there any possibility that I can pass an array of elements like this: array(field1, field2, field3) to a function?
Edit: I added a while loop statement to make the concept more comprehensive.
<script>
function checkFields(f, m){
var fn = f.length;
alert(fn);
for(i=0; i<=fn; i++){
var nfn = f[i].length; //Here's where it's not working
alert(nfn);
}
}
</script>
You should be applying the indexer on the f parameter, instead of the fn variable which is an integer.
fn is the length of your array, not your array. You should be using f
Change...
var nfn = fn[i].length; //Here's where it's not working
To...
var nfn = f[i];
Also, you will find that the for loop will fail, as i will reach fn but the array stops at fn-1
So change...
for(i=0; i<=fn; i++){
To...
for(i=0; i<fn; i++){
f[i] still points to just the incorrect input names. You don't really get access to the input field.
Do this:
var inputName = f[i] + "[]";//remember the input name is field1[] and not field1.
var value = document.querySelector( "input[name='"+inputName+"']" ).value;
the value here is just the input text of the input field and not really an array. If you have multiple fields with the same name, then use document.querySelectorAll method to get all the input fields and then iterate to get the values one by one.
To help you understand better, consider these 2 options:
Option 1:
html:
<input name="field1[]" />
<input name="field1[]" />
access the value:
var inputFields = document.querySelectorAll("input[name='field1[]']");
var values = [];
for (var j = 0; j < inputFields.length; j++) {
var val = inputFields[i].value;
values.push(val);
}
Option 2:
html:
<input name="field1[0]" />
<input name="field1[1]" />
access the value:
var values = [];
var j = 0;
var inputField;
while (true) {
var inputField = document.querySelector("input[name='field1[" + j + "]']");
if (!inputField) break;
values.push(inputField.value);
j++;
}
Note that, in option 1, there are multiple fields with the same "name" and in option 2, there are multiple fields with unique names.

Use array value as variable name

I need to use jQuery's keyup function to take the value from input html form elements and display said values in a div elsewhere.
The working code looks as follows:
$('#name').keyup(function() {
var name = $(this).val();
$('#name-in-document').html(name);
});
Since I have many identical instances of the above code block, I'd like to use a for loop to loop through an array of values. The catch is the name of the variable in the second line
var name = $(this).val();
would come from the array.
I have tried the following loop, which does not work because (as I understand it) a Javascript variable cannot be named an array value:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var inputsArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(inputsArray[i]);
})
};
So I have two questions:
Is it true that I cannot use the array values to create a variable in the for loop?
Is there an alternate way to accomplish the same thing (getting the variable names from the array) that might work?
I am just beginning JavaScript and really appreciate any insight. Thank you!
1. It is not true
2. You'll need to make a closure over the variable i or over the value from inputArray[i] and inside the event-bind the keyword this refers to the DOMNode witch triggers the event:
Read more absout closures here How do JavaScript closures work?
var inputsArray = ["phone", "name", "address"],
i = 0,
len = inputsArray.length;
for ( ; i < len; i ++ ) {
makeKeyupBind(inputsArray[i]);
}
function makeKeyupBind( value ) {
$("#" + value).on("keyup", function() {
$("#" + value + "-in-document").html( this.value );
});
}
That variable only exists within the scope of the function passed as a callback for the keyup event so I don't really see the need to give it a dynamic name; you could call it absolutely anything at all and not run into conflicts.
For the alternative approach, I would recommend giving #name (and his friends) a class name, e.g.
<input class="js-key-up" id="name" />
Then you can do away with the array and the for loop altogether. Also, adding new HTML elements would not require adding items to the array.
HTML
<input class="js-key-up" id="phone">
<input class="js-key-up" id="name">
<input class="js-key-up" id="address">
<p id="phone-in-document"></p>
<p id="name-in-document"></p>
<p id="address-in-document"></p>
JavaScript
​
$('.js-key-up').keyup(function (e) {
var id = $(this).attr('id');
$('#' + id + '-in-document').html($(this).val());
});​
I've created a jsfiddle with the code in.
Try this:
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var valuesArray[i] = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(valuesArray[i]);
})
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
$("#"+inputsArray[i]).keyup(function() {
var htmlValue = $(this).val();
$("#"+inputsArray[i]+"-in-document").html(htmlValue);
})
I think you don't need to name variable from array, do you?
You can build a selector straight from the array and skip the loop completely. Use the id of the current input to create the selector for the other element
var inputsArray = ["phone", "name", "address"];
$('#'+ inputsArray.join(',#') ).keyup(){
$('#'+this.id+"-in-document").html( $(this).val() );
})
This will create the selector:
$('#phone,#name,#address')
Above assumes that you are trying to find elements :
$("#phone-in-document").html(val);
$("#name-in-document").html(val);/* etc*/
#Wes Cossick: this line inside of the loop is wrong:
var valuesArray[i] = $(this).val();
if you want to do it that way declare the array before the loop. that is problem of OP
#diana: if i understand you correct, you want to add a dynamic keyup handler to every item in the array? if it is that way, that code should do it (dont reassign items in the array!) the trick is to create a closure (code is untested).
var inputsArray = ["phone", "name", "address"];
for (var i = 0; i < inputsArray.length; i++) {
(function(item) {
$("#"+item).keyup(function() {
$("#"+item+"-in-document").html($(this).val());
});
})(inputsArray[i]);
};
if you are using jQuery (and it seems so ;-), take a look at the each-function in jQuery: http://api.jquery.com/jQuery.each/
that should be a lot easier for you ;-)

get id of checked checkbox in gridview in javascript

I am having checkbox in each itemTemplate of asp:gridview
I want to get ids or values of those many selected checkboxes using only javascript
In pure javascript I'm not sure about platform portability: you'd REALLY want jQuery or some other helper library here.
With jQuery:
var values = [];
var ids = [];
jQuery.each(jQuery("input:checkbox").find(":checked"), function(){
values.push(jQuery(this).val());
ids.push(jQuery(this).attr("id");
});
will give you the ids and values of all the checked checkboxes.
EDIT: ugly, but this might work...
var values = [];
var ids = [];
var inputs = document.getElementsByTagName("input");
var i;
for(i=0;i<inputs.length;i++){
if(inputs[i].hasAttributes() && inputs.getAttribute('type') == "checkbox" && inputs.getAttribute('checked')){
values.push(inputs[i].getAttribute('value'));
ids.push(inputs[i].getAttribute('id'));
}
}
Let me know if that does what you want.
I am not exactly sure on what you are trying to do but this might help you out. This will get all of the inputs on the screen and process only the checked ones.
var inputList = document.getElementsByTagName("input");
var resultsArray = [];
for(var i = 0; i < inputList.length; i++) {
if (inputList[i].getAttribute("checked") == true) {
resultsArray.push(inputList[i]);
}
}
Sorry, forgot to tell you that this would be a list of elements. You will then need to extract them however you want to from resultsArray.

Categories

Resources