Nate
Nate

Reputation: 28414

How to set one select box equal to another?

I have two identical select boxes (aside from their names, of course), and I need to have the value of the second select box be set equal to the value of the first when a checkbox is checked. Here's part of my code:

<form id="theForm" name="theForm">

<select name="stateSelect" id="stateSelect">
        <option value="AL">Alabama</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
</select>

<select name="stateSelect2" id="stateSelect2">
        <option value="AL">Alabama</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
</select>

<input type="checkbox" name="checky" onClick="doStuff()">
</form>

doStuff() 
{
    // change it from here
}

So, I've tried a bunch of different things, including code I've found on forums and on SO, but nothing seems to work. What code should I have in my javascript function so that when the function runs the second select box is set equal to the first?

Thanks for your help!

Upvotes: 0

Views: 1436

Answers (2)

Aaron
Aaron

Reputation: 5237

(Where #sel1 is the id of your first select, #sel2 is the id of your second select and #checkbox is the id of your checkbox:)

$('#checkbox').click(function(){
    if ($('#sel2').attr('disabled') != 'disabled') {
        $('#sel2').attr('disabled', 'disabled');
        $('#sel2').val($('#sel1').val());}     
    else
        $('#sel2').removeAttr('disabled');
});
    $('#sel1').change(function(){
    if ($('#sel2').attr('disabled') == 'disabled')
        $('#sel2').val($(this).val());
});

See http://jsfiddle.net/u4n7n/

Upvotes: 0

stewe
stewe

Reputation: 42644

Try this:

var s1=document.getElementById('stateSelect');
var s2=document.getElementById('stateSelect2');
s1.onchange=function(){
    s2.value=s1.value;
}

Demo: http://jsfiddle.net/rLEvD/

Upvotes: 3

Related Questions