0

I have a javascript function that goes like this:

function change_one()
{
var one = document.getElementById("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"?

3 Answers 3

6

"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());
}
Sign up to request clarification or add additional context in comments.

4 Comments

oh, okay. so i should use "GetElementByClassName" instead of "GetElementById"?
@Lance, yes, getElementsByClassName. However, it's not completely cross-browser, so you'll probably want to use a library.
@Lance: Although all you need in theory is the DOM API, there's a lot of cross-browser weirdness (and vendor-specific optimizations available). It's much more productive to use a library like jQuery, Prototype, YUI, Closure, or any of several others which has already worked around a lot of it (and usually a lot more concise and feature-rich as well).
It's not as easy to select things in javascript by class with vanilla, so use jQuery. Then it's just $('.classname').value(one);
0

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.

1 Comment

The text boxes might be "independent" i.e. outside of any form, though iterating form elements might be more efficient than my way of getElementsByTagName
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.