Haider
Haider

Reputation: 3

Javascript show message and hide message onclick on select tage

I have a select box

<select id="box1" onchange="turnOff();" onclick="show();">
    <option value="1" >1</option>
    <option value="2" >2</option>
</select>

and

<p id="helpMessage"  style="display: none;" >something</p>

and js code is

function turnOff(){ 
    document.getElementById('helpMessage').style.display = 'none';              
}
function show(){
    document.getElementById('helpMessage').style.display = 'block';
}

problem it shows the message onclick, but onchange not working

Upvotes: 0

Views: 5753

Answers (3)

Keerthi
Keerthi

Reputation: 923

Your code actually works. It's because that you are attaching both the click and the change handler, it fires at the same time. Your onchange event makes the display to none but at the same time, the click event is also triggered and that's why you are able to see the text.

Edit:

function turnOff(){  
            document.getElementById('helpMessage').style.display = 'none';              
        }
        function show(btn){                
            document.getElementById('helpMessage').style.display = 'block';
          btn.onclick = function(){};
        }
<select id="box1" onchange="turnOff();" onclick="show(this);">
<option value="1" >1</option>
<option value="2" >2</option>
</select>
<p id="helpMessage"  style="display: none;" >something</p>

Upvotes: 1

user5161174
user5161174

Reputation:

onchange instead of onChange It's case sensitive so the capital "C" won't work.

Upvotes: 0

Shrinivas Pai
Shrinivas Pai

Reputation: 7711

<select id="box1"  name="form_select" onchange="turnOff(this)">
    <option value="1" >1</option>
    <option value="2" >2</option>
   </select>

function turnOff(elem){
   if(elem.value == 1)
      document.getElementById('helpMessage').style.display = "none";
   else
      document.getElementById('helpMessage').style.display = "block";
}

Upvotes: 0

Related Questions