I have simple HTML like this;
<div id="buildyourform"> <div class="row"> <div class="col-sm-6"> <div class="input-group mb-2"> <select class="form-control" id="language"> @foreach($language as $l) <option value="{{$l->id}}" >{{$l->name}}</option> @endforeach </select> </div> </div> <a href="javascript:void(0)" id="save-button" class="btn btn-light btn-sm "> <i class="fa fa-ban"></i> Upload </a> </div> </div> </div>
I have a plus button, using which I am appending the same fields below. Now I want to retrieve the respective selected language id with the click of the respective upload button. But every time it returns me the value of first select field.
Here is what I have tried;
$(document).on('click', '#save-button', function(){ var obj=$(this); //language = obj.closest("div[class=row]").find("select[id=language]").val(); language = $(this).parent().find("select[id=language]").val(); console.log(language); });
Can anyone let me know how to get respective selected language id on respective button click?
Advertisement
Answer
You need to use prev function and change select[id=xxxx] by select#language
$(document).on('click', '#save-button', function(){ var obj=$(this); //language = obj.closest("div[class=row]").find("select[id=language]").val(); language = $(this).prev('.col-sm-6').find("select#language").val(); console.log(language); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="buildyourform"> <div class="row"> <div class="col-sm-6"> <div class="input-group mb-2"> <select class="form-control" id="language"> @foreach($language as $l) <option value="{{$l->id}}" >{{$l->name}}</option> @endforeach </select> </div> </div> <a href="javascript:void(0)" id="save-button" class="btn btn-light btn-sm "> <i class="fa fa-ban"></i> Upload </a> </div> </div>