I have a repeating table where the name of the elements would be (e.g. 'tdName_1' 'tdName_2'), and I was wondering if it would be possible to getElementsByName('tdName_').
PS: I can not use Jquery.
Thanks In advance.
Cesar.
This is not possible. I'm assuming for the rest of this answer that the elements you're interested in are <td>s. If so, then you should be aware that the name attribute is not valid for <td> elements.
You will have to create a list of matching elements manually. If you decide to use the name attribute anyway (instead of, say, adding a class in the class attribute), something like the following will work:
var table = document.getElementById("your_table_id");
var tds = table.getElementsByTagName("td");
var matchingTds = [];
for (var i = 0, len = tds.length, td, tdName; i < len; ++i) {
td = tds[i];
tdName = td.getAttribute("name");
if (tdName && tdName.indexOf("tdName_") == 0) {
matchingTds.push(td);
}
}
With vanilla javascript you can use the querySelectorAll method:
document.querySelectorAll('[name^=tdName]')
This should work in all modern browsers, including IE9 or later (though I haven't tested it yet).
Not easy or probably possible with getElementsByClassName but you can put JQuery at rescue:
$('td[name=tdName_1]') // matches exactly 'tdName_1'
$('td[name^=tdName]') // matches those that begin with 'tdName'
Obviously, not. But you can use getElementsByTagName() and then filter by name:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript"><!--
function find(){
var inputs = document.getElementById("foo").getElementsByTagName("input");
var found = [];
for(var i=0, len=inputs.length; i<len; i++){
if(inputs[i].name.match(/^tdName_\d+$/)){
found.push(inputs[i]);
}
}
alert(found.length + " elements found");
}
//--></script>
</head>
<body>
<form action="" method="post" id="foo">
<input type="text" name="tdName_1">
<input type="text" name="tdName_2">
<input type="text" name="tdName_3">
<input type="text" name="not_me">
<input type="text" name="tdName_4">
<input type="text" name="neither_me">
<input type="text" name="tdName_5">
<input type="button" onclick="find()" value="Find">
</form>
</body>
</html>
AFAIK, getElementsByName requires a static string as an argument.
I don't know if you have any control over the elements, but you should probably give them the same name and use getElementsByName.
Another solution would be to loop through names and use getElementByName('tdName_' + i).
No, you would have to fetch all relevant elements - e.g. using getElementsByTagName - and loop through them until you find one or more elements that fit your criteria.
Maybe you can work around using getElementsByClassName and give every element you want to match a certain class? (Update, the native version is not availalable on SO, thanks Andy E. This is a very popular workaround implementation.)
You say you can't use JQuery and I'm sure you have a good reason for that, but stuff like this is what Frameworks are there for. Would Prototype or MooTools be an option?
As Tim Down said, the name attribute is not valid for <td> elements. It should still work if you decide to use it though. One option is to use a while loop, like this:
function getAllNamedTDs ()
{
var cTD, i=1, elArr = [];
// If an element with "tdName_"+i is not found, exit the loop
while (cTD = document.getElementByName("tdName_"+(i++)))
elArr.push(cTD);
// return the array of elements or null if no elements were found.
return elArr.length ? elArr : null;
}
Instead of using the name attribute, you should use the id attribute and then replace getElementByName with getElementById
put TWO (2) names on each element you want to find... make the first class name the same on every element and the second class name 'tdName_1' or 'tdName_2' (or whatever). Run document.getElementsByClassName on the class name common to all your elements... then loop through the array, do className.split(' ') to get an array where array[0] is the common name and array[1] is the differentiated name, and... do what you need to ...
Related
need some help! am trying to get the value of the below input id "j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" and have tried jquery and javascript such as: document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63") but keep getting a null result. ID can't be changed either, any help appreciated
<td class="sf42_cell_bottom_light"><span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61"><input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417"></span></td>
Use this:
$("[id='j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61']")
By the way, since you are apperently using JSF, this is a good practice to set id to each component to avoid such horrible ids (who can changes if you add/remove components).
See more information in this thread:
Handling colon in element ID with jQuery
Do you have any control of the element? Can you add a class to it?
var val= document.getElementsByClassName("TheClassName");
Or you can get the TD with class sf42_cell_bottom_light (if it is unique) then get its INPUT elements by:
var theTd= document.getElementsByClassName("sf42_cell_bottom_light");
var val = theTD.getElementsByTagName("INPUT");
I need to see more of the HTML to give you an better answer.
You may need to escape colon in your id .So
try this
function RemoveInvalidCharacter(myid) {
return '#' + myid.replace(/(:|\.|\[|\])/g, "\\$1");
}
And call like this
$(RemoveInvalidCharacter('j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61'));
Have a look at How do I select an element by an ID that has characters used in CSS notation
I have tested this code:
<td class="sf42_cell_bottom_light">
<span id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id61">
<input id="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" maxlength="200" name="j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63" size="20" type="text" value="717474417">
</span>
</td>
<script type="text/javascript">
document.write(document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63").value);
</script>
in FF, IE, Chrome (the latest versions)... and seems to work ok... ar you sure it is about this id?
Replace:
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:3:j_id63")
with
document.getElementById("j_id0:j_id2:j_id4:j_id54:0:j_id59:0:j_id63")
The id is different.
http://jsfiddle.net/wNePW/
I have a field in my page named as "myField"
Now this is dynamic So there are 2 cases i.e. it can be just 1 field as;
<input type="text" name="myField" />
OR there can be 2 fields as below;
<input type="text" name="myField" />
<input type="hidden" name="myField" />
I use the following code to access the value in JS;
document.forms[0].myField[0].value
However, this does not work if there is only 1 field (as in the first case)
How do I write dynamic JS code to handle the same?
It should be cross browser compatible.
Yes, because in the first case you should use document.forms[0].myField.value.
I'd suggest to retrieve elements with getElementsByName() method:
var val = document.getElementsByName("myField")[0].value;
better way is to give a unique ID to each element and then get it with
document.getElementById(id).value
Have a look at JQuery, and here's some information on how to get the value out.
provided there is at least one element name "myField"
var count = document.forms[0].myField.length;
for(var i=0; i < count; i++){
// do something with document.forms[0].myField[i].value
console.log(document.forms[0].myField[i].value);
}
fiddle : http://jsfiddle.net/HtrrT/
I used the following code:
<html>
<head>
<script type="text/javascript" language="javascript">
function doit(page) {
var entry = page.entry;
var flag = false;
document.write(entry.length);
}
</script>
</head>
<body>
<span id="error_checkbox" style="color: blue;"> </span>
<form name="subscribeTablePage">
<input type="checkbox" id="entry" value="1"/> <label>1</label><br/>
<input type="button" value="Submit" onclick="doit(document.subscribeTablePage)"/>
</form>
</body>
</html>
Why is the value of entry.length undefined? At the same time when I tried with multiple checkboxes, the value of entry.length was the number of checkboxes used!
Use Case :
I am going to retrieve rows from Database and in that case I need to check the number of checkboxes checked to perform deletion operation !! Please give ur valuable comments to sort this problem
entry is id of your input
it should be name if you want to refer it in that way..
<input type="checkbox" name="entry" id="entry" value="1"/>
To access it form element by id you have to use
document.getElementById('idOfElement')
Also I dont find your objective for using length. you can get size of the input not length.
If you want to find number of checkboxes checked then probably in javascript you can check by writing a script as below
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true) {
count++;
}
}
You are trying to access the checkbox #entry. add the attribute name="entry" like so.
<input type="checkbox" id="entry" name="entry" value="1" />
Form objects are accessed by their name property.
As for the Javascript, you want value, not length.
document.write(entry.value);
length represents the length in characters of a given string.
Why is the value of entry.length undefined?
Because form.entry references the element, and the element doesn't have a length property. You want:
entry.value.length;
At the same time when I tried with multiple checkboxes, the value of entry.length was the number of checkboxes used!
Because if more than one form control has the same name, form.controlName references a collection of all the controls with the same name. HTML Collections have a length property that is the number of elements in the collection.
Also, the line:
> document.write(entry.length);
will clear the entire document, likely you want:
alert(entry.value.length);
// or
console.log(entry.value.length);
You may find it useful to read the entire section about forms in the HTML 5 specification, and also relevant parts of the HTML 4.01 standard.
I know that in jQuery you can use something like $(".cssClass") to get all elements with this class. However in plain html and javascript how do you group elements logically? For example:
<input id="fee1" data-id="1" data-group="Fees" type="text" value="$15.00"/>
<input id="fee2" data-id="2" data-group="Fees" type="text" value="$25.00"/>
<input id="fee3" data-id="3" data-group="Fees" type="text" value="$35.00"/>
I want to create a javascript function like this:
function GetByDataGroup(dataGroup){
/* returns something like [[1,"$15.00"],[2,"$25.00"],[3,"$35.00"]]*/
}
EDIT : Due to some political reasons I cant use jQuery or any framework..i know it doesnt make sense :)
In the case of form elements like you've given in your example, the <fieldset> is the logical grouper.
Your form can (and some might go as far as to say 'should') have many fieldsets breaking up your form into logical areas.
Once you have the relevant form fields divided up into the logical <fieldset>'s you can grab these using your Javascript either through a class/id on the fieldset, or some other selector (perhaps you're grabbing all fieldsets on the page etc).
This makes it a lot easier if you're using Plain Old Javascript rather than a framework to grab those items by some kind of id. Consider:
<fieldset id="contactDetails">
<input ... />
<input ... />
<input ... />
</fieldset>
Using your POJ you can get all of these from:
var contactDetails = document.getElementById('contactDetails');
Can you use another javascript framework? There are many: http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks
You could use something like this:
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag); // use "*" for all elements
var pattern = new RegExp('\\b'+searchClass+'\\b');
for (var i = 0; i < els.length; i++)
if ( pattern.test(els[i].className) )
classElements[classElements.length] = els[i];
return classElements;
}
(from here: http://www.dynamicdrive.com/forums/showthread.php?t=19294)
I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in
var special=(10000-health);
var health=(100);
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
this just writes "special" to the box, when I would like the value instead.
You have to set the value explicitly:
document.getElementById('special').value = special;
Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.
Update: Here is an example:
<body>
<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />
<script type="text/javascript">
var health = 100;
var special = 10000 - health;
document.getElementById('special').value = special;
</script>
</body>
References: getElementById, DOM
MDC's JavaScript Guide is also worth reading.
document.getElementById('special').value = special;
you have to use some kind of DOM manipulation. One of the more popular libraries is JQuery.
using jQuery you'd write something like
$('#special').val(special);
var input = document.getElementById('special');
input.value = special;