Multiple form validation: where to put $ajax when valid? - javascript

I have multiple forms on a page and I'm trying to validate them with jQuery. The validation section is working, however, I can't figure out where to put the ajax if the form is valid.
Update: I have no idea how many forms there will be as these are dynamically generated.
<p>reload</p>
<div id="messages">
<div id="message">
<ul></ul>
</div>
</div>
<form action="#" method="post" class="form">
<select name="foo" class="required">
<option value="">Select...</option>
<option value="foo">Foo</option>
</select>
<input type="text" name="bar" class="required">
<input type="submit" value="submit">
</form>
<form action="#" method="post" class="form">
<select name="foo" class="required">
<option value="">Select...</option>
<option value="snafoo">Snafoo</option>
</select>
<input type="text" name="bar" class="required">
<input type="submit" value="submit">
</form>
<script src="//code.jquery.com/jquery.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script>
$('.form').each(function() {
$(this).validate({
submitHandler:function(form) {
var foo = $(form).find('select[name=foo]').val();
var bar = $(form).find('input[name=bar]').val();
form.submit();
},
rules: {
foo: {
required: true
},
bar: {
required: true
}
},
messages: {
foo: {
required: 'Please select a foo'
},
bar: {
required: 'Please enter a bar'
}
},
errorContainer: $('#messages'),
errorLabelContainer: $('#messages ul'),
wrapper: 'li',
// callback functions to work with bootstrap
highlight:function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight:function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
});
// if the form is valid, do some ajax...
$('.form').on('submit', function(){
if($(this).valid()){
// testing...
alert(foo);
$.ajax({
type: 'POST',
url: 'script.php',
data: 'foo=' + foo,
cache: false,
success: function(data){
// do stuff...
}
});
}
return false;
});
</script>

foo is undefined in your submit event. Need to add the following string:
$('.form').on('submit', function(){
var foo = $('select', this).val();
...
});

Related

Validate fields using jquery

I'm creating a form that requires to enter some fields.
The basic required attribute won't work on me, so I would like to use jQuery.
Then when those fields were already filled, the submit button will be enabled.
here's my code:
$(function() {
$('#catalog_order').validate(
{
rules:{
schedule: {
required: true
}
},
messages:{
schedule: "Please indicate schedule",
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" /> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<label for="schedule"> Date: </label> <input type="date" id="schedule" name="schedule" value="M-D-YY"/> <!-- REQUIRED -->
<label for="figurine_select"> Figurine/s: </label> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<select name="figurine_sel" id="figurine_select" />
<option selected value=" ">--Figurines--</option>
<option value="angel">Angel</option>
<option value="teletubies">Teletubies</option>
</select>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled="disabled" />
</form>
Hope someone can help me out.
Thank you!!
This Fiddle Should work
Note that for every field you should specify all its option inside js object ( between brackets )
schedule: {
required: true
},
Below working snippet
jQuery.validator.addMethod("dateFormat", function(value, element) {
console.log(value,/^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value));
return /^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value);
}, "Invalid Date !");
$(function() {
$('#checkin').validate(
{
rules:{
schedule: {
required:true,
dateFormat: true,
}
},
messages:{
required:"Required Field !"
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" />
<label for="schedule"> Date: </label> <input id="schedule" name="schedule" placeholder="M-D-YY"/>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled />
</form>
This is how I validate that.
return false is just the same us disabling it
<form role="form" id="checkin" name="checkin" method="post">
<input id="dedicatalog"/>
<input id="date" type="date"/>
</form>
<script>
$('#checkin').on('submit', function() {
var dedicatalog = $.trim($('#dedicatalog').val());
var date = $.trim($('#date').val());
if(dedicatalog == '' || date == '') {
return false;
}
});
</script>
You can use the invalidHandler parameter to check for any invalid fields:
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#button').hide();
} else {
$('#button').show();
}
}

Forms - synchronous request and displaying a div on submission

I'm making a yahtzee-type two player dice game. To start the game, the user enters 2 names and submits, which should start the game and display the dice area. I've done a lot of trial and error, but I haven't been able to submit the form, get the input, and show the play area.
HTML:
<div id="top_area">
<div id="new_game_form">
<form action="http://examples.funwebdev.com/process.php" method="post" name="new_game">
Player 1:
<br>
<input type="text" name="player1">
<br> Player 2:
<br>
<input type="text" name="player2">
<br>
<input id="newGameSubmit" type="submit" value="Start Game">
</form>
</div>
<div id="player_turn">
Please enter player names and load a new game!
</div>
<div id="player_scores">
Current Score
</div>
</div>
<div id="play_area">
<div class="play_div" id="game_board">
<a class="diceimage" id="dice1"></a>
<a class="diceimage" id="dice2"></a>
<a class="diceimage" id="dice3"></a>
<a class="diceimage" id="dice4"></a>
<a class="diceimage" id="dice5"></a>
</div>
<div class="play_div" id="submit_move">
<form class="play_div" action="http://examples.funwebdev.com/process.php" method="post" name="submit_move">
<input type="submit" value="Roll the dice!" onclick="rollDice()">
</form>
</div>
<div id="submit_score">
<form action="">
<select name="Score">
<option value="2OfAKind">Two of a kind</option>
<option value="3OfAKind">Three of a kind</option>
<option value="4OfAKind">Four of a kind</option>
<option value="5OfAKind">Five of a kind</option>
<option value="fullHouse">Full house</option>
</select>
<input type="submit" value="Submit your score">
</form>
</div>
</div>
JavaScript:
$(document).ready(function () {
//game setup
$("#new_game").on("submit", newGameListener);
});
function newGameListener(e) {
e.preventDefault();
setUpUsers();
$(".play_area").show();
}
I've also tried:
$(document).ready(function () {
$("#new_game").submit(function (event) {
var newGameData = {
"player1": $("input[name=player1]").val(),
"player2": $("input[name=player2]").val()
};
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
(".play_area").show();
});
event.preventDefault();
});
});
and:
$(document).ready(function () {
$("#newGameSubmit").click(function () {
event.preventDefault();
var player1 = $("#player1").val();
var player2 = $("#player2").val();
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: dataString,
cache: false,
success: function () {
(".play_area").show();
}
});
}
return false;
});
});
I suspect my usage of form name may be wrong (should I be using id instead? is the # right? etc.) but I've played around with that and still couldn't get it.
I tried modifying your last approach. I hope it will work once you update it with below modified code:
In your HTML; play_area is an id given to <div> element. So to deal with it JQuery we need to use # and not the dot. Like $("#play_area").show();
CSS:
#play_area{
display:none;
}
Jquery:
$(document).ready(function () {
$("form[name=new_game]").submit(function (e) {
return false;
});
$("#newGameSubmit").click(function (event) {
event.preventDefault();
var player1 = $("#player1").val();
var player2 = $("#player2").val();
var newGameData = {
"player1": player1,
"player2": player2
};
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: newGameData,
cache: false,
success: function () {
$("#play_area").show();
}
});
});
});
I have created a fiddle too; but it won't work because we can't make cross domain Ajax calls from within jsfiddle.net to your funwebdev.com domain.
But you can refer it:
http://jsfiddle.net/vijayP/bkvw95jn/2/
Fixed the form not being submitted. Check the following code.. !!
<script>
jQuery(document).ready(function($) {
$("#new_game").submit(function() {
var newGameData = {
"player1": $("input[name=player1]").val(),
"player2": $("input[name=player2]").val()
};
$.ajax({
type: "POST",
url: "http://examples.funwebdev.com/process.php",
data: newGameData,
dataType: 'json',
encode: true,
success: function(data) {
(".play_area").show();
alert(data);
}
});
return false;
});
});
</script>
</head>
<body>
<div id="top_area">
<div id="new_game_form">
<form action="#" method="post" id="new_game" name="new_game">
Player 1:
<br>
<input type="text" name="player1">
<br> Player 2:
<br>
<input type="text" name="player2">
<br>
<input id="newGameSubmit" type="submit" value="Start Game">
</form>
</div>
<div id="player_turn">
Please enter player names and load a new game!
</div>
<div id="player_scores">
Current Score
</div>
</div>
<div id="play_area">
<div class="play_div" id="game_board">
<a class="diceimage" id="dice1"></a>
<a class="diceimage" id="dice2"></a>
<a class="diceimage" id="dice3"></a>
<a class="diceimage" id="dice4"></a>
<a class="diceimage" id="dice5"></a>
</div>
<div class="play_div" id="submit_move">
<form class="play_div" action="http://examples.funwebdev.com/process.php" method="post" name="submit_move">
<input type="submit" value="Roll the dice!" onclick="rollDice()">
</form>
</div>
<div id="submit_score">
<form action="">
<select name="Score">
<option value="2OfAKind">Two of a kind</option>
<option value="3OfAKind">Three of a kind</option>
<option value="4OfAKind">Four of a kind</option>
<option value="5OfAKind">Five of a kind</option>
<option value="fullHouse">Full house</option>
</select>
<input type="submit" value="Submit your score">
</form>
</div>
</div>

jquery validation plugin ajax submit a form not working

I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is working but ajax code will do two time and the form cannot send out.
bootstrap form
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic</label>
<input class="form-control" type="text" name="topic" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label "> ruser: </label>
<input class="form-control" type="text" name="ruser" value="<?php echo $username; ?>" readonly/>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
<button class="btn btn-success" id="submitcontact">ok</button>
</form>
javascript
$(document).ready(function () {
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages: {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter nuser'
},
content: {
required: 'enter content'
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function (msg) {
alert("ok!");
if (msg == 'ok') {
alert(msg);
location.reload()
}
},
error: function () {
alert("failure");
}
});
return false;
}
});
$('#submitcontact').click(function () {
$('form.contact').submit();
})
});
How can i fix the problem?
The jsfiddle
You probably need to remove this bit:
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Please see the example:
http://jsfiddle.net/8eoreedb/1/
Use .valid() method:
Description: Checks whether the selected form is valid or whether all selected elements are valid.
Updated Fiddle
$('#submitcontact').on('click', function() {
if ($('form.contact').valid()) {
// Form is valid
$('form.contact').submit();
}
});
Doc: http://jqueryvalidation.org/valid/
Demo: http://jsfiddle.net/8eoreedb/4/

How to perform validation using jquery.validate?

I am trying to use jquery.validate to validate some fields in a jquery modal dialog. To practice I thought I would create a simple JSFiddle to make sure my syntax is correct. I'm missing something, hopefully someone can help.
Here is my simple form:
<form id="myform" method="post" action="#">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
Here is my jquery:
$("#submitEdit").click(function (event) {
event.preventDefault();
Validate();
});
function Validate()
{
$("#frmEdit").validate({
rules: {
QtyOnHand: {
required: true
}
},
messages: {
QtyOnHand: {
required: 'Qty Required'
}
}
});
}
Working Fiddle Demo
Just keep
$("#frmEdit").validate({//this will validate you don't need call validate function
rules: {
QtyOnHand: {
required: true
}
},
messages: {
QtyOnHand: {
required: 'Qty Required'
}
}
});
Remove
$("#submitEdit").click(function (event) {
event.preventDefault();//stopping validation to occur
}
Problem Fiddle
<form id="myform" method="post" action="#">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
JS:
$("#myForm").validate({
rules: {
field1: {
required: true
},
field2: {
required: true
}
},
messages: {
field1: {
required: 'field1 Required'
},
field2: {
required: 'field2 Required'
}
}
});
check
Fiddle

remove jquery validation error message after select value

I have a problem using bootstrap select plugin and jQuery validation. when i select value, error message This field is required not remove While normal validation(without bootstrap select plugin) after select value error message auto remove. how to fix this problem?
JSFIDDLE
HTML:
<form id="myform"> <----With Select Plugin
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
<br/>
<input type="submit" />
</form>
<form id="myform1"> <----Without Select Plugin
<select name="fruit">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
<br/>
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('.selectpicker').selectpicker();
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform1" ).validate({
rules: {
fruit: {
required: true
}
}
});
You need to check the validity on change
$('.selectpicker').selectpicker().change(function(){
$(this).valid()
});
Demo: Fiddle
Try this
$('select').change(function(){
if ($(this).val()!="")
{
$(this).valid();
}
});
Here is the Fiddle

Categories

Resources