form submit in popup box - javascript

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/

Related

How to disable HTML/JavaScript form if JavaScript is disabled in browser

First off the bat I am new to this an really trying my best to understand how this works. I have the following simple login form that leads to a homepage if the right login credentials are submitted. However when run in Firefox with JavaScript disabled the login credentials are ignored and my homepage is displayed anyway no matter what login details I provide. I have created a message in between <noscript></noscript> which fires when JavaScript is disabled. What I would like to achieve is that the warning message displays only and that the form etc. is disabled and not displayed until the login page is reloaded with JavaScript enabled. Can someone please help me with this? It is much appreciated!! My code is
<!doctype html>
<!-- This is is the main start page saved in index.html -->
<html lang="en-US">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<h2>Login details</h2>
<noscript>
<h3>Before you login</h3>
<p>JavaScript needs to run for this site to work properly.<br />
Please activate JavaScript in your browser<br />
and reload this page to login.
</p>
</noscript>
<form id="myForm" name="login" onsubmit="return validateFormOnSubmit()" action="http://localhost:8080/index.html" method="post">
<fieldset>
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
<script>
function validateFormOnSubmit() {
var un = document.login.username.value;
var pw = document.login.password.value;
var username = "username"
var password = "password"
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can achieve this without adding extra JavaScript. You can use a <noscript> tag also in the <head>, so you are able to hide this with CSS:
…
<head>
…
<noscript>
<style>
#myForm {
display: none
}
</style>
</noscript>
</head>
…

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 prevent submit button from submitting after textbox loses focus

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

jQuery confirmation of page leaving

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

Why this submit all form code isn't working?

The code below is colouring the input but not submitting the form in chrome. It's working in Firefox:
<script type="text/javascript">
$(function(){
$('input').keypress(function(event) {
if (event.keyCode == '13') {
//alert($(this).parentsUntil('form').css('color'));
$('form').css('color','red');
$('form').submit();
}
});});</script>
Please note that the submit button is set to display:none, if I change it to visibility:hidden, it works but it reserve the place which is not what I want.
Thanks.
EDIT
Here's a full example as requested below:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script>
<title>دخول</title>
<script type="text/javascript">
$(function(){
$('input').keypress(function(event) {
if (event.keyCode == 13) {
$(this).parents('form').submit();
}
});
});
</script>
</head>
<body>
<form action="http://www.yahoo.com" method='post'>
<table >
<tr><td>name: </td><td><input type="text" name="username" value=""></td></tr>
<tr><td>password: </td><td><input type="password" name="password" value=""></td></tr>
<tr><td colspan=2>Login
<div style="display: none;"><input type="submit" name="submit" value="Login" id="loginfrm"></div></td></tr>
</table>
</form>
your problem is that you named your submit button submit, the browser sees that as a used name, give the submit button a name like dosubmit or whatever and it works.
with name submit (does not work)
http://www.jsfiddle.net/pVUwW/
with name dosubmit (works)
http://www.jsfiddle.net/pVUwW/1/
the only difference in those is the name of the submit.
Other than that i changed the event.keyCode to event.which from your original code, see http://api.jquery.com/event.which/ for explanation why.
This is strange, just tried this in Chrome, it works correctly even without your code (keypress)
http://jsfiddle.net/72Nbm/

Categories

Resources