Question

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>
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top