Home > database >  How to pass selected attributes to dropdown in html using query
How to pass selected attributes to dropdown in html using query

Time:01-29

 <select    multiple="multiple" name="colors[]" id="color">
    <option value="" >choose color</option>
    <option value="black"   >Black</option>
    <option value="white" >White</option>
    <option  value="green" >Green</option>
    <option  value="red" >red</option>
  </select>

in this dropdown I want to pass selected attributes
eg:

<option  value="red" selected >red</option> 

using jquery and how to pass set multiple select

<option  value="red" selected >red</option> 
<option  value="white" selected >white</option> 

if my values of colors comes from a database like eg:yellow ,blue how to store to store in that database mycode : var colorstoadd=yellow ,blue

$("#color").find('input[type="select"]').append('<option value=' colorstoadd  'selected' '>' colorstoadd '</option>')

CodePudding user response:

If your data returned from database like "yellow , red , green";

You can use the next code

  • Split colors using .split(',')
  • Loop through the array of colors after split by using .each
  • Use .trim() to avoid any left/right white-spaces

let colorstoadd = "yellow , red , green";

$.each(colorstoadd.split(',') , (i , color) => {
  $("#color").append('<option value="' color.trim() '" selected>' color.trim() '</option>')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select    multiple="multiple" name="colors[]" id="color">
  <option value="" >choose color</option>
  <option value="black" >black</option>
</select>

Additional

  • To check the color already exists in the dropdown use if($("#color option[value='" color "']").length)
  • To add selected attribute $("#color option[value='" color "']").attr("selected" , true);

let colorstoadd = "yellow , red , green";

$.each(colorstoadd.split(',') , (i , color) => {
  if($("#color option[value='" color.trim() "']").length){
    $("#color option[value='" color.trim() "']").attr("selected" , true);
  }else{
    $("#color").append('<option value="' color.trim() '" selected>' color.trim() '</option>')
  }
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select    multiple="multiple" name="colors[]" id="color">
  <option value="" >choose color</option>
  <option value="black" >black</option>
  <option value="red" >RED</option>
</select>

  •  Tags:  
  • Related