Mick Asgorther
Mick Asgorther

Reputation: 77

Get attribute with selector value

<input type="text" value="Here" id="aaa"> <br />
<span id="check">check</span>

$('#check').click(function(){
   alert($('input [value="Here"]').attr('id'));
})

http://jsfiddle.net/mHYsJ/

why this not working? How can i get attribute with selector VALUE?

Upvotes: 1

Views: 245

Answers (4)

JoniS
JoniS

Reputation: 97

Here is a useful function (taken from here) that gets all elements containing value for specified attribute:

var getAllElementsWithAttribute = function (attribute) {
    var matchingElements = [];
    var allElements = document.getElementsByTagName('*');
    for (var i = 0; i < allElements.length; i++) {
        if (allElements[i].getAttribute(attribute)) {
            matchingElements.push(allElements[i]);
        }
    }
    return matchingElements;
};

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227310

Remove the space in your selector.

$('input[value="Here"]').attr('id')

The space means "descendant of".

Upvotes: 2

Gabe
Gabe

Reputation: 50523

Remove the space should be:

alert($('input[value="Here"]').attr('id'));

Upvotes: 2

Ram
Ram

Reputation: 144739

You should not use space between the element and the attribute selector, currently your selector tries to find a element with attribute value='here' within the input element, try the following:

$('#check').click(function(){
   alert($('input[value="Here"]').attr('id'));
})

DEMO

Upvotes: 3

Related Questions