How to set the selected value of the selected window

I have one input field with variable width, like small, large, medium. I have a CSS style for this.

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 field select:

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

Now I need to check that the field inputhas a class smallor mediumor large and set the corresponding block selectas selected. In jQuery, I directly set the selected values ​​as medium, but still the dropdown shows small.

How to check if a field has inputany of these classes using a function hasClass()? Can we check it at a time?

+5
source share
3 answers

Use this

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

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

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

.hasClass() .

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

" jquery " medium ", "

jQuery, select id="1", :

$("#1").val("medium");  // or, obviously, use a variable instead of "medium"

id="1" , . html - id . , id, .

id jQuery, , . ( , , JS-, .)

+3

id html

. ,

var selectedOption="";
if($('.title').hasClass('small'))
{
  selectedOption='small';
}
else if($('.title').hasClass('medium'))
{
  selectedOption='medium';
}
else
{
  selectedOption='large';
}

//i am assuming you have only one select on your page, else replace it with id selector
$("select option[value="+selectedOption+"]")).prop('selected','true');  //setting the correct option as selected
+2
source

All Articles