Chris Chong
Chris Chong

Reputation: 187

Change select box on input range change

I want to know how to change the selected option on select box on range change, like, if value 1 of range, select the first option, and value 2 the second and so on

<input type="range" min="1" max="3" step="1" data-rangeslider/>
<select id="price-leval" name="price_leval">
<option value="first" id="asdasd">1st level</option>
    <option value="second" id="asdasd">2nd level</option>
    <option value="third" id="asdasd">3rd level</option>
</select>

I need the option values stay as value="first" second and third.

Upvotes: 0

Views: 1471

Answers (3)

Tejasva Dhyani
Tejasva Dhyani

Reputation: 1362

The problem can be solved using a custom attribute say 'label'

<select id="price-leval" name="price_leval">
    <option value="first" label='1'>1st level</option>
    <option value="second" label='2'>2nd level</option>
    <option value="third" label='3'>3rd level</option>
</select>

and then accessing the value of the option using the label

$("input[type=range]").on('change', function(){
    var value = $("select#price-leval>option[label='"+$(this).val()+"']").attr("value");
    $("select").val(value);
});

Upvotes: 0

Fseee
Fseee

Reputation: 2627

Here's my working solution:

HTML

<input id="range" type="range" min="1" max="3" step="1">
<select id="price-leval" name="price_leval">
   <option value="first" id="opt1">1st level</option>
   <option value="second" id="opt2">2nd level</option>
   <option value="third" id="opt3">3rd level</option>
</select>`

SCRIPT

 $("#range").mousemove( function(e){      
    $("#price-leval").val(decodeNumber($(this).val()));
 });

function decodeNumber(number){
if(number=="1"){
return "first";
}
if(number=="2"){
return "second";
}
if(number=="3"){
return "third";
}

}

Make sure jquery is loaded in your page Here's the fiddle

WARNING It's not a good practice in my opinion to have a string instead of number in option value

Upvotes: 0

Bla...
Bla...

Reputation: 7288

EDIT: Check out this Fiddle.

HTML

<select>
    <option value="1" id="asdasd">Первый уровен</option>
    <option value="2" id="asdasd">wqe</option>
    <option value="3" id="asdasd">asd</option>
</select>

jQuery

$("input[type=range]").on('change', function(){
    $("select").val($(this).val());
});

If you don't want to change the value then use this:

$("input[type=range]").on('change', function(){
    $('select :nth-child('+$(this).val()+')').prop('selected', true);
});

Upvotes: 1

Related Questions