简体   繁体   中英

Get text of option before the currently selected option of a dropdown

I'm working on a form where I need to validate a textbox field is between the currently selected dropdown item, and the item immediately before the selected.

Example Dropdown:

<select>Select</option>
  <option value="57">25</option>
  <option value="58">28</option>
  <option value="59" selected>30</option>
  <option value="60">32</option>
  <option value="61">33</option>
  <option value="62">35</option>
</select>

Given the selected item, 59, I need jquery to give me the value for the previous item, in this case 58. Note this is just an example, the values are not always sequential like this.

I can easily get the item after the selected item in jQuery using:

$("#SealShaftSizeID option:selected + option").text();

I am unable to find some jQuery to do the reverse of that.

You can resolve like this:

 $("option[selected]").prev().css( "background-color", "red" ); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <select> <option>1</option> <option selected>2</option> <option>3</option> </select> 

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