Tanveer
Tanveer

Reputation: 2107

jQuery getting selected option of dynamically rendered dropdown list

I am working on an MVC + jQuery project, I am creating dropdown list on runtime. After rendering while submitting form through jQuery, I am trying to get selected value. Drop down is rendered and working fine

enter image description here

Also I can check in source code. I am trying to get dropdown list by

 $('#Monday_Periods').children('.PeriodRow').each(function () {

    var elements = $(this).html();
    var found = $('.Subject', elements);           

});

I found all objects in variable found, and I can see it in Chrome debug

enter image description here

But after this I am unable to get selected value. As you can see in debug mode that no option is selected. I tried to get by val or text but no luck. Anybody can tell me that how I can get selected value

Upvotes: 3

Views: 2196

Answers (1)

squaleLis
squaleLis

Reputation: 6484

$(this).html(); is loosing the reference to the DOM (html() returns a String, not a DOM node).

Try to modify in:

var elements = $(this);
var found = $('.Subject', elements);
found.each(function(el){
   console.log($(this).val());
}           

or use directly (you already have an id on it!):

$('#subject1').val(); 

EDIT: SNIPPET ADDED

function printResults(){
  $('#Monday_Periods').children('.PeriodRow').each(function () {

      var elements = $(this);
      var found = $('.Subject', elements);
      found.each(function(el){
         console.log($(this).val());
      });           
    
  });
}

$('#print-results').click(printResults);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form id="Monday_Periods">
  <div class="PeriodRow">
    <select class="Subject">
      <option value="none">-- Select Subject --</option>
      <option value="1">Biology</option>
      <option value="2">Physics</option>
    </select>
    
    <select class="Subject">
      <option value="none">-- Select Subject --</option>
      <option value="1">Biology</option>
      <option value="2">Physics</option>
    </select>

  </div>
  <button type="button" id="print-results">PRINT RESULTS</button> 
</form>

Upvotes: 1

Related Questions