0

I was trying to add product details to table based on product name which can be collected from following input box.

 <input type="text"  autofocus class="form-control" id="productSearch"  placeholder="Product name"> 

But the problem is it can't empty the text box after adding the value and go to previous input box. How do i make it empty and focus only same input box?

 $( "#productSearch" ).change(function(event) {    
  $.ajax({
    type: "get",
    url: "{!! asset('searchByProductName') !!}",
    dataType: 'json',
    data: { name:this.value },
    success: function(response){
      if ($('#' + response.id).length !== 0) {
        return false; 
      }

     var markup = "<tr id="+response.id+"><input type='hidden' name='product_id[]'  value="+response.id+"><td><i class='flaticon-delete-1 delete-row' onclick='deleteRow(this)'></i></td><td>"+response.product_name+"</td><td>"+response.product_unit_price+"</td><td><input type='text' name='quantity[]' class='quantity' value='1'></td><td class='total'>"+response.product_unit_price+"</td><td>"+response.notes+"</td></tr>";

      $("table tbody").append(markup);      
      $(this).val(""); 
      return false; 
      event.preventDefault();
     }   
  }); 
});
Akhil Aravind
  • 5,741
  • 16
  • 35
Hola
  • 2,163
  • 8
  • 39
  • 87

1 Answers1

1

The problem lies in this as it doesn't refer to $("#productSearch"), because you use it inside a function. Since $("#productSearch") refers to a single element, you won't have any problems, if you use that in the place of $(this).

Alternatively, you can use event.target or context: this in $.ajax, as shown below:

$("#productSearch").change(function(event) {
     $.ajax({
         context: this,
         type: "get",
         url: "{!! asset('searchByProductName') !!}",
         dataType: 'json',
         data: {
             name: this.value
         },
         success: function(response) {
             //...
             $(this).val("");
         }
     });
 });
Angel Politis
  • 10,955
  • 14
  • 48
  • 66