0

I'm exploring javascript now. The following code runs correctly, but after I click the button, the page is refreshing. This is not desired. Any help would be appriciated. Thanks in advance.

<html>
<head>
</head>
<body >  
<form>
<input onchange="chk_change();" type="checkbox" id="chk_city" checked="checked"><label     for="chk_city">All cities</label></input><br>
<select id="sel1" style="display:none;margin:20 0 0 0;padding:3; width:100">
<option id="opt1">London
<option id="opt2">Moscow
<option id="opt3">Tokyo</option>
</select>
<br>
<button id="btn1" onclick="aa();">Go</button><br>
<p id="p1" style="border:1px solid black;width:200;height:50"></p>
</form>
</body>



<script type="text/javascript" >
function chk_change(){

var ch=document.getElementById('chk_city').checked;
    if (ch ==true){
     ch=document.getElementById('sel1').style.display='none';
    }
    else {
    ch=document.getElementById('sel1').style.display='block';
    }

}



function aa(){

sel = document.getElementById('sel1');

var text=(sel.options[sel.selectedIndex].text);
var ch=document.getElementById('chk_city').checked;
    if (ch ==true){
    document.getElementById('p1').innerText="All cities";
    }
    else{
    document.getElementById('p1').innerText=text;
    }
}

</script>


</html>
bnieland
  • 6,047
  • 4
  • 40
  • 66
GGSoft
  • 439
  • 6
  • 15
  • 1
    A ` – Rudie May 14 '14 at 19:28
  • I see no reason that wouldn't work, but try removing the `
    `, it could possibly be connected.
    – Mikk3lRo May 14 '14 at 19:28
  • @Chris there is no jquery involved and it is not tagged with it – Huangism May 14 '14 at 19:29
  • @Huangism It doesn't matter, the default action of a button is the same whether jQuery is involved or not. The accepted answer is not related to jQuery. – Chris Baker May 14 '14 at 19:31

1 Answers1

4

The default behavior of any button in a form is to be a submit button, which means that it will cause the page to reload. Set the property type='button' on the button and it will act just as a plain button, without submitting anything.

Sam Hanley
  • 4,707
  • 7
  • 35
  • 63