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.
Related
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
I have a ID with special characters. I need to get the value of this input with JQUERY.
<input style="text-align:center; width:50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
<script>
function jq(str) {
var id = str.replace(/[%#;&,\.\+\#*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\\\$&');
var value = $("#"+id).val();
alert(value);
}
</script>
I try with this, but i dont have response in the alert.
Help! please!
Normally you can use jQuery's escape sequence in a selector, \\, to escape special characters. However that won't work in this case as the id you have specified in the element is invalid as it contains spaces.
Due to that you will have to use the attribute selector in jQuery to retrieve it:
var $el = $('[id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG"]');
console.log($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="text-align: center; width: 50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG">
A much better solution would be to fix the id of your elements before they are output in to the page to remove the spaces and special characters.
Get the answer from fiddle here
I have written in both javascript & jquery. There is an option fot trying // before every special character in ID, but that doesn't worked for me. So on the other way you can get the answer. Check & let me know.
$("#clickID").on('click', function(){
getVal = $(document.getElementById('adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG')).val();
console.log(getVal);
alert(getVal);
});
function jq(str) {
var element = document.getElementById("adhocGlobal_##HELLO DAVID%VSOP1240%6X0.7LFIG");
var value = $(element).val();
alert(value);
}
I want the value of last textbox to be grabbed by the varialble on multiple textbox with same ID.
HTML
<input type="text" id="get"><br>
<input type="text" id="get"><br>
<button id="grab">Click</button><br>
SCRIPT
$("#grab").click(function(){
var value = $("#get").val();
});
Or, a way to delete the first textbox might also work. Working Example
Your HTML is invalid: HTML elements can't have the same id attribute.
Use the class attribute, instead.
You can then use .last() to get the last element that matches the .get selector:
$("#grab").click(function(){
var value = $(".get").last().val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="get" value="foo"><br>
<input type="text" class="get" value="bar"><br>
<button id="grab">Click</button><br>
(I added the value attributes for demonstrative purposes. Obviously, they can be removed.)
If you want to get the first element's value if the second one is empty, you could do this:
$("#grab").click(function(){
var firstValue = $(".get").val(); // `.val()` gets the first element's value by default
var secondValue = $(".get").last().val();
var result = secondValue || firstValue;
alert(result);
});
If you don't have any control on ids you should use following solution. If you can change the ids you should change them.
You approach will not work because the id is not unique. It will always get the first input.
$("#grab").click(function() {
// var value = $(this).prev("input").val(); // Will work when there is no `<br>`
alert($('input[id="get"]').last().val());
});
Here $('input[id="get"]') will get all the elements having id get and last() will get the last element from it.
Demo: https://jsfiddle.net/orghoLzg/1/
So I'm using padolsey's regex filter to try and select dynamically generated nested form fields. Why do I keep getting an empty value for test in the selector code below?
jQuery.expr[':'].regex = function(elem, index, match) {
var matchParams = match[3].split(','),
validLabels = /^(data|css):/,
attr = {
method: matchParams[0].match(validLabels) ?
matchParams[0].split(':')[0] : 'attr',
property: matchParams.shift().replace(validLabels,'')
},
regexFlags = 'ig',
regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g,''), regexFlags);
return regex.test(jQuery(elem)[attr.method](attr.property));
}
//selector code
$(document).ready(function() {
var test = $('input:regex(id, agreement_activities_attributes_\d*_id)');
console.log(test);
});
html code that contains input field I'm trying to select
<input id="agreement_activities_attributes_0_id" name="agreement[activities_attributes][0][id]" type="hidden" value="28" />
There is an error in the code.
.replace(/^s+|s+$/g,'')
should be
.replace(/^\s+|\s+$/g,'')
Then it should work.
The replacement removes any surrounding whitespace (trims the string). The space you used in the selector (:regex(id, agreement_activities_attributes_\d*_id)) would be included in the match pattern, and thus only match elements with an id that started with space.
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.