jQuery toggling disabled / enabled on a paired input

mauzilla picture mauzilla · Aug 31, 2012 · Viewed 10.8k times · Source

I have 2 paired input fields, and need to toggle enabled/disabled between them (if one is enabled the other should be disabled).

I have no idea how to approach this, any ideas?

Answer

Richard de Wit picture Richard de Wit · Aug 31, 2012

Example: the item1 is enabled, the item2 is disabled

<input type="text" id="item1">
<input type="text" id="item2" disabled>

<button id="switch">Click here to toggle</button>

This will toggle the items when some kind of switch is clicked. Use it on whatever toggles it, i.e. the button above:

$("#switch").on("click", function()
{
    $("#item1").prop("disabled", !$("#item1").prop("disabled"));
    $("#item2").prop("disabled", !$("#item2").prop("disabled"));
});

If you really want to make sure they're opposites;

$("#switch").on("click", function()
{
    var toggle = $("#item1").prop("disabled");

    $("#item1").prop("disabled", !toggle );
    $("#item2").prop("disabled", toggle ); // item2 will always be the opposite of item1
});