0

I am trying to write a JavaScript function where if value 1 from the first dropdown(pcount) automatically selects value 1 for drop down 2(listedname), But then if anything besides value 1 (2,3,4) is chosen I do not want drop down 2 to do anything except default back to please select if value 1 was selected and then changed to another value. I am very new to JavaScript and programming in general and have not been able to find any examples similar to this. So any help will help!

JavaScript Funtion:

<script type="text/javascript">
function leaveChange() {
    if (document.getElementById("pcount").value = 1){
        document.getElementById("listedname").value = 1;
    }else
        document.getElementById("listedname").value = 2;

    }
}
</script>

Dropdown 1 and 2:

<select id="pcount" onchange="leaveChange()">
  <option value="" selected="selected">Please Select</option>
  <option value="1">0</option>
  <option value="2">1</option>
  <option value="3">2</option>
  <option value="4">3</option>
</select>

<select id="listedname">
  <option value="" selected="selected">Please Select</option>
  <option value="1">Business Name</option>
  <option value="2">Individual Owner</option>
</select>
Tim Nikischin
  • 368
  • 1
  • 18

2 Answers2

5

If you are doing your if clause with one equals sign, Javascript will check if your element is set to the new value successfully.

Instead, when you do a comparison, use double equal signs (in your case)

if (document.getElementById("pcount").value == 1){
Tim Nikischin
  • 368
  • 1
  • 18
javisrk
  • 582
  • 4
  • 19
  • 1
    Indeed, also use tripe equals to make it a strict comparison. More info on strict comparing can be found here: http://stackoverflow.com/a/523647/1077230 – jansmolders86 Oct 01 '14 at 14:40
  • @DB7 - Just substitute the given answer with your line 3. No other changes :) Other 2 must remain with single '=' – Sainath Krishnan Oct 01 '14 at 14:46
0

If anyone is looking for the JavaScript function here you go!

<script type="text/javascript">
function leaveChange() {
    if (document.getElementById("pcount").value == 1){
        document.getElementById("listedname").value = 1;
    }     
    else if (document.getElementById("pcount").value != 1){
        document.getElementById("listedname").value = "";

}
}
</script>