简体   繁体   中英

Using jQuery, how do I get a specific dropdown element (<select></select>) based on the value of the dropdown?

I have a class of dropdowns --.selMapField -- and I want to select the dropdown that has a specific value. For instance:

const myattr=$(`.selMapField[value="MYSKU"]`).attr(`x`);

Use jQuery's .filter() to find the elements by value

 const myattr = $(".selMapField").filter((_, { value }) => value === "MYSKU").attr("x") console.log(myattr)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script> <select class="selMapField" x="A"><option selected>FOO</option></select> <select class="selMapField" x="B"><option selected>MYSKU</option></select> <select class="selMapField" x="C"><option selected>BAR</option></select>


As always, you might not need jQuery

 const myattr = Array.from( document.querySelectorAll(".selMapField") ).find(({ value }) => value === "MYSKU")?.getAttribute("x") console.log(myattr)
 <select class="selMapField" x="A"><option selected>FOO</option></select> <select class="selMapField" x="B"><option selected>MYSKU</option></select> <select class="selMapField" x="C"><option selected>BAR</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