avidaicu
avidaicu

Reputation: 27

jQuery, disable input once values are stored in the new section

I have 2 select lists mySelect and mySelect2. When one is selected if you click on the checkbox the other changes simultaneously.

Please check code below:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function displayResult() {
    if(document.form1.billingtoo.checked == true) {
        var x = document.getElementById("mySelect").selectedIndex;
        // Set selected index for mySelect2
        document.getElementById("mySelect2").selectedIndex = x;
   }
}

</script>
</head>
<body>

<form name="form1">
Select your favorite fruit:
    <select id="mySelect">
        <option>Apple</option>
        <option>Orange</option>
        <option>Pineapple</option>
        <option>Banana</option>
    </select>

    <br>

    <input type="checkbox" name="billingtoo" onclick="displayResult()">

    <br>

Select your favorite fruit 2:
    <select id="mySelect2">
        <option>Apple</option>
        <option>Orange</option>
        <option>Pineapple</option>
        <option>Banana</option>
    </select>

</form>
</body>
</html>

...how do I disable (grey out) mySelect2 so that you cannot make any changes any changes once the values are in place?

thanks.

Upvotes: 0

Views: 114

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

Not sure why your question is tagged "jQuery" when you're not using any, but still:

// with "plain" JS:
document.getElementById("mySelect2").disabled = true;

// with jQuery
$("#mySelect2").prop("disabled", true);

Either way set the disabled back to false to re-enable the control.

Here's one of many ways to rewrite your function with jQuery:

$(document).ready(function() {
    // bind the checkbox click handler here,
    // not in an inline onclick attribute:
    $('input[name="billingtoo"]').click(function() {
        var $mySelect2 = $("#mySelect2");
        // if checkbox is checked set the second select value to
        // the same as the first
        if (this.checked)
            $mySelect2.val( $("#mySelect").val() );
        // disable or re-enable select according to state of checkbox:
        $mySelect2.prop("disabled", this.checked);
    });
});

Demo: http://jsfiddle.net/nnnnnn/99TsC/

Upvotes: 6

Related Questions