How to select option if value contains string

Viewed 876

I need to select option if value contains particular string.

<select>
    <option value="sunday,1523">Sunday</option>
    <option value="monday,1583">Monday</option>
</select>

Need to select option contains 1583 value. I tried, but not working.

$("select option:contains(1583)").prop("selected","selected")
5 Answers

Vanilla JS solution using Array.prototype.filter:

var options = Array.from(document.querySelectorAll("select option"))
options.filter(option => option.value.includes("1583"))[0].selected = true;
<select>
  <option value="sunday,1523">Sunday</option>
  <option value="monday,1583">Monday</option>
</select>

You can also use JavaScript's built-in includes() method.

let select = document.querySelector("select");

for(let i=0; i<select.options.length; i++){
    if(select.options[i].value.includes('1583')){
    select.options[i].selected = true;
  }
}
<select>
    <option value="sunday,1523">Sunday</option>
    <option value="monday,1583">Monday</option>
</select>

Use the Attribute selector [value] that ends with $=

const num = "1583";

$(`option[value$="${num}"]`).prop("selected", true);
<select>
  <option value="sunday,1523">Sunday</option>
  <option value="monday,1583">Monday</option>
</select>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

//if contain specific word '1583'
$("select option[value~='1583']").prop("selected", true)

//if contain word '1583'
$("select option[value*='1583']).prop("selected", true)

//if ending with '1583'
$("select option[value$='1583']).prop("selected", true)

Remember, the difference between prop() and attr() eg:prop("selected", true), attr("selected", "selected")

Related