jebmarcus jebmarcus - 1 year ago 71
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


<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 id="box2" name="letters">
<option value="a">A</option>
<option value="b">B</option>


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

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

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

cis cis
Answer Source

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") {
  } else {


Here is a link to a working demo:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download