I tried to use jQuery serialize to confirm user for form content change. It seems working. The issue is that before I submit the form, I reset the window.onbeforeload to null and hope it will not popup the confirmation dialog when user clicks submit button. But my code below still show the popup when submit button clicked.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery warn page leaving</title>
<link rel="stylesheet" href="../jquery-ui-1.10.4.custom/css/smoothness/jquery-ui-1.10.4.custom.css">
<script src="../jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"></script>
<script src="../jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(document).ready(function(){
$('#form').data('serialize',$('#form').serialize());
}
);
$(window).bind('beforeunload', function(e){
if($('#form').serialize()!=$('#form').data('serialize'))
return "Data changed.";
else e=null;
// i.e; if form state change show box not.
});
$("#form").submit( function() {
alert("called submit");
window.onbeforeunload = null;
});
function disableBeforeUnload() {
alert ("call disable func");
window.onbeforeunload = null;
}
</script>
</head>
<body>
Go to google
<form id="form" name='experiment' action="#" onsubmit="disableBeforeUnload();">
<Label for='firstName'>First name: </label><input name = 'fname' type="text" size="30" />
<Label for='firstName'>Last name: </label><input name = 'lname' type="text" size="30" />
<select name ='options'>
<option value=1> One</option>
<option value=2> two</option>
<option value=3> three</option>
</select>
<button type="submit" name="submit" />
</form>
</body>
</html>
Maybe it'll be better to use unbind function? Like following:
$("#form").submit( function() {
alert("called submit");
window.unbind('beforeunload')
});
You need to unbind the jQuery handler, not the native onbeforeunload event. So use:
$(window).unbind('beforeunload');
Or now, preferred method is to use off() to unbind:
$(window).off('beforeunload');
And on() for binding instead of bind(). Be aware though that bind() and unbind() aren't deprecated, it's still ok to use it.
jsFiddle
Related
I have a textbox with an onchange event. When the function fires, a hidden element is shown. However, when the onchange is fired due to a submit button click, the element is show very briefly because the submit function fires right after. Is there any way to prevent the submit button from not firing if it was the element that caused the textbox to "lose focus"?
EDIT:
jquery 1.3.2
<script type="text/javascript">
function phoneChanged(currentElement, valueToCompareAgainst) {
$('#divPhoneChanged').show('slow');
}
</script>
<div id="divChange">
<asp:TextBox ID="txtPhoneCell" runat="server"></asp:TextBox>
</div>
<div id="divPhoneChanged" style="display: none; padding-bottom: 15px">
<asp:Label ID="lblPhoneChanged" runat="server" Font-Bold="true" Text="Your phone number on file will be updated with the value you provided above.">
</asp:Label>
</div>
<div style="margin-top: 10px">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</div>
And in the code-behind on the page load:
txtPhoneCell.Attributes.Add("onchange", String.Format("phoneChanged(this, '{0}')", strPhoneCell))
I prepared a code using standard html code. So no asp.net. It relies on setting a global value (startSubmit) to false when the onchange event is triggered. The form submits only if its value is true.
Alternatives:
Instead of the startSubmit variable you can define a hidden input whos value changes to false when the onchange event is triggered.
Instead of using the .submit() jquery method you can define the onsubmit attribute on the form element .
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Prevent submit</title>
<script src="https://code.jquery.com/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var startSubmit = true;
$(document).ready(function () {
$('#theForm').submit(function (event) {
if (!startSubmit) {
event.preventDefault();
startSubmit = true; // Set to "true", so that the next click submits the form.
return false;
}
return true;
});
});
function phoneChanged(currentElement, valueToCompareAgainst) {
$('#divPhoneChanged').show('slow');
startSubmit = false;
}
</script>
</head>
<body>
<!-- This random number changes on each page refresh, e.g. on each form submission. -->
Page reloaded: <strong><?php echo rand(1, 99999); ?></strong>
<br/><br/>
<form id="theForm" action="" method="post">
<div id="divChange">
<input type="text" id="txtPhoneCell" onchange="phoneChanged(this, '4');">
</div>
<div id="divPhoneChanged" style="display: none; padding-bottom: 15px">
<label id="lblPhoneChanged">
Your phone number on file will be updated with the value you provided above.
</label>
</div>
<div style="margin-top: 10px">
<button type="submit" id="btnSubmit">
Submit
</button>
</div>
</form>
</body>
</html>
Edit:
I made many tests and I couldn't find an eleganter solution than the one above. Personally, I would have chosen to do it like #rickjerrity recommended:
<script type="text/javascript">
function phoneChanged(currentElement, valueToCompareAgainst) {
$('#divPhoneChanged').show('slow');
}
</script>
[...]
<input type="text" id="txtPhoneCell" onkeyup="phoneChanged(this, '4');">
try using preventDefault function in the javascript.
Prevent Default on W3 schools
I'm writing a Javascript script tightly bounded to events. I must execute some instructions on 'focus' event, and some different instructions on 'select' event.
With my surprise I see that giving focus programmatically, fires 'select' event too! That's a big problem.
Can you tell me why this is happening, and if I can block select event programmatically only when I give focus programmatically?
See the following example. When clicking to 'Give focus' button, console will write 'You selected something'!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input id="field" type="text" />
Give focus
<script>
$(document).ready(function () {
$('#field').on('select', function(e) {
console.log('You selected something');
});
$('#btn').on('click', function(e) {
$('#field').focus();
})
});
</script>
</body>
</html>
Try this:
$(document).ready(function () {
$('#field').on('select', function(e) {
console.log('You selected something');
});
$('#btn').click( function(e) {
$('#field').focus();
})
});
<input id="field" type="text" />
Give focus
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
I'm having an issue using jQuery 1.4.2 .delegate function with IE 9. I would love to use the latest version of jQuery and just use the .on function but I am forced to use 1.4.2 due to a vendor product.
My goal is to have a function fire off when the text field changes. So if it's empty and it gets set to "test" then a function will run.
Here's what I'm trying to do, the alert never shows...
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function test(result) {
var result = result;
$("#txtTest").val($("#txtTest").val() + result);
}
$("body").delegate("#txtTest", "change",function() {
alert( "Handler for .change() called." );
});
</script>
</head>
<body>
Test: <input type="text" id="txtTest"/><br />
<input type=button value=Test name="Submit" id="btnTest" onclick="test('testing the call')" />
</body>
</html>
I have also tried using myCustomEvent:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function test(result) {
var result = result;
$("#txtTest").val($("#txtTest").val() + result).trigger("myCustomEvent");
}
$("body").delegate("#txtTest", "myCustomEvent",function() {
alert( "Handler for .change() called." );
});
</script>
</head>
<body>
Test: <input type="text" id="txtTest"/><br />
<input type=button value=Test name="Submit" id="btnTest" onclick="test('testing the call')" />
</body>
</html>
Thanks in advance
The problem is that you named your submit button "Submit". This is a no-no for HTML!! Browsers default to using internal submit functions when buttons are named submit. see [*] below.
Also, a val() inject doesn't trigger the change() event, so we need to call that manually.
Change Submit to xSubmit and trigger the change event at the end of the chain manually and it works. It should also be in a dom ready wrapper:
html
Test: <input type="text" id="txtTest"/><br />
<input type="button" value="Test" name="xSubmit" id="btnTest" onclick="test('testing the call')" />
js
$(function() {
$("body").delegate("#txtTest", "change", function() {
alert( "Handler for .change() called." );
});
});
function test(result) {
$("#txtTest").val($("#txtTest").val() + result).change();
}
demo:
http://jsfiddle.net/at7eoarL/1/
Further Reading: * - https://issues.apache.org/jira/browse/TAP5-947
when I release a key in an input form html field, I get in Firefox 33.1 in jQuery an keyup event and also an unwanted focusout event. I just want the keyup event when releasing the key.
This is my code:
<html>
<head>
<script src="libraries/jquery/jquery-1.11.1.min.js"></script>
</head>
<body>
<form id="contact_form">
<input class="contact_save" type="text" value="" />
</form>
</body>
<script>
$(document).ready(function($){
$('#contact_form .contact_save').focusout(function() {
alert("focusout!");
});
$('#contact_form .contact_save').keyup(function() {
alert("keyup!");
});
});
</script>
</html>
What I am doing wrong?
Thanks
Michael
It's because the alert causes the focusout to be called. Putting the result in another element for an example does not cause it to trigger:
$('#contact_form .contact_save').focusout(function() {
alert("focusout!");
});
$('#contact_form .contact_save').keyup(function() {
$('#result').val('keyup');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact_form">
<input class="contact_save" type="text" value="" />
<output id="result" />
</form>
Trying using:
$('#contact_form .contact_save').blur(function() {
alert("focusout!");
});
I create a login form in popup box. When the username field is left blank, an error message will appear to notify the user to fill in the empty username field. As a test, I click on the login button leaving the username field, and the message appears in the popup box as expected. But the problem is the popup box is closed immediately.
So, my question is how do I keep the popup box open with the error message shown?
Here is my script:
<!doctype html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Modal Login Window Demo</title>
<link rel="shortcut icon" href="http://designshack.net/favicon.ico">
<link rel="icon" href="http://designshack.net/favicon.ico">
<link rel="stylesheet" type="text/css" media="all" href="http://designshack.net/tutorialexamples/modal-login-jquery/style.css">
<script type="text/javascript" src="http://designshack.net/tutorialexamples/modal-login-jquery/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://designshack.net/tutorialexamples/modal-login-jquery/js/jquery.leanModal.min.js"></script>
</head>
<body>
<div id="w">
<div id="content">
<center><a href="#loginmodal" class="flatbtn" id="modaltrigger">Modal Login</a</center>
</div>
</div>
<div id="loginmodal" style="display:none;">
<?php
if($_POST["loginbtn"]){
if(!$_POST["username"]){
echo "<center><font color=red>please fill your username</font></center>";
}elseif(!$_POST["password"]){
echo "<center><font color=red>please fill your password</font></center>";
}
}
?>
<h1>User Login</h1>
<form method="post">
<label for="username">Username:</label>
<input type="text" name="username" id="username" class="txtfield" tabindex="1">
<label for="password">Password:</label>
<input type="password" name="password" id="password" class="txtfield" tabindex="2">
<div class="center"><input type="submit" name="loginbtn" id="loginbtn" class="flatbtn-blu hidemodal" value="Log In" tabindex="3"></div>
</form>
</div>
<script type="text/javascript">
$(function(){
$('#loginform').submit(function(e){
return false;
});
$('#modaltrigger').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
});
</script>
</body>
</html>
The closeButton option will always cause the modal to be closed when the corresponding button is clicked. And looking at the leanModal source, there doesn't seem to be any direct way to manipulate its event-handling callback.
So if all you want to do is to keep the form modal opened if the fields are not filled, and let your server-side codes perform the validation you can just do the following:
$('#loginform').submit(function(e){
if(!$('#username').val()) {
$('#loginmodal').show();
}
else
console.log("Enter your username");
return false;
});
Live demo on jsfiddle. Notice that I added an id to the form tag, and fixed some of the malformed HTML tags in the fiddle.
Haven't had a chance to test but try stopping the propagation of the click function, doing that tells the browser to not complete the default action for this event.
$('#loginbtn').click(function(e){
if(!$('#username').val()){
e.stopPropagation();
}
});
or as the other answer suggests try using jquery validation which will help in getting all this to work much more easily I like to use: http://jqueryvalidation.org/
This appears to be very similar to this question: How to force a html5 form validation without submitting it via jQuery
That answer assumes that you would be adding the required attribute to the necessary form elements, and also that you use a polyfill such as html5shiv if old browser support is a requirement.
use jquery validationEngine. It is a good one for your requirement.
See demo here
You have some missing information in the sample html, the form ID is missing therefor jQuery will not attach to it.
I handle this situation by using AJAX for the form action with a json response.
Here is an example from one of my recent apps... Notice the event.preventDefault() method to keep the form from submitting.
$(function () {
jQuery('body').on('submit', '#frmlOGIN', function (event) {
event.preventDefault();
jQuery.post("?action=ajax_signup", jQuery("#frmlOGIN").serialize(), function (data) {
if (data.status == "OK") {
jQuery("#modal_content").html(data.content);
} else {
jQuery("#error_message").html(data.response);
}
});
});
$('#modaltrigger').leanModal({
top: 110,
overlay: 0.45,
closeButton: ".hidemodal"
});
});
Here is a jsfiddle example.
http://jsfiddle.net/LqmzwwL3/