Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an input element by value using javascript?

People also ask

Can I get element by value in JavaScript?

Introduction to JavaScript getElementsByName() methodThe getElementsByName() accepts a name which is the value of the name attribute of elements and returns a live NodeList of elements. The return collection of elements is live.


with ie6-ie7-ie8

function getInputsByValue(value)
{
    var allInputs = document.getElementsByTagName("input");
    var results = [];
    for(var x=0;x<allInputs.length;x++)
        if(allInputs[x].value == value)
            results.push(allInputs[x]);
    return results;
}

with modern browsers ie9+ (? not sure for ie9 actually) :

document.querySelectorAll("input[value=something]");

You can use document.querySelectorAll() on modern browsers (https://developer.mozilla.org/En/DOM/Document.querySelectorAll), e.g.

var byValue = document.querySelectorAll('input[value="something"]');

For older browsers you'll have to iterate over the inputs and check the value, e.g.

var inputs = document.getElementsByTagName("input"),
    i,
    len,
    byVal = [],
    value = "something";

for (i = 0, len = inputs.length; i < len; i++) {
    if (inputs[i].value === value) {
        byVal.push(inputs[i]);
    }
}

Something like this works:

function getCheckboxByValue(v) {
        var inputs = document.getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {
                if(inputs[i].type == "checkbox" && inputs[i].value == v) {
                        return inputs[i];
                }
        }
        return false;
}
(function testCheckbox() {
        getCheckboxByValue("1").checked = true;
})();

Using jQuery would be much better, though.


var elems = [].filter.call( document.getElementsByTagName("input"), function( input ) {
    return input.value === "something";
});

http://jsfiddle.net/ts2Rr/3/