jebmarcus jebmarcus - 4 months ago 10
HTML Question

Dynamic form with Javascript

I am making a simple dynamic form using pure Javascript. I have two dropdowns and want to make the second one appear only when certain options from the first one are selected

HTML:

<form class="form">
<div class="form-group">
<select id="box1" name="num">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

<select id="box2" name="letters">
<option value="a">A</option>
<option value="b">B</option>
</select>
</div>
</form>


Javascript:

<script type="text/javascript">
$("#box1").onchange = function () {
var box1 = document.getElementById("box1");
var value = box1.options[box1.selectedIndex].value;

if (value = "1" || value = "2") {
$("#box2").show();
} else {
$("#box2").hide();
}
};
</script>


But this is not working. How do I make this work?

cis cis
Answer

There are several problems. First, your event should be changed to this:

$("#box1").on('change', function () {

Next, your conditional logic was using a single '=', which assigns the value. This should be changed to a double or triple equals, which checks for equality. See the difference here: JavaScript performance difference between double equals (==) and triple equals (===).

  if (value = "1" || value = "2") {

Here is the final code:

$("#box1").on('change', function () {
  var value = $(this).val();

  if (value === "1" || value === "2") {
      $("#box2").show();
  } else {
      $("#box2").hide();
  }
});

Edit:

Here is a link to a working demo:

https://jsfiddle.net/pt5yyuLz/

Comments