Search code examples
ajaxlaravellabeljquery-selectbox

Changing select box value cannot applied in lables using ajax and jquery


In Laravel I have dynamically added multiple select box and labels using jquery. The Select Box values are coming from the database. Using Ajax depending on select box values the label's value (that also come from the database) has to be changed dynamically. It works but all label values are changing. I want to apply values to label only to the specific. Here I have to attach my code. Thanks in Advance.

Ajax code for changing select box value and apply results to label

$(document).on('change','.mySelect', function() {
     alert(this.value);
    var unit=this.value;

   var me=$(this);
$.ajax({
  type: "get",
  dataType:"json",
  url: "{{URL('newuphist/findunit')}}",
  data:{unit:unit},
  success: function(data){

   me.closest('.mySelect').find("#unitlbl").html(data['unit']);

  },

  error:function(){
   me.closest('.mySelect').find("#unitlbl").html("Error");

  }



});

HTML Code

    <div class="select">

     <select  class="mySelect" name="cat[]" >


        @foreach($data as $item)
           @component('compnew')
              @slot('opt')
               {{$item->diseaseName}}

               @endslot
            @endcomponent

        @endforeach

     </select> &nbsp &nbsp

    @component('comptxt')

    @endcomponent 
    &nbsp &nbsp

      @if(isset($res))

         <label   id="unitlbl" >{{$res}}</label>
         @else
            <label   id="unitlbl"></label>


    @endif     

  <br/>
</div>
</div>

enter image description here

enter image description here


Solution

  • You have to add label in same select box div .

     e.g
       <div class="select"> 
        <select class="mySelect">
             //code
        </select>
        <label id="myLabel"></label>
       </div>
    

    jquery code like

     $(document).on('change','.mySelect', function() {
        alert(this.value);
       var unit=this.value;
    
    var me = $(this); // add this 
    
    $.ajax({
      type: "get",
      dataType:"json",
      url: "{{URL('newuphist/findunit')}}",
      data:{unit:unit},
      success: function(data){
            me.closest('.select').find("#myLabel").html(data['unit']);
    
      },
    
      error:function(){
    
    $(".unitlbl").html("not get");   
    
      }
    
    });
    

    This will work for you dear .