I have a javascript function that goes like this:
function change_one()
{
var one = document.getE开发者_如何学PythonlementById("one").value;
document.getElementById("tag").value=one;
}
It works fine until there are two elements the same id.
I'm using php to fetch stuff from mysql and while it's looping thru, it's echoing input tags that have the same id value.
How I get this javascript code to apply to all of the input tags that have the id equal to "one"?
"It works fine until there are two elements the same id."
That's completely invalid. The best solution is change the PHP code to use classes, or another way to distinguish. You may find it helpful to use a JavaScript library to find elements matching that class.
EDIT: Using jQuery, with tag
and one
classes:
function change_one()
{
$(".tag").val($(".one").val());
}
It works correctly even then not fine :)
id
attribute is for unique identifier, therefore your page with input tags that have the same id cannot pass validation. As workaround you can loop thru document.forms.elements
collections.
I agree that it's better to have valid HTML but life can sometimes be unfair and sometimes we must break some rules to achieve something.
So to answer the original question here, here is code that will "support" more than one input with same ID and simply append their values:
var arrInputs = document.getElementsByTagName("input");
var one = "";
for (var i = 0; i < arrInputs.length; i++) {
var oCurInput = arrInputs[i];
if (oCurInput.id == "one")
one += oCurInput.value;
}
document.getElementById("tag").value=one;
Again, if possible fix the core of the problem by using "class" instead of "id" but if for some reason it's not an option, use the above code.
精彩评论