Alex Alex - 1 month ago 18
jQuery Question

Jquery button triggers form submit

The following script enables users to prompt a value into the input field of a form:

<script>
$(document).ready(function(){
$("button").click(function(){
$('input[name="fine"]').val(computeEndTime($('input[name="ini"]').val()));
});
function computeEndTime(ini){
var parts = ini.split(/[:,\s\.]+/).map(Number);
var hourstart = parseInt(parts.shift());
var minutestart = parseInt(parts.shift());
var totalm = (hourstart * 60) + minutestart + 100;
var minutes = totalm%60;
var hours = (totalm - minutes) / 60;
return hours + ":" + minutes;
}
});
</script>


The HTML form is this:

<form action="next.php" method="POST">
<input type="text" name="ini" maxlength="5" />
<input type="text" name="fine" maxlength="5" />
<button>100</button>
<input type="submit" name="invia" value="go on" />
</form>


As you can see, the script takes the time value typed into input
"ini"
and through the button prompts into input
"fine"
another time value (the initial one + 100 minutes).

The problem I am having is that when the button
<button>
is pushed, also the other submit button of the form is triggered, and the user is immediately redirected to the page next.php.

How can I avoid this, and require the user to push the submit button?

Answer

Change the button to

<button type="button">100</button>

The default is type="submit", so it submits the form.

Comments