Using jquery, what is the best way to get the “next” textbox with a specific class name

ε祈祈猫儿з 提交于 2019-12-24 08:27:09

问题


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.


回答1:


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




回答2:


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.




回答3:


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" />


来源:https://stackoverflow.com/questions/7155605/using-jquery-what-is-the-best-way-to-get-the-next-textbox-with-a-specific-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!