简体   繁体   中英

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 listen 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;

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.

eg 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.

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.

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 (just prev doesn't work).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM