Home > Back-end >  Change input to disabled after other input is selected
Change input to disabled after other input is selected

Time:11-24

Here's my code

<form>
    <select name="foo">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>
    <input name="input1" type="text">
    <input name="input2" type="text">
    <input name="input3" type="text">
</form>

What I need to happen is when I select Option 1, input1 needs to be disabled. How can I do this with javascript?

CodePudding user response:

You can use the selectedIndex of the select

const inputs = document.querySelectorAll("input");

document.querySelector("[name=foo]")
  .addEventListener("input", function(e) {
    const idx = this.selectedIndex - 1;
    inputs.forEach((input, i) => input.disabled = i === idx);
  });
<form>
  <select name="foo">
    <option>---</option>
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
  </select>
  <input id="input1" name="input1" type="text">
  <input id="input2" name="input2" type="text">
  <input id="input3" name="input3" type="text">
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

How about something like this? Add an event listener to the input event on select element, and use a switch or if statement to change the desired element.

document.querySelector("select")
  .addEventListener("input", e => {
    const inputs = document.querySelectorAll("input");
    inputs.forEach(input => input.disabled = false);
    const [in1, in2, in3] = inputs;
    switch (e.target.value) {
      case "option1":
        in1.disabled = true;
        break;
      case "option2":
        in2.disabled = true;
        break;
      case "option3":
        in3.disabled = true;
        break;
    }
  });
<form>
  <select name="foo">
    <option>---</option>
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
  </select>
  <input id="input1" name="input1" type="text">
  <input id="input2" name="input2" type="text">
  <input id="input3" name="input3" type="text">
</form>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

There are lots of ways to do what you are looking for. You can try this.

You can add a CommonClass to each input.

$( "CommonClass" ).click(function() {

// disable all elememts
    $("form").each(function(){
        $(this).prop("disabled", true)
    });

// remove disabled attribute from currunt clicked element
  $(this).removeAttr("disabled");

//fetch value of the currently selected element.
  var selected_Val = $(this).val();
//use value anywhere.

});
  • Related