user3350885
user3350885

Reputation: 749

jQuery select box with respect to the change event

I have a dropdown that will change with respect to the first value (i.e from_value). What I'm trying to do is. There will be numbers from 1 to 10. So if the first value is selected as 2, then the second value (i.e to_value) should be populated with 2 to 10 in the dropdown.

Below is my code and I'm not sure to run the loop here. Could someone help me in running the loop and do my task.

In other words - If the first drop down is selected with value 2, then the second dropdown should populate with 2,3,4,5,6,7,8,9,10 If the first dropdown is selected with 8, then the second dropdown should show 8,9,10

$("#from_value").change(function(){
    var from_value = $("#from_value").val();
    $("div.to_value").html('<label>To Value</label><select name="to_value" id="to_value"><option>'+ from_value +'</option></select>');
});

Upvotes: 0

Views: 53

Answers (2)

Balachandran
Balachandran

Reputation: 9637

try

HTML

<select id="from_value">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
</select>
<select id="to_value">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
</select>

JS

$("#from_value").change(function () {
    var val = +this.value;
    $("#to_value option").hide();
    $("#to_value option:gt(" + val + "),#to_value option:eq(" + val + ")").show();
    $("#to_value").val(val);
});

DEMO

Upvotes: 1

phpsmashcode
phpsmashcode

Reputation: 746

Hope you are getting value in from_value. Then you could try this

$("#from_value").change(function() {
    var from_value = $("#from_value").val();
    var opts = '';
    for(var i = from_value; from_value <=10; i++)
    {
        opts = opts+'<option>' + i + '</option>';
    }
    $("div.to_value").html('<label>To Value</label><select name="to_value" id="to_value">' + opts + '</select>');
});

Upvotes: 1

Related Questions