Bind function to submit event
I´m trying to bind a simple function to a submit event, that:
- Retrieves the values of all input fields
- Sets the action attribute of the form
- Submits the form
Inspired by this answer - I came up with the following code:
$(document).ready(function() {
$('#fbook').bind('submit', function(event) {
event.preventDefault();
var baseURL = $(this).children(开发者_JS百科'#base').val();
var hotelID = $(this).children('#destination').val();
var dateIn = $(this).children('#show-date-in').val();
var location = baseURL + "&hotelID=" + hotelID + "&dateIn=" + dateIn;
$(this).attr('action', location);
$(this).submit();
});
});
And here´s the jsFiddle with HTML and JS: http://jsfiddle.net/mattvic/2wRHc/47/
Unfortunately it doesn´t work and I just can´t see where I went wrong. I hope someone can spot the error.
Many thanks!
Your code will go into an infinite loop, because $(this).submit()
calls the submit handler bound to the form element, which triggers the handler that calls $(this).submit()
, which calls the submit handler bound to the form element, and so on.
If you use the form's own submit
method, you can avoid the recursion:
this.submit();
Since the form contains a button of type submit
, your $(this).submit()
won't work. Instead, try the following -
$(document).ready(function() {
$('#booking-button').click(function(event)
{
event.preventDefault();
var baseURL = $("#fbook").children('#base').val();
var hotelID = $("#fbook").children('#destination').val();
var dateIn = $('#show-date-in').val();
var location = baseURL + "&hotelID=" + hotelID + "&dateIn=" + dateIn;
$("#fbook").attr('action', location);
$("#fbook").submit();
});
});
jsfiddle example.
Change your jQuery to this:
$(document).ready(function() {
$('#fbook').submit(function(event) {
var baseURL = $('#base', this).val();
var hotelID = $('#destination', this).val();
var dateIn = $('#show-date-in', this).val();
var location = baseURL + "&hotelID=" + hotelID + "&dateIn=" + dateIn;
$(this).attr('action', location);
});
});
精彩评论