Reputation: 181
I have two forms here, the first is a select dropdown select, which when posted generates another form, creating an amount input boxes based on the number selected. This second form then puts the data from the input boxes into 2 array. All this works perfectly but I am trying to add extra functionality to the submit button on the second form. I created a function 'showcontet()' to show and hide the content in the div with id 'table'. This works perfectly when used on a button outside of the form. When used on the submit button inside the form you can see the content for about 1 second before it then disappears again.
<head>
<script type="text/javascript">
showcontent = function(){
var content = document.getElementById('tabl');
content.style.display = 'inline';
}
</script>
<?php
$userkey = array();
$userval = array();
$usernum = $_POST['usernum'];
$total = 0;
?>
<form action='MYPIE.PHP' method='POST'>
HOW MANY SECTIONS?
<select name="usernum" value="<?php echo $usernum;?>">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
</select>
<input type="submit" name="submitnum" value="submit selection" />
</form>
<form action='MYPIE.PHP' method='POST'>
<?php
for ($i=1; $i<$usernum+1; $i++){
echo '<input type="hidden" value="' .$usernum.'" name="usernum" />';
echo "<br>insert key: <input name='key".$i."' value='".$userkey[$i]."'> insert value: <input name='val".$i."' >";
$userkey[$i] = $_POST["key".$i];
$userval[$i] = $_POST["val".$i];
}
?>
</br>
<input type="submit" value="submit" name="submit keys" onclick="showcontent()" />
</form>
</table>
<div id="tabl" style="display:none;">
content
</div>
Apologies for the bad indentation, I am pretty new to this & thanks for any help
Upvotes: 0
Views: 2286
Reputation: 6615
make your second button not a 'submit' button but a regular 'button' else it will fire the submit of the form...
or
set the 'showcontent()' function on the forms 'onsubmit' event and let that function return false:
onsubmit="return showcontent()"
function showcontent(){
var content = document.getElementById('tabl');
content.style.display = 'inline';
$.ajax({
type: "POST",
url: "MYPIE.PHP",
data: { usernum: $("select[name='usernum'] option:selected").val() }
}).done(function() {
alert('data posted');
});
return false;
}
Upvotes: 0
Reputation: 3826
You need add e.preventDefault(); to the event handler to prevent the browser from submitting the form and loading the page.
Don´t use return false as this is other sideeffects you might not want. see http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
Upvotes: 0
Reputation: 887285
You need to return false
from the event handler to prevent the browser from submitting the form and loading the page.
Upvotes: 2