Javascript 在追加时不显示输入字段

标签 javascript jquery ajax

我有简单的输入字段,例如:

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

相关文章:

javascript - 如何在另一个类中通过类名定位一个div

javascript - 专注于 jquery tokeninput 元素(Chrome 和 Opera)

php - 如何发送多个ajax请求?

javascript - excel的html表格不显示英镑货币符号

javascript - 动态向 Laravel 表单添加字段

javascript - 为什么 Firebase Auth 在登录时重新加载页面?

javascript - AngularJS $timeout 在计算值之前不等待 UI-Router 完成渲染

jquery - 在 Mustache.js 模板中创建一个可用的 jQuery 按钮

ajax - 第一次单击命令按钮不会重定向到另一个页面