How to hide and show element before submit form using javascript ?
When i press button i want to show id="loading"
and hide id="sub"
before submit form ?
I test this code, i will show id="loading"
and hide id="sub"
but not submit form.
How can i do that ?
<form id="myForm" name="send_ask" action="xxx.php" method="post">
<input type="text" name="id" value="12345" style=" display: none;">
<button id="sub">Send</button>
<span id="result"></span>
</form>
<div id="loading" style=" display: none;">WAIT</div>
<script type="text/javascript">
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
$("#sub").hide(),
$("#loading").show(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function() {
return false;
});
</script>
I suggest to use $.ajax()
and use beforeSend
& complete
. Example:
$('#myForm').submit(function(e){
e.preventDefault();
$.ajax({
url: $("#myForm").attr("action"),
data: $("#myForm :input").serializeArray(),
type: 'post',
dataType: 'html',
success: function(data){
$("#result").html(data);
},
beforeSend: function(){
$("#loading").show()
},
complete: function(data){
$("#loading").hide()
}
});
});
Your $.post
parameters are wrong. The right ones are
$.post(url, data, function(result){.. run some code on complete .. }, dataType);
So you need to run the show/hide logic either in the complete callback or before the post. A better way would be to attach the handler to the submit function instead of button click.
$("#myForm").submit(function() {
$("#sub").hide();
$("#loading").show();
$.post(this.action, $(':input', this).serializeArray(), function(info){
$("#result").html(info);
});
clearInput();
return false;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.