How to set select box selected value

kamala picture kamala · Sep 15, 2012 · Viewed 24.2k times · Source

I have one input field with variable width like small, large, medium. I have CSS styling for that.

Example:

case 1: <input type="text" id="a1" class="title small required" />
case 2: <input type="text" id="a1" class="title medium" />
case 3: <input type="text" id="a1" class="title large required" />

Meanwhile I have a select box:

<select id="b1">
    <option value="small">Small</option>
    <option value="medium">Medium</option>
    <option value="large">Large</option>
</select>

What I require now is to check the input field has class of small or medium or large and to set the relevant select box as selected. In jQuery I have directly set the selected values as medium, but still the drop-down shows small.

How do I check whether the input field has any of these classes using the hasClass() function? Are we able to check for this one at a time?

Answer

Parthi04 picture Parthi04 · Sep 15, 2012

Use this

$('#b1').val("small"); // to set small as selected

$('#b1').val("medium");

$('#b1').val("large");

Use .hasClass() for the next one.

var size = $("#al").hasClass('small')? 'small':
  ($("#a1").hasClass('medium')? 'medium' :
  ($("#a1").hasClass('large')? large :' null')); 
alert(size);