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

110 Views Asked by At

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

2

There are 2 best solutions below

4
Affan On BEST ANSWER

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 .

1
AudioBubble On

Try this:

$(document).on('change','select', function() {
    var lbl = $(this).parents('div.select').find('#unitlbl');
    /* TO DO */
});

and use lbl.html() or lbl.text() to update text.