jQuery toggling disabled / enabled on a paired input

10,966

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
});
Share:
10,966
mauzilla
Author by

mauzilla

DevOps Manager at intellihost

Updated on June 04, 2022

Comments

  • mauzilla
    mauzilla almost 2 years

    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?

  • mauzilla
    mauzilla over 11 years
    Hey @GeenHenk, thanks for this. This would work but I do not have a toggle button, I have specific times within my script I turn them on and off, so I need a way to toggle it automatically if the other one of the pair is changed (so if anyone changes, do the opposite on the other one)
  • Smamatti
    Smamatti over 11 years
    Then use for example focusin/out to enable/disable the other element and vice versa. $("#item1").focusin(function() { $("#item2").prop("disabled", "disabled"); }); -- api.jquery.com/focusout
  • Richard de Wit
    Richard de Wit over 11 years
    @MauritzSwanepoel, you can make this in like function toggleDisable() and when the disabling occurs in your code, you can then call to this function as well. I suppose there is somewhere where one of the 2 gets disabled