开发者

Using jquery, when I click on a link, how can I refer to a select dropdown right above it?

I have a link and I l开发者_运维问答isten to the click event. In the event handler, I want to validate that the user has actually made a choice on the select dropdown right above this link.

How can I get a reference to this select item relative to my link so I can validate it?

here is the html below. the event handler is on the click of the ".Next" link.

 <select class="dropdown" name="myDropdown">
 <option value="">Select Item . . .</option>
 <option value="1">1</option>
 <option value="2">2</option>
 </select>

 <br>
 <a id="Next3" class="Next" href="">Next</a>&nbsp;


Using JQuery, the most specific selector looks like:

var reference = $("#Next3").prevAll("select.dropdown[name='myDropdown']:first")[0];
var selectedAny = reference.value != "";

Explanation of code: $("#Next3") refers to the link with id="Next3" .prevAll() is a function which selects all previous elements according to a selector (justprev doesn't work).

select.dropdown[name='myDropdown']:first selects the first (closest) occurence of the selectelement, which class is dropdown and name equalsmyDropdown(case sensitive).


If the select is directly before the link then you can use prev http://api.jquery.com/prev/

If the HTML is more complicated then that you'll need to post it.


You can use sibling or parent selectors or a combination both but I would not recommend it since those kinds of selector tend to be fragile. When you change the structure of your html the selector might fail.

I think it would be better if you give your dropdown an id, then associate that id with the link using jquery.data().

Update: Given the html you posted, try using the closest() filter.

e.g. in your event handler:

function someEventHandler() {
  $(this).closest('select.dropdown')...
}

If the name is known or there is only one pair of link-dropdown you can just refer to the select by name then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜