targetting form elements using array values in javascript - javascript

I have a small form in javascript with two Input values with the same class name. I know that you can target them by giving them ids but is there a way to target them using array values?
<td>
<input class="inputtextb" type="text" name="adults" maxlength="3"> Adults
<input class="inputtextb" type="text" name="children" maxlength="3"> Children above 5 years

You can use document.getElementsByClassName() for that:
var inputs = document.getElementsByClassName('inputtextb');
inputs[0] // the first input
inputs[1] // the second input
In case that doesn't work - can i use getElementsByClassName - you could iterate over all <input> elements using document.getElementsByName() and filter out the ones you want; or use jQuery ;-)

Use the following code:
var adults = document. getElementsByClassName('inputtextb')[0].value
var children = document. getElementsByClassName('inputtextb')[1].value
In Firefox 3, you can convert it into an Array and then call forEach on it:
var inputVals = document.getElementsByClassName("inputtextb");
var elsArray = Array.prototype.slice.call(inputVals, 0);
elsArray.forEach(function(el) {
console.log(el.tagName);
});
Note : It does not return an Array, it returns a NodeList objects.

Related

jQuery css selector match form array names

html
<input name="single">
<input name="multi[]">
<input name="multi[]">
<input name="multi_keys[my]">
<input name="multi_keys[key]">
jQuery
var match_single = $('[name="single"]');
var match_multi = $('[name="multi"]'); // No match
var match_multi_keys = $('[name="multi_keys"]'); // No match
console.log(match_single.length);
console.log(match_multi.length);
console.log(match_multi_keys.length);
It will only match match_single because the other selectors are not correct.
How can I make them match the form field arrays as well?
I could do this:
var match_multi = $('[name="multi[]"]');
but how can I match when there are keys inside and they are unknown? I would like to write it like this:
$('[name="multi_keys*');
You can use ^= which matches what an attribute starts with:
$('[name^="multi"]')
Note that this will match both name="multi[]" and name="multi_keys[]". If you wish to select multi[] and multi_keys[] separately, you can simply add the opening square bracket to that selector:
$('[name^="multi["]')
...and:
$('[name^="multi_keys["]')
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
– W3C's Selectors specification
use the * before the = like this $('[name*="multi"]');
var match_single = $('[name="single"]');
var match_multi = $('[name*="multi"]'); // No match
var match_multi_keys = $('[name*="multi_keys"]'); // No match
console.log(match_single.length);
console.log(match_multi.length);
console.log(match_multi_keys.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="single">
<input name="multi[]">
<input name="multi[]">
<input name="multi_keys[my]">
<input name="multi_keys[key]">
You can query these inputs by matching the prefix of the input names, like $('[name^=multi_keys]') so it will pick up elements which' name starts with multi_keys . But it is quite hacky.

Javascript set value for Form obeject Array

I am looking to add data to a form object which is an array.
This works fine:
<input type="text" name="object" value="">
<script>document.form.object.value = "value";</script>
But when the object is an array it's not working:
<input type="text" name="object[]" value="">
<script>document.form.object[0].value = "value";</script>
The value of the object is not changing.... Any idea?
I would like to loop the script so I need to create an array. Didn't find any solution...
Per example, I would utilize document.form.elements['object[]'].value = "value". Otherwise, if you intended on having multiple form elements with the same name (multiple inputs with object[], and iterate via the collection, can use the following:
var myForm = document.form;
var myControls = myForm.elements['object[]'];
for (var i = 0; i < myControls.length; i++) {
var aControl = myControls[i];
}
The example provided, in your code, the name provided is not perceived as an array.
The attribute value "object[]" is just a string to JavaScript -- it does not interpret that as an array. However, when brackets appear in a name, you cannot use it any more in the dot-notation, but must write:
document.form["object[]"].value = "value";
<form name="form">
<input type="text" name="object[]" value="">
</form>
If you have more than one element with name="object[]", then the above will only target the first one of these. To set the value of all those elements, you must loop. This you can (for instance) do with the elements property and Array.from to iterate over those elements:
Array.from(document.form.elements["object[]"], function(elem) {
elem.value = "value";
});
<form name="form">
<input type="text" name="object[]" value="">
<input type="text" name="object[]" value="">
</form>
For those using IE: replace Array.from with [].map.call

Putting element names in a list "[]" with Javascript

I want to put all input element names of a specific parent to a list with Jquery.
<form id="got">
<input name="jon">
<input name="oberyn">
<input name="tyrion">
</form>
var inputs = ["jon", "oberyn", "tyrion"];
So i can manipulate them with forEach.
How can i do that?
You could use .map method.
var inputs = $('#got').find('input').map(function() {
return $(this).attr('name');
}).get();
Try using arrays - jQuery .each().
Demo Fiddle
var arr = [];
$('#got input').each(function(){
arr.push($(this).prop('name')); //a simple way : arr.push(this.name);
console.log(arr);
});

How to get values of each input field using jquery having same name?

I am trying to get the values of each of the input field that are under same set. Below is my code:
Input field 1:
<input type="text" maxlength="255" name="amount[]" >
Input field 2:
<input type="text" maxlength="255" name="amount[]" >
and so on....the number of fields are variable.
Now I want to get the values the user typed in each of the field that is named . How to do that in jquery?
I have tried following code but it returns nothing:
$("input[name=amount[]]").val();
you can get all values in an array
var values = $('input[name="amount[]"]').map(function(){
return this.value;
}).get();
console.log(values);
Demo ---> http://jsfiddle.net/BFjp5/
Since there are multiple element with same name you need indexing:
$("input[name='amount[]']")[0].value;
Here is demo
and for getting all elements values:
$("input[name='amount[]']").each(function (i,v) {
alert(this.value);
});
Here is demo
by javascript
function getValues(){
var ids=document.getElementsByName('amount[]');
var ary=new Array();
for(var i=0;i<ids.length;i++){
ary[i]=ids[i].value;
}
return ary;
}
$("input[name='amount[]']")
This will get you a set of elements. You can get value of each of those elements by iterating over them.
$("input[name='amount[]']").each(function(){
$(this).val();
});
Try to pass the attribute value as a string since [ and ] are meta-characters,
var values = $("input[name='amount[]']")
.map(function(){ return $(this).val() })
.get().join('');
DEMO
You don't!
The whole point of ID's in the DOM is that they are unique.

Get values of all textboxes with same name attributes in jquery

I need to get values of all textboxes with same name attributes using jquery.
<input type="text" id="text1" name="text[]">
<input type="text" id="text2" name="text[]">
<input type="text" id="text3" name="text[]">
How can I get all values of textbox text[] and compare it using jquery.
I tried using
var values = $("input[name='text[]']")
.map(function(){return $(this).val();}).get();
but am no successful.
You can use map method and store the values into an array.
$(function(){
var values = $('input[name="text[]"]').map(function(){
return this.value
}).get()
})
http://jsfiddle.net/UugWW/
This one should work :
$('input[name="text[]"]');
You can loop on it to get all values.
$('input[name="text[]"]').each(function() {
alert($(this).val());
});
Let's split the requirement into smaller problems.
First you want to select all those inputs.
var $inputs = $("input[name='text[]']")
It returns a jQuery object, containing all the input named text[].
You also might not need to use square brackets into the name.
var inputs = $inputs.get();
Extract the matching elements into a plain Array, so that we can now access Array's prototype methods, such as Array.prototype.map.
var values = inputs.map(function takeValue(input) {
return input.value;
});
Use a selector like this:
$('input[type="text"][name="text[]"')
var textboxcount = document.getElementsByName("text").length;
var textvalue="";
for (var i = 0; i < textboxcount ; i++) {
textvalue= textvalue + document.getElementsByName("text").item(i).value;
}
alert(textvalue);

Categories