Home > OS >  Pre select an option in a select box
Pre select an option in a select box

Time:05-13

i've got the following select box, I'd like to pre select news when the page is loaded,

<select type="text" name="cn_terms[category][]" id="cn_metabox_category"  multiple="" data-select2-id="cn_metabox_category" tabindex="-1" aria-hidden="true">
  <option value="32" data-select2-id="19">Community</option>
  <option value="85" data-select2-id="20">News</option>
  <option value="33" data-select2-id="21">Old News</option>
  <option value="1" data-select2-id="22">Uncategorized</option>
</select>

I've tried

$( document ).ready(function() {
$("#groupsel_0 option[value=85]").prop("selected", true);});    

and

$( document ).ready(function() {
  $("#cn_metabox_category").val("85");    
});

but neither seem to work.

CodePudding user response:

The second version works. Fire up the snippet.

$( document ).ready(function() {
  $("#cn_metabox_category").val("85");    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select type="text" name="cn_terms[category][]" id="cn_metabox_category"  multiple="" data-select2-id="cn_metabox_category" tabindex="-1" aria-hidden="true">
  <option value="32" data-select2-id="19">Community</option>
  <option value="85" data-select2-id="20">News</option>
  <option value="33" data-select2-id="21">Old News</option>
  <option value="1" data-select2-id="22">Uncategorized</option>
</select>

CodePudding user response:

When the page loads you can try this (you can put it in <body onl oad="//put code here">):

$("option[value='85']").attr('selected','selected');
  • Related