cc2k cc2k - 4 months ago 7
PHP Question

php funtion calling inside a form

I am trying to make a page with several buttons(or links) that will direct to different pages.

I have tried this by using the following code that should redirect the user to google.com.

<!DOCTYPE HTML>
<html>
<body>

<form id='form' action="main.php">

<button id="allSetsButton" class="float-left submit-button"> main</button>
</form>

<script type="text/javascript">

document.getElementById("allSetsButton").onclick = function (){
location.href = 'http://google.com';
};
</script>

</body>
</html>


However, when I press the button, the page refreshes instead of redirecting me.

What am I doing wrong here?

Answer

Add type="button" to your button element so that it's not considered as a submit button for the form (which causes to submit the form before your event handler can do anything).

<button type="button" id="allSetsButton" class="float-left submit-button"> main</button> 
Comments