Skip to content Skip to sidebar Skip to footer

Selecting An Option Based On The Value Of Its Data Attribute

I want to choose (aka jQuery preselect) and set the value based on data variable. The list has 3 items having same values but differing data-d. Suppose I have variable selectvar='d

Solution 1:

Use below code and give id to your select.

$("#select2 option[data-id='" + selectvar + "']").prop("selected", true);

Solution 2:

Set the selected variable - then iterate over teh select list options and compare the data attribute - it the same - set selected property.

var selectvar = "d";


 $("#select2 option").each(function(){
     var id= $(this).attr('data-id');
    if(id === selectvar){ 
      $(this).prop('selected',true);
    }
 })
 
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="select2"><optiondata-id="mo"value="1">1</option><optiondata-id="d"value="2" >one</option><optiondata-id="h"value="3">o-ne</option></select>

Solution 3:

$("button").click(function() {
  var selectVal = $("input").val();
  
  $('[data-id="' + selectVal + '"]').prop("selected", true);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select><optiondata-id="mo"value="1"style="display: none;">1</option><optiondata-id="d"value="1"style="">one</option><optiondata-id="h"value="1">o-ne</option></select>
Data-id:<input/><button>Change</button>

Post a Comment for "Selecting An Option Based On The Value Of Its Data Attribute"