How to prevent submit button from submitting after textbox loses focus - javascript

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

Related

I want to hide the form and show a written success message as well as reload the page with a hash value

I'm working on a form and as I submit I want to hide the form and show a written success message when I submit it. I want to also be able to reload the page with a hash value.
I made this function, which works but I feel like it'll give me some reload problems as the form appearing again and success message dissapearing. The form tag contains the onSubmit="submissionmMessage()
<script>
function submissionMessage() {
window.location.hash = "#success";
document.getElementById("successMessage").style.display = 'block';
document.getElementById("form").style.display = 'none';
</script>
<div>
<p style="display:none;" id="successMessage"><strong> Success!</strong></p>
</div>
It works for hiding the showing the message but I feel like there could be room for errors?
also if I put in the "window.location.hash = "#success"
and the success url as the url with the #sucess at the end will it be counter-intuitive?
Sample Code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#success {
display: none;
}
</style>
</head>
<body>
<p id="demo" class="font-effect-shadow-multiple"></p>
<script>
function submissionmMessage() {
/*
Get Response from SERVER using AJAX.
*/
document.getElementById("success").style.display = "block";
}
</script>
<div id="success">Your Form has bee Submitted.</div>
<form id="form" method="POST" action="#" onsubmit="event.preventDefault(); submissionmMessage();">
<input type="text" name="txt" id="txt" />
<input type="submit" name="submit" />
</form>
</body>
</html>

How to add additional GET parameters in a mixed Form/HREF link that uses a modal box?

I have an issue that is a little tricky.
First, for folks who will run my snippet first -- when you run my example and click Generate, you will first see a modal box, which (on my backend) first reads the $_GET data. My submit mechanism uses A HREF method, to which I want to add more data via form, or otherwise, to be read by the receiving page.
In HTML source below, observe:
I have a link to portal.php, which includes query parameters
clicking that link engages the modal_box mechanism
my link is a button
I need to have a way to add data (GET, or POST), that will submit upon the click of that button, and be received by the resulting page (portal.php in my example).
I want, for example, to be able to print on my receiving page that the following are true:
$_GET['p'] == 'select';
$_GET['coverpage'] == 'standard';
How?
Snippet Follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<meta charset="utf-8" />
<title>T</title>
<script>
$(document).ready(function() {
$(".modal_box").click(function() {
$("#iframe_dialog_box").attr('src', $(this).attr("href"));
$("#div_modal_box").dialog({
width: 300,
height: 200,
modal: true,
close: function() {
$("#iframe_dialog_box").attr('src', "about:blank");
}
});
return false;
});
});
</script>
</head>
<body>
<div id="div_modal_box" title="portal.php?p=select" style="display:none;">
<iframe id="iframe_dialog_box" width="100%" height="100%"></iframe>
</div>
<form METHOD="GET">
<input type="radio" name="coverpage" value="standard" checked="checked">standard
<br>
<input type="radio" name="coverpage" value="more">more
<br>
<a href="portal.php?p=select&action=print" class="modal_box">
<button type="submit">Generate</button>
</a>
<script>
$("button").button();
</script>
</form>
</body>
</html>
Your click handler should get the values from the form, and add them to the URL before assigning the iframe src:
$(document).ready(function() {
$("button").button();
$(".modal_box").click(function() {
var coverpage = $(":radio[name=coverpage]").val();
$("#iframe_dialog_box").attr('src', $(this).attr("href") + '&coverpage=' + coverpage);
$("#div_modal_box").dialog({
width: 300,
height: 200,
modal: true,
close: function() {
$("#iframe_dialog_box").attr('src', "about:blank");
}
});
return false;
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<div id="div_modal_box" title="portal.php?p=select" style="display:none;">
<iframe id="iframe_dialog_box" width="100%" height="100%"></iframe>
</div>
<form METHOD="GET">
<input type="radio" name="coverpage" value="standard" checked="checked">standard
<br>
<input type="radio" name="coverpage" value="more">more
<br>
<a href="portal.php?p=select&action=print" class="modal_box">
<button type="submit">Generate</button>
</a>
</form>

form submit in popup box

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/

how to show error message on submit button?

Can you please tell me how to show an error message on submit button click ?.I am getting an error message after running the program (when I write required :true). I need to show an error message when a user submits the form. I am using this plugin https://github.com/McNull/angular-febworms
Can we get onchange event of select field ?
In my example a red border is displayed when I run the application. I don't want this. I need this when a user clicks the 'submit' button
http://plnkr.co/edit/JOI82JrEBcKJMrzLgtZd?p=preview
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css#2.3.2" data-semver="2.3.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" />
<link rel="stylesheet" href="https://rawgithub.com/McNull/angular-febworms/master/package/febworms.min.css" />
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="http://code.angularjs.org/1.2.0/angular.js" data-semver="1.2.0"></script>
<script src="http://code.angularjs.org/1.2.0/angular-route.js"></script>
<script type="text/javascript" src="https://rawgithub.com/McNull/angular-febworms/master/package/febworms.min.js"></script>
<script type="text/javascript" src="dummy-schema.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MyFormController as frmCtrl">
<div class="container">
<div class="row-fluid">
<form class="form-horizontal" name="form.state" novalidate>
<div febworms-form
febworms-schema="form.schema"
febworms-form-data="form.data">
</div>
<div class="form-actions">
<a class="btn btn-primary" ng-disabled="form.state.$invalid" ng-click="frmCtrl.save()">Save changes</a>
</div>
</form>
</div>
</div>
</body>
</html>
But need to blur event to validate or onchange event ?
Since your form name is 'form.state' and your field name is 'required' (which is a bit confusing by the way, you may want to change that), you can get useful information about your validation state with the following expressions in the scope of your form:
form.state.required.$error // yields something like { "required": true, "pattern": false }
form.state.required.$valid // yields a boolean
form.state.$error
form.state.$valid
I haven't heard of a way of knowing whether a form has already been submitted or not. My best shot would be to add some state for this in the controller :
$scope.errorShown = false;
$scope.showErrorMessage = function(){
$scope.errorShown = true;
};
And in your HTML :
<div class="form-actions">
<a class="btn btn-primary" ng-disabled="form.state.$invalid" ng-click="(form.state.$valid ? frmCtrl.save() : showErrorMessage())">Save changes</a>
</div>
<div ng-if="errorShown && form.state.$invalid">
Your form is not valid.
</div>
Plunkr here.

form post by clicking "no submit" button

i got got confused when i run the static js and html below
i want to dynamicly add option by clicking button, but when i put it under the form , it will do acition post, unless i put it out of form ,it works. what's the reason? i didn't set type as "submit" for the add button, does any button clicked in form will cause form action?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>作业管理</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST" >
<div id="postform">
本次作业标题
<input type="text" name="title" />
<br>
<div class="postoption">
添加项目
<input type="text" name="option[]" />
音频文件
<input type="file" name="radio[]" />
答案
<input type="text" name="answer[]" />
</div>
</div>
<button id="add">添加输入项</button>
<input type="submit" value="提交" />
</form>
<script type="text/javascript">
window.onload = function(){
var add = document.getElementById("add");
add.onclick = function(){
addOption();
}
}
function addOption(){
var postForm = document.getElementById("postform");
var postoptions = document.getElementsByClassName("postoption");
var op = postoptions[0];
var optionClone = op.cloneNode(true);
postForm.appendChild(optionClone);
};
</script>
</body>
</html>
The <button> element is a submit button by default. You can change this with the type="button" attribute, which makes it do nothing by default, or calling preventDefault on the event. But I'd go with the attribute since then your intention is semantically clear without actually running the script.

Categories

Resources