我有简单的输入字段,例如:
<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>
My problem is that
append
on success will not replace with my static input.
当我在选择上使用时,相同的代码可以工作,但不知何故它不适用于输入。
最佳答案
您要将输入附加到输入,请尝试将 stock 类添加到 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
}
}
}
关于Javascript 在追加时不显示输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48698455/