Reputation: 451
JavaScript
<script>
function changeColor() {
var element = user.elements["group1"];
for (var i = 0; i < element.length; i++) {
if (element[i].checked == true) {
var newColor = element[i].value;
alert("hai");
document.getElementById("changeColor").style.background = newColor;
}
}
}
</script>
HTML
<div id="color">
<input type="radio" name="group1" id="color1" value="#990000" /><label for="color1">Red</label>
<input type="radio" name="group1" id="color2" value="#009900" /><label for="color2">Green</label>
<input type="radio" name="group1" id="color3" value="#FFFF00" /><label for="color3">Yellow</label><br><br><br>
<button onclick="changeColor()">Change</button>
The above HTML and JavaScript code is fine when I click on the radio button the background color is changed. It is working properly. However, my problem is that after the color change the browser will automatically refresh, which I do not want.
Upvotes: 1
Views: 10232
Reputation: 3414
After click on submit button the onclick event will call. So if you send boolean value return false then the page is not submit here is code i am using return false;
<script>
function changeColor() {
var element = user.elements["group1"];
for (var i = 0; i < element.length; i++) {
if (element[i].checked == true) {
var newColor = element[i].value;
document.getElementById("changeColor").style.backGround = newColor;
return false;
}
}
}
</script>
Change the onlick event add return before your changeColor() function
<button onclick="return changeColor();">Change</button>
Upvotes: 1
Reputation: 2286
Its looks like your button is the only button in the form so the browser is thinking its the submit button for the form.
As pointy says you can add a type to the button, add you onclick function to a different element such as a link (with an anchor not an actual link of course otherwise you will get the same problem) or move the button outside of the form.
Upvotes: 0
Reputation: 3161
You could wrap the radio-buttons with a form, like this, leaving the button outside:
<form name="form_radiobuttons">
<input type="radio" name="group1" id="color1" value="#990000" /><label for="color1">Red</label>
<input type="radio" name="group1" id="color2" value="#009900" /><label for="color2">Green</label>
<input type="radio" name="group1" id="color3" value="#FFFF00" /><label for="color3">Yellow</label><br><br><br>
</form>
<input type="button" onclick="changeColor()">Change</button>
This way the form won't be submitted when you click the button.
Upvotes: 0