JS getElementsByName with part of id as variable [duplicate] - javascript

Here is an example of my form (only inputs that I want, but there is many others):
<form name="inputform" action="..." method="post">
<input type="hidden" name="id_qtedje_77" id="id_qtedje_77" value="0">
<input type="text" id="id_qte_77" name="prestation_detail_fields[77][qte_collecte]" value="0.00">
<input type="text" id="id_rec_77" name="prestation_detail_fields[77][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_77" name="prestation_detail_fields[77][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[77][dechet_non_present]" value="1">
<!-- another TR -->
<input type="hidden" name="id_qtedje_108" id="id_qtedje_108" value="0">
<input type="text" id="id_qte_108" name="prestation_detail_fields[108][qte_collecte]" value="0.00">
<input type="text" id="id_rec_108" name="prestation_detail_fields[108][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_108" name="prestation_detail_fields[108][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[108][dechet_non_present]" value="1">
</form>
What I want is to get values of inputs, but as the form is built in PHP, I don't know the line identifier (77, 108).
Is there a way to do something like getElementByName('id_qtedje_%') ?
Note: I'm not using any library, and I don't plan to use one.

Your best bet is probably document.querySelectorAll, which you can use any CSS selector with, including an "attribute starts with" selector like input[id^="id_qtedje_"]. It's supported on all modern browsers, and also IE8:
var elements = document.querySelectorAll('input[id^="id_qtedje_"]');
If you wanted just the first match (rather than a list), you could use document.querySelector instead. It returns a reference to the first match in document order, or null if nothing matched.
Alternately, you could give the elements a class name, then use document.getElementsByClassName, but note that while getElementsByClassName was supported in old versions of Chrome and Firefox, IE8 doesn't have it, so it's not as well-supported as the more-useful querySelectorAll in the modern era.
var elements = document.getElementsByClassName("theClassName");
If you use any libraries (jQuery, MooTools, Closure, Prototype, etc.), they're likely to have a function you can use to look up elements by just about any CSS selector, filling the gaps in browser support with their own code. For instance, in jQuery, it's the $ (jQuery) function; in MooTools and Prototype, it's $$.

You can use the starts with selector in jQuery
var listOfElements = $('[name^="id_qtedje_"]')
You may also be interested with the contains and ends with selectors
Using querySelectorAll, you can do
document.querySelectorAll('[name^="id_qtedje_"]')
Alternatively:
Assuming that all elements are inputs, you may use this:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
return x[i];
}
}
}
which can be called as getElementByNameStart("id_qtedje_")
Note that this only returns the first element of this type. To return all:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
var a=[];
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
a.push(x[i])
}
}
return a;
}
If the elements are of any type, replace "input" with "*" (beware, this may make your code slow)

Related

Access and add fields with a button in HTML

This seems like it should be simple but I can't get it to work. The environment I am working in requires that I use NAME instead of ID, so I am making certain that all of my names are unique. I simply want to get two numbers from input fields, add them together and put the answer into a read only field.
<input type="number" name="first_num"></input>
<input type="number" name="second_num"></input>
<input type="number" name="sum_of_num" readonly></input>
<button name="perform_sum" onclick="document.getelementsbyname("sum_of_num")[0].value=(document.getelementsbyname("first_num")[0].value+document.getelementsbyname("second_num")[0].value)">Sum</button>
<input type="number" name="first_num"></input>
<input type="number" name="second_num"></input>
<input type="number" name="sum_of_num" readonly></input>
<button name="perform_sum" onclick="document.getElementsByName('sum_of_num')[0].value = (parseInt(document.getElementsByName('first_num')[0].value) + parseInt(document.getElementsByName('second_num')[0].value))">Sum</button>
getelementsbyname -> getElementsByName (javascript is case sensitive)
" -> ' (if you use double apex in html you have to slash your double apex in javascript or have to use single apex in javascript, or reverse)
.value is string, you need to convert it in int
You'll need to use single quotes, otherwise it thinks the attribute is closed. Also the functions are case-sensitive so it should be getElementsByName
from
<button name="perform_sum" onclick="document.getelementsbyname("sum_of_num")[0].value=(document.getelementsbyname("first_num")[0].value+document.getelementsbyname("second_num")[0].value)">Sum</button>
to
<button name="perform_sum" onclick="document.getElementsByName('sum_of_num')[0].value=(document.getElementsByName('first_num')[0].value+document.getElementsByName('second_num')[0].value)">Sum</button>
jQuery answer because it's the easiest (even though you didn't tag jQuery):
$("button").click(function () {
var first_num = Number($("input[name='first_num']").val());
var second_num = Number($("input[name='second_num']").val());
$("input[name='sum_of_num']").val(first_num + second_num);
});
jQuery makes it super simple to select by attributes such as name.
you have to use parseInt function else it will just concat two box values.

HTML collection structure same in all browsers

When you search elements using document.getElementsByTagName() we get a HTMLCollection. If elements have ids then output have elements with index and with id.
Question is, will this structure remain constant across all browser or will it change?
Example
(function() {
var inputs = document.getElementsByTagName("div")[0].children;
console.log(inputs);
})()
<div id="content">
<input type="text" id="input1" />
<input type="text" id="input2" />
<input type="text" id="input3" />
<input type="text" id="input4" />
</div>
If more than one elements matching the string used as an index, you can't rely on browsers doing this equal.
Browser compatibility
Different browsers behave differently when there
are more than one elements matching the string used as an index (or
namedItem's argument). Firefox 8 behaves as specified in DOM 2 and
DOM4, returning the first matching element. WebKit browsers and
Internet Explorer in this case return another HTMLCollection and Opera
returns a NodeList of all matching elements.
Src: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

Get the value of element using javascript by its class name

hi everyone I have an element like this :
<div class="price-box">
<span class="regular-price" id="product-price-27">
<span class="price">
...
</span>
</span>
</div>
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />
i have tried to get the value using this line
document.getElementByClassName('input-text qty').value="myvalue"
but that didn't work
how can I get the value without jquery?
note : I've included prototype.js in my project !
what about this one too :
<button type="button" title="Add to Cart" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span>Add to Cart</span></span></button>
I want to disable it using Javascript and by its class name !!!?
You might be looking for querySelector:
document.querySelector( ".input-text.qty" );
This returns a single item, rather than a NodeList. If you would like a NodeList instead, use the alternative querySelectorAll. Keep in mind that these methods take CSS Selectors. The selectors you can use are limited to the browser this code is executed in. Keep it simple.
These two methods have better browser support than getElementsByClassName, so I would encourage you to use them instead of taking your current approach.
Demo:
Since you are using Prototype in the page already, you may find this element using the "double-dollar" method:
$$('.input-text.qty');
As others have pointed out above, this returns an array of matched elements (or an empty array, if you don't have anything on the page that matches). So the easiest way to do anything to the result is with invoke():
$$('.input-text.qty').invoke('setValue', 'myvalue');
or
$$('.input-text.qty').invoke('disable');
Any of the Prototype Element methods can be invoked in this manner. If you want to do something custom to the element(s) based on some attribute, you can use each() instead:
$$('.input-text.qty').each(function(elm){
if (elm.frobber == 'froom') elm.remove();
});
Firstly, its getElementsByClassName (elements is plural) -- this will return an array of elements that satisfy the condition. You must specify the index of the array to modify the element properties:
document.getElementsByClassName('input-text qty')[0].value="myvalue"
You have id="qty" so forget class, just use
document.getElementById('qty').value = "myvalue";
Which is most efficient.
Other dom native methods like getElementsByClassName/TagName(note there are s after Element) returns an array like object NodeList.
You need to use index or loop to access it.
You error is that you using:
1) getElementByClassName instead of getElementsByClassName
2) getElementsByClassName returns array so you must get [0] element
So try this one:
var p = document.getElementsByClassName('input-text qty')
console.log(p[0])
p[0].value = "MyValue"
Demo
getElementByClassName() returns the array of matched elements, so to acces the first element of array use 0 index like
document.getElementsByClassName('input-text qty')[0].value="myvalue";
Or
You can use the id(qty) from input tag, and put the value on this tag by getElementById() something like
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />
document.getElementById('qty').value="myvalue";

Javascript get values of multiple text fields

I have a dynamic web page where the content may contain between 1 and 10 links, provided in text boxes, similar to the following:
<input size="50" id="link" value="http://Something.Something" type="text">
<input size="50" id="link" value="http://SomethingElse.Something" type="text">
I need javascript to be able to read all of the links, and be able to manipulate the data (store in array, output to screen, etc)
I know that I can read a single id using the following
var link = document.getElementById('link');
Which will return the first match - but, how can I do a loop or obtain all the values for all the links, bearing in mind that the number of links cannot be determined beforehand?
P.S. I have tried using getElementsByTagName('input') but there are more inputs on the page, which means it's getting more results than I'd like it to get.
You can make them all have names and search by name.
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
Then you can get it with:
var vrows = document.getElementsByName("vrow");
alert(vrows.length);
Give them all a common class and access using document.getElementsByClassName('class').
IDs should be unique for each element. You could use document.getElementsByClassName or document.querySelectorAll(".class"); and then use the class name (assuming relatively modern browser). Or use document.getElementsByTagName() and then iterate through the elements comparing with the class.
Attach a jQuery lib and you will be able to do something like:
$('input[type=text]').each(function(i, val){
alert($(this).val());
});

Get element by part of Name or ID

Here is an example of my form (only inputs that I want, but there is many others):
<form name="inputform" action="..." method="post">
<input type="hidden" name="id_qtedje_77" id="id_qtedje_77" value="0">
<input type="text" id="id_qte_77" name="prestation_detail_fields[77][qte_collecte]" value="0.00">
<input type="text" id="id_rec_77" name="prestation_detail_fields[77][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_77" name="prestation_detail_fields[77][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[77][dechet_non_present]" value="1">
<!-- another TR -->
<input type="hidden" name="id_qtedje_108" id="id_qtedje_108" value="0">
<input type="text" id="id_qte_108" name="prestation_detail_fields[108][qte_collecte]" value="0.00">
<input type="text" id="id_rec_108" name="prestation_detail_fields[108][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_108" name="prestation_detail_fields[108][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[108][dechet_non_present]" value="1">
</form>
What I want is to get values of inputs, but as the form is built in PHP, I don't know the line identifier (77, 108).
Is there a way to do something like getElementByName('id_qtedje_%') ?
Note: I'm not using any library, and I don't plan to use one.
Your best bet is probably document.querySelectorAll, which you can use any CSS selector with, including an "attribute starts with" selector like input[id^="id_qtedje_"]. It's supported on all modern browsers, and also IE8:
var elements = document.querySelectorAll('input[id^="id_qtedje_"]');
If you wanted just the first match (rather than a list), you could use document.querySelector instead. It returns a reference to the first match in document order, or null if nothing matched.
Alternately, you could give the elements a class name, then use document.getElementsByClassName, but note that while getElementsByClassName was supported in old versions of Chrome and Firefox, IE8 doesn't have it, so it's not as well-supported as the more-useful querySelectorAll in the modern era.
var elements = document.getElementsByClassName("theClassName");
If you use any libraries (jQuery, MooTools, Closure, Prototype, etc.), they're likely to have a function you can use to look up elements by just about any CSS selector, filling the gaps in browser support with their own code. For instance, in jQuery, it's the $ (jQuery) function; in MooTools and Prototype, it's $$.
You can use the starts with selector in jQuery
var listOfElements = $('[name^="id_qtedje_"]')
You may also be interested with the contains and ends with selectors
Using querySelectorAll, you can do
document.querySelectorAll('[name^="id_qtedje_"]')
Alternatively:
Assuming that all elements are inputs, you may use this:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
return x[i];
}
}
}
which can be called as getElementByNameStart("id_qtedje_")
Note that this only returns the first element of this type. To return all:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
var a=[];
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
a.push(x[i])
}
}
return a;
}
If the elements are of any type, replace "input" with "*" (beware, this may make your code slow)

Categories