简体   繁体   中英

JQuery Set selected option

I have two selection boxes, the default value is - and i want to pick something else for both, my first problem is both fields have dynamic id like prod-685209-Size so i'm having trouble accessing with id.

I have the following HTML:

<select class="sku-attr" name="Size">
<option value="_def">-</option>
    <option value="S">S</option>
    <option value="M">M</option>
    <option value="L">L</option>
    <option value="XL">XL</option>
</select>

<select class="sku-attr" name="Color">
    <option value="_def">-</option>
    <option value="Black">Black</option>
    <option value="Blue">Blue</option>
</select>

So i executed the following:
document.getElementsByTagName('select')[0].selectedIndex = 2
document.getElementsByTagName('select')[1].selectedIndex = 2
It worked on the front side, showing my new options but it didn't prompt the backend as it is not actually selecting the options. Backend works fine when i click to these options by hand, basically i need another solution to choose these options.

If I don't misunderstood your requirement then you need something like this. Just add two different ids to your select element and attach a change event listener. For example size and color

 var s = document.getElementById("size"); var c = document.getElementById("color"); function getSize() { sizeSelected = s.value; console.log('size=' + sizeSelected); } function getColor() { colorSelected = c.value; console.log('color=' + colorSelected); } s.addEventListener('change', getSize); c.addEventListener('change', getColor); 
 <select id="size" class="sku-attr" name="Size"> <option value="_def">-</option> <option value="S">S</option> <option value="M">M</option> <option value="L">L</option> <option value="XL">XL</option> </select> <select id="color" class="sku-attr" name="Color"> <option value="_def">-</option> <option value="Black">Black</option> <option value="Blue">Blue</option> </select> 

您需要在dom命令之后添加.validate()才能真正提示页面。

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