Using jquery, what is the best way to get the “nex

2019-08-14 05:08发布

i have a bunch of repeating textboxes and comboboxes on an html page. I want to change the value of the textbox below the combobox when i change the combobox. So i have this code so far:

$('.myDropdown').change(function () {
    var currentDropdownValue = $(this).val(); 
    if (currentDropdownValue == "Regular") {
         //CHANGE TEXTBOX BELOW THIS COMBOBOX WITH CLASS = "QUANTITY" TO 10.
    }
});

here is my html

<select class="myDropdown">
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

<input class="quantity" type="text" />

basically, i need to figure out the right selector syntax as i was using "Closest()" but that seems to only go up the DOM tree and not past the current value.

3条回答
姐就是有狂的资本
2楼-- · 2019-08-14 05:22

You could use .next() to return the next item or pass it a selector if you are more picky.

$(this).next('.quantity').val(10);

No need for extra DOM Traversing like parent() or such.

Working JSFiddle: http://jsfiddle.net/CXzVe/2/.

查看更多
别忘想泡老子
3楼-- · 2019-08-14 05:28

If you happen to be updating your DOM after the initial load of the page, you'll need to use $.live() or $.delegate() because jQuery is not aware of the change.

JavaScript

$(".manufacturer").live("change", function () {
    var currentValue = $(this).val(); 
    if (currentValue && currentValue === "Regular") {
         $(".quantity").val("10");
    }
});

HTML

<select class="manufacturer">
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>
 <option value="mercedes">Mercedes</option>
 <option value="audi">Audi</option>
</select>

<input class="quantity" type="text" />
查看更多
我命由我不由天
4楼-- · 2019-08-14 05:36

You can try next():

$('.myDropdown').change(function () {
    var currentDropdownValue = $(this).val(); 
    if (currentDropdownValue == "Regular") {
         //CHANGE TEXTBOX BELOW THIS COMBOBOX WITH CLASS = "QUANTITY" TO 10.
        $(this).next('.quantity').val('10');
    }
});

You may need to jump around your HTML structure a bit if your input field isn't a sibling of your drop-down, such as $(this).parent().next('.quantity').val('10').

Edit: here's a jsFiddle for you.

查看更多
登录 后发表回答