简体   繁体   中英

Javascript not show input field on append

I have simple input field like:

<div class="col-md-3">
  {{ Form::label('stock', 'Stock') }}
  <input type="text" value="" class="stock form-control" name="stock" disabled>
</div>

And also I have JavaScript code which is working fine in back end and result is success 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.

same code goes when I use on select and it works but somehow it doesn't work for inputs.

You are appending input to input, try adding stock class to the div and append child inputs inside it like:

<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>");
      }
    });
  });

If data returns only one object, then try :

$('.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
          }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM