jQuery validation within dialog - javascript

I'm creating popup forms using jQuery dialog & validation plugin. It all works fine except one thing - the error message doesn't clear off when form is closed, i.e. the form does not "reset" itself back to its initial state when user close the form.
My codes are as follows:
HTML
<div id="popupfrm" title="Action Plan Details">
<form id="frmAClientActionPlanDetails" method="post" action="">
<ul>
<li>
<label id="lActionPlanTitle" for="lActionPlanTitle">Action Plan Title*:</label>
<input id="iActionPlanTitle" name="iActionPlanTitle" class="text" size="50" />
</li>
<li id="iActionPlanTitleMsg" class="errorStr"></li>
<li>
<label id="lDescription" for="lDescription">Description*:</label>
<input id="iDescription" name="iDescription" class="text" size="50" />
</li>
<li id="iDescriptionMsg" class="errorStr"></li>
<li>
<label id="lNotes" for="lNotes">Notes:</label>
<textarea id="iNotes" name="iNotes" cols="35" rows="4" class="text"></textarea>
</li>
<li id="iNotesMsg" class="errorStr"></li>
<li>
<label id="lDateUploaded" for="lDateUploaded">Date Uploaded:</label>
<input id="iDateUploaded" name="iDateUploaded" class="text" size="50" maxlength="10" readonly="readonly" />
</li>
<li id="iDateUploadedMsg" class="errorStr"></li>
<li>
<label id="lFileUploaded" for="lFileUploaded">File Uploaded:</label>
<input id="iFileUploaded" name="iFileUploaded" type="file" value=""/>
</li>
<li id="iFileUploadedMsg" class="errorStr"></li>
<li><br />
</li>
<li>
<input type="submit" id="btnUpdate" name="btnUpdate" value="Update" class="button" />
</li>
</ul>
</form>
</div>
JS - dialog
$(document).ready(function(){
var iActionPlanTitle = $( "#iActionPlanTitle" ),
iDescription = $( "#iDescription" ),
iNotes = $( "#iNotes" ),
iFileUploaded = $( "#iFileUploaded" ),
allFields = $( [] ).add( iActionPlanTitle ).add( iDescription ).add( iNotes ).add( iFileUploaded );
alert(allFields);
$('#popupfrm').dialog({
autoOpen: false,
width: 600,
modal: true,
close: function() {
allFields.val( "" ).removeClass( "error" );
}
});
// Popup Links
$('#popupfrm_link').click(function(){
$('#popupfrm').dialog('open');
return false;
});
$('#popupfrm_link2').click(function(){
$('#popupfrm').dialog('open');
return false;
});
//hover states on the static widgets
$('#popupfrm_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
JS - validation
$('#frmAClientActionPlanDetails').validate({
rules: {
iActionPlanTitle: {
required: true,
minlength: 2
},
iDescription: {
required: true,
minlength: 2
}
},
messages: {
iActionPlanTitle: {
required: "Please enter a title."
},
iDescription: {
required: "Please enter a description."
}
},
errorElement: "li",
});
Can anyone please advise? Thanks!

On closing the dialog box, you have to clear the errormsg string value :
close: function() {
.
.
$('#iFileUploadedMsg').val('');
.
.
}

Debug your page and check what is the class or id your error labels are taking. Then based on those attributes you can clear text from them.
For clearing you can use something like this:
$(id).html('');

Related

trigger jquery modal popup on form submit

This is my first time working with jquery modals. I'm trying to display the popup only when the form is submitted. But instead, it's displaying on page load. How do I fix it?
<script>
$( function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Yes": function() {
$( this ).dialog( "close" );
},
"No": function() {
$( this ).dialog( "close" );
}
}
});
} );
</script>
<div id="dialog-confirm" title="Not so fast">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px
20px 0;"></span>Did you want to add a third for only $50? Click Yes to add</p>
</div>
<form id="orderform" action="/action_page.php">
Package 1:<br>
<input type="text" name="packageonename" value="">
<br>
Package 2:<br>
<input type="text" name="packagetwoname" value="">
<br><br>
<input type="submit" value="Submit">
</form>
In order to prevent the dialog from automatically opening you can set autoOpen property to false when initializing the dialog.
Then, on form's submit event, you could open the dialog by calling element.dialog("open").
Note that I have added an event.preventDefault() in the submit event handler to prevent the form from submitting.
$(function() {
$("#dialog-confirm").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
autoOpen: false,
buttons: {
"Yes": function() {
$(this).dialog("close");
},
"No": function() {
$(this).dialog("close");
}
}
});
$("#orderform").on("submit", function(e) {
$("#dialog-confirm").dialog("open");
e.preventDefault();
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="dialog-confirm" title="Not so fast">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px
20px 0;"></span>Did you want to add a third for only $50? Click Yes to add</p>
</div>
<form id="orderform" action="/action_page.php">
Package 1:<br>
<input type="text" name="packageonename" value="">
<br> Package 2:<br>
<input type="text" name="packagetwoname" value="">
<br><br>
<input type="submit" value="Submit">
</form>
You can do like this
$('#orderform').submit(function() {
$("#dialog-confirm").dialog("open");
return true; // return false to cancel form action
});

calculation output does not display in modal

my modal does not display my output (empty modal) except for the title. I have checked and the output is working when i don't display it within the modal.
what can i change to display the output?
<script>
$( function() {
$( "#mortgageResults" ).dialog({
autoOpen: false,
modal: false,
resizable: false,
autoResize: true,
show: {
effect: "clip",
duration: 400
},
hide: {
effect: "drop",
duration: 400
}
});
$( "#mortgagebtn" ).on( "click", function() {
$( "#mortgageResults" ).dialog( "open" );
return false;
});
} );
</script>
computation:
<div id="calculator_one">
<?php
$borrow = $_POST['borrow']; //amount borrowed
$interest = $_POST['interest']; //interest rate
$term = $_POST['term']; //term
$months = ( $term * 12 );
$answer = ($borrow * ($interest / 100)) / 12;
$answer_two = ( $borrow * (($interest/12) / 100) / ( 1 - pow( 1 + (($interest/12) / 100), -$months)) ); ?>
<form id="calcualtor" action="" method="post" class="calculator">
<label class="calcAmount">Amount to borrow (₱)</label>
<input class="calcAmount" type="text" name="borrow" maxlength="6" />
<br />
<label class="calcInterest">Interest (%)</label>
<input class="calcInterest" type="text" name="interest" maxlength="4" />
<br />
<label class="calcTerm">Term (Years)</label>
<input class="calcTerm" type="text" name="term" maxlength="2" />
<br />
<button id="mortgagebtn" type="submit">Calculate</button>
</form>
</div>
my display output:
<div id="mortgageResults" title="Mortgage Results">
<?php
if (isset($_POST['mortgagebtn'])){
echo "<p class='calc_header'>Results</p>";
echo "<div id='results'><p class='calc_result'>Based on borrowing <span class='mortgage'>₱", number_format($borrow) , "</span> over <span class='mortgage'>", ($term), " years</span> at <span class='mortgage'>", ($interest), "%</span>, your monthly repayments would be:</p>";
echo "<p class='calc_result'>Interest Only <span class='mortgage'>₱", number_format($answer,2), "</span></p>";
echo "<p class='calc_result'>Repayment <span class='mortgage'>₱", number_format($answer_two,2), "</span></p></div>";} ?>
</div>
The issue is here:
<button id="mortgagebtn" type="submit">Calculate</button>
here you have not assign the name. And you are trying to check it like:
if (isset($_POST['mortgagebtn'])){
Assign the name like:
<button id="mortgagebtn" name="mortgagebtn" type="submit">Calculate</button>
and try again.

JQuery validation accepts even if input contains only whitespaces

I am having trouble validating if input fields contains only whitespaces. I have specified the required rule for the required fields but it still works if I just type spaces. also, noSpace rule for username field does not seem to work. It disables validation for the other fields. Here is my markup.
<form method=post class="form-auth-small" action="../php/controller/registration_controller.php">
<div class="form-group row m-t-10px">
<div class="col-sm-6 text-left m-b-5px">
<label><h5>RANK: </h5></label>
<select class="form-control" name="rank" required="required">
<option value="rank1">NUP</option>
<option value="rank2">PO1</option>
<option value="rank3">PO2</option>
<option value="rank4">PO3</option>
<option value="rank5">SPO1</option>
<option value="rank6">SPO2</option>
<option value="rank7">SPO3</option>
<option value="rank8">SPO4</option>
<option value="rank9">PINSP</option>
<option value="rank10">PSINSP</option>
<option value="rank11">PCINSP</option>
<option value="rank12">PSUPT</option>
<option value="rank13">PSSUPT</option>
<option value="rank14">PCSUPT</option>
<option value="rank15">PDIR</option>
<option value="rank16">PDDG</option>
<option value="rank17">PDG</option>
</select>
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>USERNAME: </h5></label>
<input class="form-control" name="username" placeholder="Username must only contain characters [A-Z] and numbers [0-9]" type="text" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>FIRST NAME: </h5></label>
<input class="form-control" name="fname" type="text" minlength="1" required="required">
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>PASSWORD: </h5></label>
<input class="form-control" name="pwd" placeholder="Choose a strong password" type="password" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>MIDDLE NAME: </h5></label>
<input class="form-control" name="mname" type="text" minlength="1" required="required">
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>EMAIL: </h5></label>
<input class="form-control" name="email" type="email" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>LAST NAME: </h5></label>
<input class="form-control" name="lname" type="text" minlength="1" required="required">
</div>
</div>
<div class="form-group clearfix m-b-5px">
<button type="submit" name="btnRegister" class="btn btn-primary btn-lg btn-block">REGISTER</button>
</div>
<div class="bottom m-b-15px">
<span><i class="fa fa-lock"></i> Already have an account? Sign in.</span>
</div>
</form>
JS (Without noSpace rule)
$(document).ready(function () {
$('.form-auth-small').validate({
rules: {
rank: {
required: true
},
username: {
required: true,
minlength: 3
},
fname: {
required: true
},
mname: {
required: true
},
lname: {
required: true
},
pwd: {
required: true
},
email: {
required: true
}
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
// Add `has-feedback` class to the parent div.form-group
// in order to add icons to inputs
element.parents( ".col-sm-5" ).addClass( "has-feedback" );
error.insertAfter( element );
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !element.next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" ).insertAfter( element );
}
},
success: function ( label, element ) {
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !$( element ).next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-ok form-control-feedback'></span>" ).insertAfter( $( element ) );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-6" ).addClass( "has-error" ).removeClass( "has-success" );
$( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
},
unhighlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-6" ).addClass( "has-success" ).removeClass( "has-error" );
$( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
}
});
});
DEMO
Thank you in advance!
Just add this method before your jQuery validate function run::
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No space please and don't leave it empty");
AND use
noSpace: true
for each field you want.
Try this
$(document).ready(function() {
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No space");
$(".form-auth-small").validate({
rules: {
username : {
noSpace: true
}
}
});
})
$(".form-auth-small").validate({
rules: {
username : {
required: true,
normalizer: function(value) {
return $.trim(value);
}
}
}
});
use normalizer , in which it will trim or remove all whitespaces.
simple solution.enjoy your day

add class to footer after click button from submit

Hello i'm new in php and javascript developer and i have a question.
i have an html file with a form for registration and a footer section
In the registration form when i add sucessfully a user i hide the input text and show a message, but the footer section go up.
For fix this visual problem i want add the "footer-fixed-bottom" to fotter section but only when hide the input text in this way i block the footer at the end of page.
i have an html and a java script in external file... my problem is access to footer section from javascript.
html code
<section class="page-login section-4">
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-md-6 col-md-offset-3">
<div class="well well-6 mb0">
<h2 class="section-title-2 st-2 mb20">Registrazione</h2>
<p>Possiedi gi&agrave un account ? Login</p>
<form id="RegistrationForm" class="register-form form form-2" method="post" action="php/registrati.php">
<label>
Nome Utente
<input name="name " id="name" type="text" required class="form-control" placeholder="Nome">
</label>
<label>
Email <span class="required">*</span>
<input name="email " id="email" type="email" required class="form-control" placeholder="Email">
</label>
<label>
Password <span class="required">*</span>
<input name="password " id="password" type="password" required class="form-control" placeholder="Password">
</label>
<label>
Confirm Password <span class="required">*</span>
<input name="confirmpassword" id="confirmpassword" type="password" required class="form-control" placeholder="Confirm Password">
</label>
<label class="hideFormcontrol">
<input type="checkbox" name="terms" id="terms" value="ok" required class="hideFormcontrol">
Acconsento a DBSoftware Termini e condizioni e Privacy
</label>
<div class="alert alert-success hidden br0" id="contact-success">
<span class="glyphicon glyphicon-ok "></span>
<strong>Success!</strong> Grazie per esserti registrato.
</div>
<div class="alert alert-danger hidden br0" id="contact-error">
<span class="glyphicon glyphicon-remove "></span>
<strong>Error!</strong> Le password inserite non corrispodono.
</div>
<div class="alert alert-danger hidden br0" id="contact-present">
<span class="glyphicon glyphicon-remove "></span>
<strong>Error!</strong> Email gi&agrave presente nel database.
</div>
<div>
<input type="submit" class="hideFormcontrol btn voyo-btn-2 rounded mt5" value="Registrati">
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer class="footer-wrapper no-border" >
<div class="sub-footer">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="pull-left">
<p>© Copyright 2015 DBSoftware</p>
</div>
<div class="pull-right">
<ul class="social-icon dark-2 rounded">
<li><i class="fa fa-facebook"></i></li>
<li><i class="fa fa-twitter"></i></li>
<li><i class="fa fa-google-plus"></i></li>
<li><i class="fa fa-tumblr"></i></li>
<li><i class="fa fa-rss"></i></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- END Sub footer -->
</footer>
<!-- END Footer -->
jscript with validate code
if ($('.register-form').length) {
var form = {
init: false,
initialize: function () {
// if form is already initialized, skip
if (this.init) {
return;
}
this.init = true;
var $form = $(".register-form");
$form.validate({
submitHandler: function (form) {
// Loading Button
var btn = $(this.submitButton);
btn.button("loading");
// Ajax Submit
$.ajax({
type: "POST",
url: $form.attr("action"),
data: {
"name": $form.find("#name").val(),
"email": $form.find("#email").val(),
"password": $form.find("#password").val(),
"confirmpassword": $form.find("#confirmpassword").val(),
"terms": $form.find("#terms").val()
},
dataType: "json",
success: function (data) {
var $success = $form.find("#contact-success"),
$error = $form.find("#contact-error"),
$present = $form.find("#contact-present");
switch (data.response) {
case "success":
$success.removeClass("hidden");
$error.addClass("hidden");
$present.addClass("hidden");
//Reset Form
$form.find(".form-control")
.val("")
.blur()
.parent()
.removeClass("has-success")
.removeClass("has-error")
.addClass("hidden")
.find("label.error")
.remove();
$form.find(".hideFormcontrol")
.addClass("hidden")
break;
case "error":
$error.removeClass("hidden");
$success.addClass("hidden");
$present.addClass("hidden");
break;
case "present":
$error.addClass("hidden");
$success.addClass("hidden");
$present.removeClass("hidden");
break;
}
},
complete: function () {
btn.button("reset");
}
});
},
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
password: {
required: true
},
confirmpassword: {
required: true,
equalTo: "#password"
},
terms: {
required: true
}
},
messages: {
name: {
required: "<span class='form-message-error'>Please enter your name!</span>"
},
email: {
required: "<span class='form-message-error'>Please enter your email address!</span>",
email: "<span class='form-message-error'>Please enter a valid email address!</span>"
},
password: {
required: "<span class='form-message-error'>Please enter a password!</span>"
},
confirmpassword: {
equalTo: "<span class='form-message-error'>Prego, inserire la stessa password!</span>"
},
terms: {
required: "<span class='form-message-error'>Prego, selezionare le condizioni della privacy!</span>"
}
},
highlight: function (element) {
$(element)
.parent()
.removeClass("has-success")
.addClass("has-error");
},
success: function (element) {
$(element)
.parent()
.removeClass("has-error")
.addClass("has-success")
.find("label.error")
.remove();
}
});
} // END initialize
}; // END form object
form.initialize();
}
i want add in the jscript a part where i can addclass in the footer section class. In the jscript i can access to all element in the form section but i can't access the element out of form section, how can reference to footer section in the section code?
case "success":
$success.removeClass("hidden");
$error.addClass("hidden");
$present.addClass("hidden");
//Reset Form
$form.find(".form-control")
.val("")
.blur()
.parent()
.removeClass("has-success")
.removeClass("has-error")
.addClass("hidden")
.find("label.error")
.remove();
$form.find(".hideFormcontrol")
.addClass("hidden")
break;
thanks a lot for help.
You can use element/type selector to select the <footer>, and use addClass() to add a class to the element.
Using type selector:
$('footer').addClass('footer-fixed-bottom');
Using class selector:
$('.footer-wrapper').addClass('footer-fixed-bottom');

How to get a value from the input and add to the href jquery

I would like to do something like the window of favorites on google chrome so the idea is write a hiperlink and then the link appears on the page.I m using jquery but doesn't work
html:
<div id="Add" title="Add Link">
<form>
<fieldset>
<label for="dir">URL</label>
<input id="dir" type="url" class="text ui-widget-content ui-corner-all"/>
</fieldset>
</form>
<div id="cuadro"></div>
$(function(){
var a = $("#Add");
a.dialog({
autoOpen: false,
height:350,
width:250,
modal: true,
buttons: {
"Accept": function(){ //Accept
AddLink();
$( this ).dialog( "close" );
},
"Reset": function(){//Reset
dir.val(" ")
},
"Cancel": function() {//Cancel
$( this ).dialog("close");
}
},
close: function() {
$( this ).dialog( "close" );
}
});
});
function AddLink(){
var dir=$("#dir);
var link=dir.val();
alert(dir.val());
$("#cuadro").append('<li>link1</li>');
}
If you want to use your linkvariable as the href then you need to change
$("#cuadro").append('<li>link1</li>');
to
$("#cuadro").append('<li>link1</li>');
DEMO FIDDLE
I'm not sure exactly what you meant by "write a hiperlink and then the link appears on the page", so I'm going to do my best and guess that this is what you want:
User types a URL into the input box.
You display it in some div below it.
HTML
<form>
<fieldset>
<label for="dir">URL</label>
<input id="dir" type="url" class="text ui-widget-content ui-corner-all"/>
</fieldset>
</form>
<p></p>
CSS
p {
color: green;
margin: 8px;
}
JavaScript
$( "#dir" )
.keyup(function() {
var value = $( this ).val();
$( "p" ).text( value );
})
.keyup();

Categories

Resources