我有简单的输入字段,如:
<div class="col-md-3">
{{ Form::label('stock', 'Stock') }}
<input type="text" value="" class="stock form-control" name="stock" disabled>
</div>
此外,我还有JavaScript代码,后端工作正常,结果是成功200
<script type="text/javascript">
$(document).ready(function() {
$("select[name='product_id']").on("change", function() {
var productID = $(this).val();
if(productID) {
$.ajax({
url: "{{ url("admin/getProductInfo") }}/"+encodeURI(productID),
type: "GET",
dataType: "json",
success:function(data) {
$(".stock").empty().append("<input type='text' value='' class='form-control stock' name='stock' disabled>");
$.each(data, function(key, value) {
$(".stock").append("<input type='text' class='form-control stock' value="value['stock']" name='stock' disabled>");
});
}
}); //ajax
}else{
$(".stock").empty().append("<input type='text' value='' class='form-control stock' name='stock' disabled>");
}
});
});
</script>
我的问题是成功的
append
不会取代我的静态 输入
当我在select上使用相同的代码时,它可以工作但不知何故它对输入不起作用。
答案 0 :(得分:3)
您正在向输入添加输入,尝试将股票类添加到div并在其中添加子输入,如:
<div class="col-md-3 stock">
{{ Form::label('stock', 'Stock') }}
<input type="text" value="" class="form-control" name="stock" disabled>
</div>
$(document).ready(function() {
$("select[name='product_id']").on("change", function() {
var productID = $(this).val();
if(productID) {
$.ajax({
url: "{{ url("admin/getProductInfo") }}/"+encodeURI(productID),
type: "GET",
dataType: "json",
success:function(data) {
$(".stock").empty();
$.each(data, function(key, value) {
$(".stock").append("<input type='text' class='form-control' value='"+value['stock']+"' name='stock' disabled>");
});
}
}); //ajax
}else{
$(".stock").empty().append("<input type='text' value='' class='form-control' name='stock' disabled>");
}
});
});
如果数据只返回一个对象,请尝试:
$('.stock').val(''); //Just to follow what OP has earlier and no need of else statement again
if(productID){
//ajax stuff
success:function(data) {
//Clear the input's value
if(data.length > 0){
$(".stock input[type='text']").val(data[0].stock);
//data[0].stock will be good if its parsed json
}
}
}