[英]Find closest input and set value
On select value change I want find closest input by class and change value. 在选择值更改时,我希望按类找到最接近的输入并更改值。
JS JS
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#doc_service').on('change', function (){
$.getJSON('\/services\/search-service', {id: $(this).val()}, function(data){
$(this).closest('.price').val(data);
//$('.price').val(data);
});
});
});
</script>
My code $(this).closest('.price').val(data);
我的代码
$(this).closest('.price').val(data);
not changing value, I try $('.price').val(data);
不改变价值,我尝试
$('.price').val(data);
it's work, but I have many input and want change value only one closest. 这是工作,但我有很多输入,并希望更改值只有一个最接近。 Structure
html
is table
结构
html
是table
HTML HTML
<tr>
<td>
<select id="doc_service">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
<td>
<input type="text" class="price">
</td>
</tr>
<tr>
<td>
<select id="doc_service">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
<td>
<input type="text" class="price">
</td>
</tr>
this
in your code doesn't refer to the changed element, you should cache the object. this
在您的代码中没有引用更改的元素,您应该缓存该对象。 Also note that closest
method only selects the closest matching parent element. 另请注意,
closest
方法仅选择最接近的匹配父元素。
$('#doc_service').on('change', function (){
var _this = this;
$.getJSON('\/services\/search-service', {id: this.value }, function(data) {
$(_this).closest('td').next().find('.price').val(data);
});
});
And IDs must be unique, $('#doc_service')
only selects the first matching element, here classes should be used instead. 并且ID必须是唯一的,
$('#doc_service')
只选择第一个匹配的元素,这里应该使用类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.