Question

Perhaps I have been looking at this too much, but how come the id of the select tag is not alerted...??

here is the code I was playing with:

<select id="one">
    <option>an option</option>
    <option>another option</option>
</select>

<button id="btn" >look a button</button>

$("#btn").click(function() {
    var c = $(this).closest(".one").id;
    alert(c);
});

that is the hmtl and the javascript...should be an easy one...

Was it helpful?

Solution 2

closest() used to get the first ancestor element that matches your selector. You need prev() or siblings() here:

var c = $(this).prev().attr('id');

or:

var c = $(this).siblings("#one").attr('id');

since select is the previous element or sibling of your button in this case

OTHER TIPS

closest() returns the closest ancestor element matching the given selector, in your case it is the previous sibling so use .prev().

But those jQuery traversal method returns a jQuery object which does not have the id property so read the id attribute value using .attr()

$("#btn").click(function() {
    var c = $(this).prev("#one").attr('id');//as @Felix pointed out one is the id not a class
    //since you have an id for the select element you can use an id selector
    // like c = $('#one').val();
    alert(c);
});

Because all jQuery selectors return jQuery objects, onto which additional jQuery methods can be chained. If you want to access the raw element, you can use [0]:

$("#btn").click(function() {
    var c = $(this).closest(".one")[0].id;
    alert(c);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top