Prevent form from submit w/ jQuery
I have a page that displays data. A user can click "edit" button and the text displays within a form. Basically I hide form and on click toggle text to hide and form to show. I need to make sure that the form can not be submitted, via page refresh or clicking Enter key, until it is visible and the user clicks submit button.
How do I do that?
$("#dataForm").hide();
$("#editData").click(function() {
$("#d开发者_高级运维ataForm").toggle();
$("#dataText").toggle();
});
<div id="dataForm">
<label>Label 1</label>
<input type="text">
<label>Label 2</label>
<input type="text">
<input type="submit">
</div>
<div id="dataText">
Label 1: abc
<br>
Label 2: 123
<br>
<span id="editData">Edit</span>
</div>
Refresh will not submit the form. For the enter key, it should submit only if the form is in focus (selected). If you make sure it is hidden, clicking enter will not submit it.
You can prevent the form from submitting by using a submit event handler:
// When the form is closed...
$('form').bind('submit.myform', function(e) {
e.preventDefault(); // form will not be submitted
});
// When the form is opened
$('form').unbind('submit.myform');
You can namespace the submit event (as above) to make it easier to remove later on.
I would do something like this:
HTML:
<table>
<tr>
<td class="text">
Some text
</td>
<td>
<a href="#" id="edit">Edit</a>
</td>
</tr>
</table>
<div id="form">
<form action="page" method="POST">
<input type="text" name="text">
<input type="submit" name="submit" id="submit">
</form>
</div>
CSS: Hide the form div, so you can toggle it's visibility with jQuery.
#form {
display:none;
}
jQuery: Bind click event on the link, and send the text to the input. The form will then show itself.
$("table").find('td').delegate('a', 'click', function() {
var a_elem = $(this),
parent_tr = a_elem.parents('tr'),
thetext = parent_tr.find('td.text').text().trim();
$("input[name=text]").val(thetext);
$("div#form").show();
});
精彩评论