Jesse S
Jesse S

Reputation: 81

JavaScript to Change onchange Attribute

I'm having some issues with using javascript to set the onchange attribute of an HTML element. The script works fine except the else statement does not work even when the select is changed to No. I have tried to debug but nothing shows up. Can someone shed some light as to why this is happening?

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <style type="text/css">
  </style>
  <title></title>
<style type="text/css"></style></head>
<body>
    <div class="testclass">
         <select class="selectClass">
               <option value=""></option>
               <option value="y">Yes</option>
               <option value="n">No</option>
         </select>
         <input class="inputText" type="text">
    </div>

     <script type="text/javascript">

     var div = document.getElementsByClassName("testclass")[0];
     //alert(div.getElementsByClassName("selectClass")[0].value);
     var select = div.getElementsByClassName("selectClass")[0];

     select.setAttribute("onchange", "myfunction()");

     function myfunction() {
          var x = document.getElementsByClassName("selectClass")[0];
          var y = document.getElementsByClassName("inputText")[0];
          if(x.value = "y"){
               y.value = "hello";
          }
          else{
          y.value = "boo";
          }
     }
</script>

</body></html>

Upvotes: 1

Views: 381

Answers (2)

Mohit Bhatia
Mohit Bhatia

Reputation: 69

if(x.value = "y"){
y.value = "hello";
}
else{
y.value = "boo";
} 

can be converted to

y.value = (x.value === 'y') ? 'hello' : 'boo';

single equal is for assignment. == or === is for comparison. It is also recommended to use === (strong comparision) to ensure they are of same type.

Upvotes: 0

Nghi Nguyen
Nghi Nguyen

Reputation: 950

You missing "=" in if condition man

if(x.value == "y")

Upvotes: 1

Related Questions