I have a form that I am stopping from submitting with e.preventDefault(). (I've also tried return false).
I would manually tell the form to submit after a short delay, using the code:
$('form').delay(2000).submit();
Unfortunately, e.preventDefault() seems to disable the form from submitting even if it explicitly submitted using the submit() function.
Any idea how I can combine these intentions? I'd like to show a loading screen for a couple of seconds.
Thanks!
$("form").on('submit.blocker', function (e) {
setTimeout(function () {
$("form").off('submit.blocker').trigger('submit');
}, 2000);
e.preventDefault();
});
Try this.
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var okToSubmit = false;
$('form').submit(function (e)
{
if ( ! okToSubmit)
{
e.preventDefault();
var $form = $(this);
setTimeout(function ()
{
okToSubmit = true;
$form.submit();
}, 2000);
}
});
});
</script>
<form action="somewhere">
<input type="text" name="something" />
<input type="submit" />
</form>
Above code is tested.
$('form').on('submit', function(e) {
if (!e.isTrigger) {
setTimeout(function() {
$("form").trigger('submit');
}, 2000);
e.preventDefault();
}
});
you may want to try this it works for me:
<form name="demo" action="111" onSubmit="fun();return false">
<input type="text" name="name1" />
<input type="submit" />
</form>
and in the javascript
fun()
{
var x= document.forms["demo"];
setTimeout(x.submit(),2000);//time in milliseconds
}
Related
I have a situation here. I have a form which contains hidden value. When user clicks the browser back button then the form should be submitted. I have controlled the back space button but haven't found a solution for browser back button. Here is my code.
Form
<form id="movevalue" action="/media" method="post">
<input type="hidden" id="pagedetail" name="pagedetail" value="<?php echo $pagenumber; ?>" />
<input type="submit" value="" style="display:none" />
</form>
At the end of page this is my script.
script
<script>
$(function(){
$(document).bind("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
$('#movevalue').submit();
}
});
});
window.onbeforeunload = function(evt)
{
if (typeof evt == 'undefined')
$('#movevalue').submit()
}
</script>
window.onbeforeunload this not work for me.
Just use this code and this will cover all state of page leave or close...
<script>
window.onbeforeunload = function() {
$('#movevalue').submit();
return true;
};
</script>
try this:
$(function () {
if (window.history && window.history.pushState) {
window.history.pushState('', null, '');
$(window).on('popstate', function (id) {
$('#movevalue').submit();
});
}
});
<div id="language-container">
<form id="language_radio">
<input type="radio" value="//domain.tld/page.php?lang=02" name="language" id="alb">
<label for="alb">Shqip</label>
<input type="radio" value="//domain.tld/page.php?lang=03" name="language" id="eng">
<label for="eng">English</label>
</form>
</div>
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("body").fadeOut(800, newpage);
});
</script>
What I'm trying to accomplish is, when a radio button is selected, I want to fade out the entire body, and then redirect to another page.
However, I can't seem to get it to do anything. It won't fade out or redirect.
How can do I fix it (newb to JS) :)?
You can use:
$("html").fadeOut();
as such:
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
// This variable is useless
// You can remove it if it's not
// being used
newLocation = $(this).val();
$("html").fadeOut(800, function() {
// Redirect to the newLocation here
// similar behavior as clicking on a link
window.location.href = newLocation;
});
});
</script>
try :
<script type="text/javascript">
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
newLocation = $(this).val();
$("html").fadeOut(800, function() {
window.location.href = newLocation;
});
});
</script>
you can do this by
$("#language_radio input[type=radio]").change(function(event) {
event.preventDefault();
$("body").fadeOut(1000,function(){
window.location.href = $(this).val();
})
});
jsfiddle
I use the following code for edit operation and I've button in the edit screen which I want that it will be enabled when the edit is success
how can I do that?
This is the edit operation
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="UserId,FirstName,LastName,Email,Phone,PhoneWork,WorkingAt")] User user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
}
return View(user);
}
This is the button
#using (Html.BeginForm("check", "User"))
{
<input type="submit" id="btn" value="check" />
<span id='result'></span>
}
First You have to disable your button on load
#using (Html.BeginForm("check", "User"))
{
<input type="submit" id="btn" value="check" disabled />
<span id='result'></span>
}
and on your edit button write function onclick=enable(); add jquery
<script type="text/javascript">
function enable() {
var btn = document.getElementById("btn");
btn.disabled = false;
}
</script>
Just make sure your use button tag with type submit
<button type="submit" id="btn" value="check">Save</button>
This is what i m doing for my buttons, just use javascript to achieve.
<script>
$(document).ready(function () {
$(document).on('invalid-form.validate', 'form', function () {
var button = $(this).find('button[type="submit"]');
setTimeout(function () {
button.removeAttr('disabled');
}, 1);
});
$(document).on('submit', 'form', function () {
var button = $(this).find('button[type="submit"]');
setTimeout(function () {
button.attr('disabled', 'disabled');
}, 0);
});
});
</script>
Let me know if that helps.
I have a code here for disabling the radio on a form and focusing on the submit button right after the timer expires. But this code seems not to work. Can you tell me what's wrong with my code or if you have any alternative with this? I'm using jquery timeTo plugin as my timer ..
<script type="text/javascript">
$(document).ready(function() {
$('#countdown').timeTo(5000, disablefocus();
});
});
function disablefocus(){
$(document).ready(function() {
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
});
</script>
---->
<div id='countdown'></div>
<form>
<input type='radio' name='radio1' value='father'>
<input type = 'submit' id ='submitwidget' value='submit'/>
</form>
you add extra curly braces for timeTo function and miss the closed curly braces for disableFocus function.
$(document).ready(function() {
$('#countdown').timeTo(5000, disablefocus);
function disablefocus(){
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
}
});
or another way
$('#countdown').timeTo(5000, function() { disablefocus(); });
$(document).ready(function() {
$('#countdown').timeTo(20, function() {
disablefocus();
});
function disablefocus(){
var message = $('#confirmMessage');
var goodColor = "#66cc66";
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
message.css("color" , goodColor);
message.html("Press me now!");
}
});
Im building a file upload with jQuery, but Im getting a jQuery error trying to set the attributes of the form:
$(document).ready(function () {
$("#formsubmit").click(function () {
var iframe = $('<iframe name="postframe" id="postframe" class="hidden" src="about:none" />');
$('div#iframe').append(iframe);
$('#theuploadform').attr("action", "/ajax/user.asmx/Upload")
$('#theuploadform').attr("method", "post")
$('#theuploadform').attr("userfile", $('#userfile').val())
$('#theuploadform').attr("enctype", "multipart/form-data")
$('#theuploadform').attr("encoding", "multipart/form-data")
$('#theuploadform').attr("target", "postframe")
$('#theuploadform').submit();
//need to get contents of the iframe
$("#postframe").load(
function () {
iframeContents = $("iframe")[0].contentDocument.body.innerHTML;
$("div#textarea").html(iframeContents);
}
);
}
);
<div id="uploadform">
<form id="theuploadform" action="">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
</div>
<div id="iframe" style="width: 0px; height: 0px; display: none;">
</div>
<div id="textarea">
</div>
I found the solution. This code works:
<script type="text/javascript">
$(document).ready(function () {
$("#formsubmit").click(function () {
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>');
$("body").append(iframe);
var form = $('#theuploadform');
form.attr("action", "/upload.aspx");
form.attr("method", "post");
form.attr("encoding", "multipart/form-data");
form.attr("enctype", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", $('#userfile').val());
form.submit();
$("#postiframe").load(function () {
iframeContents = this.contentWindow.document.body.innerHTML;
$("#textarea").html(iframeContents);
});
return false;
});
});
</script>
<form id="theuploadform">
<input id="userfile" name="userfile" size="50" type="file" />
<input id="formsubmit" type="submit" value="Send File" />
</form>
<div id="textarea">
</div>
It's not an official plugin, however here's an example on how you could wrap the form's submitting logic into a plugin.
Example:
<form method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="text" name="test" />
<button type="submit">Submit</button>
</form>
<script>
$('form').submit(function (e) {
//prevent default submit
e.preventDefault();
//submit through frame
$(this).frameSubmit({
done: function (form, frame, options) {
console.log('done!');
},
fail: function (form, frame, options) {
console.log('fail!');
},
always: function (form, frame, options) {
console.log('always!');
}
//custom hasError implementation if needed
//by default if the frame's body HTML contains the text "unexpected error" or "server error"
//it is treated as an error
/*,hasError: function (frame) {
return false;
}*/
});
});
</script>
PLUGIN
!function ($, doc) {
var _frameCount = 0,
_callbackOptions = ['done', 'fail', 'always'],
_hasFailed = function (frame) {
var frameHtml = $(frame).contents().find('body').html();
return /(server|unexpected)\s+error/i.test(frameHtml);
},
_createFrame = function () {
return $('<iframe>').prop('name', 'jq-frame-submit-' + _frameCount++).hide().appendTo(doc.body);
};
$.fn.extend({
frameSubmit: function (options) {
return this.each(function () {
var deferred = $.Deferred(),
form = this,
initialTarget = form.target,
hasTarget = form.hasAttribute('target'),
hasFailed = options.hasFailed || _hasFailed,
//The initial frame load will fire a load event so we need to
//wait until it fires and then submit the form in order to monitor
//the form's submission state.
$frame = _createFrame().one('load', function () {
$frame.one('load', function () {
deferred[hasFailed(this) ? 'reject' : 'resolve'](form, this, options);
$frame.remove();
});
form.submit();
//restore initial target attribute's value
if (hasTarget) form.target = initialTarget;
else form.removeAttribute('target');
});
//attach handlers to the deferred
$.each(_callbackOptions, function (i, optName) {
options[optName] && deferred[optName](options[optName]);
});
//make sure the form gets posted the to iframe
form.target = $frame.prop('name');
});
}
});
}(jQuery, document);
Your form target should be the same as iframe name, for example:
<form target="frame"
action="http://posttestserver.com/post.php?dir=example"
method="post"
enctype="multipart/form-data">
<input name="file" type="file"/>
</form>
<iframe name="frame"></iframe>
And after this you can attach event to input button to listen for 'change'.
Furthemore you can get progress from server using jsonp and all of this will work in any browser event IE3+. Something like this:
$('input').change(function () {
$('form').submit();
});
$.getJSON('/echo/jsonp/?callback=?', function(e, progress) {
console.log(progress);
});
This is a good plugin to upload files using ajax
http://jquery.malsup.com/form/#file-upload
You know instead of fetching the same item multiple times, why not just reuse it:
var form = $('#theuploadform');
form.attr("action", "/ajax/user.asmx/Upload");
form.attr("method", "post");
// and so on
What kind of error are you having? can you post it?
UPDATE
Since you cannot set the attribute yourself here is a work around:
Put the form in an iframe, and attach an onchange event to the input button.
when the user select a file, you trigger the necessary code to upload the file (submit), then the parent window can close the iframe.