views:

142

answers:

6

Hello all,

How do I get the id of an input element based on its value? The values will always be unique and there are only 7 of them. I have tried this:

$('#wrapper').find("input[value='"+value+"']").each(function(){

            return this.id;

});

But nothing is returned!

Thanks all for any help

+1  A: 

You can solve this using a filter. Like this:

$('#wrapper input').filter(function() {
    return $(this).val() == value;
}).each(function() {
    return this.id;
});
tdolsen
+2  A: 

Try

$(this).id nope, this.id works, no need to create a jQuery object for the ID.

or

$(this).attr('id')

HTH

EDIT: This might work:

$('#wrapper').find("input[value='"+value+"']").attr('id');
DannyLane
`$(this).id` is not gonna work
meo
yup, you are right, have updated my answer to reflect that. Thx
DannyLane
Don't think the answer deserved to be marked down, but ok...
DannyLane
now that you have corrected it, it does not, but wrong untested/information = downvote, no ?
meo
Thats fair enough, although the answer did contain the correct info, albeit one option presented was wrong.
DannyLane
+2  A: 

your code is almost good:

$('#wrapper').find("input[value='"+value+"']").each(function(){
        return  $(this).attr("id") 
});

check here http://jsfiddle.net/5xsZt/

edit: i have just tested it with this.id it works to. Your code is right. Your error is somewhere else: check it: http://jsfiddle.net/5xsZt/3/

meo
A: 

Here's a version that will definitely work in all mainstream browsers:

function getInputWithValue(wrapper, value) {
    var inputs = wrapper.getElementsByTagName("input");
    var i = inputs.length;
    while (i--) {
        if (inputs[i].value === value) {
            return inputs[i];
        }
    }
    return null;
}

var wrapper = document.getElementById("wrapper");
var input = getInputWithValue(wrapper, "some value");
window.alert(input.id);
Tim Down
+4  A: 

You write return this.id;… Return where? You simply return value from anonymous functions and I don't see where you ever trying to use it. So the answer is:

var idYouAreSearchingFor = $('#wrapper').find("input[value='"+value+"']").attr('id');
nailxx
A: 
if ($('#wrapper').find("input[value='"+value+"']").length == 1) {   
  alert($('#wrapper').find("input[value='"+value+"']").attr('id'));
}
Salman A