Find your choices, find the value, add it and write its html text on the div

I have a simple choice, div variable and prepopulate.

Here is what I want to do:

I have a preopulate value, say:

prepop = 2; 

I want to find all the options in the select element, add the attribute selected to the option with a value of 2, and write “Val two” in the test div:

 <div id="test"></div> <select> <option value="1">Val one<option> <option value="2">Val two</option> </select> 

Any ideas how?

Here are my thoughts:

 var $options = "get all the select options"; $options.each(function(){ if (jQuery(this).val() == prepop){ jQuery('#test').html(jQuery(this).text()); } }); } 
0
source share
6 answers

I think this should do the trick:

 $(document).ready(function() { var prepop = 2; $('select').find('option').each(function() { if($(this).val() == prepop) { $('#test').html($(this).text()); } }); }); 

So what happens here, we iterate over all the “options” found under “select”. If the value of the current loop through "option" is equal to the variable pre population, we fill the div with the appropriate content.

+2
source
 $('select option').each(function(){ if ($(this).val() == prepop){ $(this).parent().val($(this).val()); $('#test').html($(this).text()); } }); 

See Example

+1
source

Just use this:

  $('select').val(prepop); 
+1
source

try it,

  $("#selectId > option").each(function() { if (this.value == prepop){ $('#test').html(this.text()); } }); 
0
source

Feels you like it:

 $(document).ready(function(){ var sel = document.getElementById('myselect'); sel.value = 2; $("#test").html( sel[sel.selectedIndex].text ); }); 

Test it here:

http://jsfiddle.net/3D44L/

0
source

// but use the identifier to select and extend the selector for options - in real use.

 var prepop = 2; $('select').val(prepop); $('#test').html($("option[value=" + prepop + "]").text()); 
0
source

Source: https://habr.com/ru/post/1210138/


All Articles