1
votes

I'm trying to enable another input field if the user selects the Other option from the dropdown and I have tried to add a state to the input field which is set to true/false depending on the value selected from the dropdown but I am not able to view the input option when I select other.

const [designation, setDesignation] = useState("");
const [showOption, setShowOption] = useState(false);

<div className="field">
  <label className="label">Designation</label>
  <div className="control ">
    <select
      className="input"
      id="designation"
      name="Your Designation"
      value={designation}
      type="text"
      onChange={(e) => {
        setDesignation(e.target.value);
        if (value == "3") setShowOption(true);
        else setShowOption(false);
      }}
      placeholder="Your Designation"
      required
    >
      <option value="1">Product Manager</option>
      <option value="2">Developer</option>
      <option value="3">Other</option>
    </select>
  </div>
</div>;
{
  showOption ? (
    <div className="field">
      <label className="label">Designation</label>
      <div className="control ">
        <input
          className="input"
          id="designation"
          value={designation}
          type="text"
          onChange={(e) => setDesignation(e.target.value)}
          placeholder="Your Designation"
          required
        />
      </div>
    </div>
  ) : (
    ""
  );
}
1
In select where you have put a condition to check if value == "3", is there any value being received? I assume it's null because value is not defined anywhereseem7teen
Then how will the get pick a particular option in my if statement if not by valueCassandra
Your onChange needs to look at the event rather than the designation. Currently it only evaluates the designationJustDebuggin

1 Answers

7
votes

You have to change onchange function like this.

onChange={(e) => {
  setDesignation(e.target.value);
  if (e.target.value == "3") setShowOption(true);
  else setShowOption(false);
}}

And some minor changes in HTML part.

{
  showOption && <div className="field">
    <label className="label">Designation</label>
    <div className="control ">
      <input
        className="input"
        id="designation"
        value={designation}
        type="text"
        onChange={(e) => setDesignation(e.target.value)}
        placeholder="Your Designation"
        required
      />
    </div>
  </div>
}

It works on my end. Please have a try and let me know if it works or not.