Jquery validation on submit form - php

I want corresponding error message to display when input boxes is empty on submit button clicked but my below code gives me the first error message i.e. "Please enter a question". Where I am doing wrong
Below is My HTML and JQUERY code:
HTML:
<form enctype="multipart/form-data" onsubmit=" return ValidateForm(this)" class="form-horizontal" id="PollIndexForm" method="post" action="/polls" accept-charset="utf-8">
<textarea name="data[Question][question]" id="message1" maxlength="50" onKeyup="return update()" ></textarea>
<span class="validate" id="validatemessage1"></span>
<input name="data[Option][optiona][]" id="optiona" type="text" class="form-control">
<span class="validate" id="validateoptiona"></span>
<input name="data[Option][optiona][]" id="optionb" type="text" class="form-control">
<span class="validate" id="validateoptionb"></span>
<input class="btn btn-lg btn-primary" type="submit" value="Save" />
JQUERY:
<script>
$(document).ready(function (){
$("#message1").keypress(function(){
$("#validatemessage1").hide();
});
$("#optiona").keypress(function(){
$("#validateoptiona").hide();
});
$("#optionb").keypress(function(){
$("#validateoptionb").hide();
});
$("#optionc").keypress(function(){
$("#validateoptionc").hide();
});
$("#optiond").keypress(function(){
$("#validateoptiond").hide();
});
$("#autoreply").keypress(function(){
$("#validateautoreply").hide();
});
});
function ValidateForm(form){
var message1=document.getElementById("message1").value;
if(message1==''){
$(".validate").html("Please enter a question").addClass("ValidationErrors");
return false;
}
var optiona=document.getElementById("optiona").value;
if(optiona==''){
$(".validate").html("Please enter option A").addClass("ValidationErrors");
return false;
}
var optionb=document.getElementById("optionb").value;
if(optionb==''){
$(".validate").html("Please enter option B").addClass("ValidationErrors");
return false;
}
var optionc=document.getElementById("optionc").value;
if(optionc==''){
$(".validate").html("Please enter option C").addClass("ValidationErrors");
return false;
}
var optiond=document.getElementById("optiond").value;
if(optiond==''){
$(".validate").html("Please enter option D").addClass("ValidationErrors");
return false;
}
var autoreply=document.getElementById("autoreply").value;
if(autoreply==''){
$(".validate").html("Please enter a autoreply message").addClass("ValidationErrors");
return false;
}
}
</script>

If I understand correctly, you have a problem because only the first validation is executed (at least this was the case when I tried your code on my PC).
What I suggest is that you use jQuery in all places (because you obviously can since you do partially) so my suggestion is the following.
HTML:
<textarea name="data[Question][question]" id="message1" maxlength="50"" ></textarea>
<span class="validate" id="validatemessage1">validatemessage1</span>
</br>
<input name="data[Option][optiona][]" id="optiona" type="text" class="form-control">
<span class="validate" id="validateoptiona">validateoptiona</span>
</br>
<input name="data[Option][optiona][]" id="optionb" type="text" class="form-control">
<span class="validate" id="validateoptionb">validateoptionb</span>
<input id="submitbtn" class="btn btn-lg btn-primary" type="submit" value="Save" />
javascript:
$(document).ready(function (){
$("#message1").keyup(function(){
console.log("validate");
$("#validatemessage1").hide();
});
$("#optiona").keyup(function(){
$("#validateoptiona").hide();
});
$("#optionb").keyup(function(){
$("#validateoptionb").hide();
});
$("#submitbtn").on("click", function(e){
if(ValidateForm(("#PollIndexForm")) == false){return false} else {return true};
});
function ValidateForm(form){
var end = true;
var message1=$("#message1").val();
console.log("message1: "+message1+"x"+message1.length);
if(message1.length==0){
$("#validatemessage1").html("Please enter a question").addClass("ValidationErrors");
$("#validatemessage1").show();
end = false;
}
var optiona=$("#optiona").val();
if(optiona==''){
$("#validateoptiona").html("Please enter option A").addClass("ValidationErrors");
$("#validateoptiona").show();
end = false;
}
var optionb=$("#optionb").val();
if(optionb==''){
$("#validateoptionb").html("Please enter option B").addClass("ValidationErrors");
$("#validateoptionb").show();
end = false;
}
return end;
}
});
This way you will handle submit button via jQuery and call function ValidateForm every time you click the button. Also, if you had cleared the field before after input, the message didn't show because it was hidden and subsequent .html() function only changes it's value so you need to .show() it again.

Related

how to submit a form through ajax only if the validation function retun true

I have a form in my page. onsubmit i have a function for validation. i need to send the values of form through ajax only if the validation function return true.
But my data is being submitted even if the validation return false. please help me out.
here is my code
form
<form id="form" method="post" onsubmit="return val()">
<input type="text" name="name" id="t1" placeholder="name" class="i">
<span id="msg1"></span><br>
<input type="number" name="roll" id="t2" placeholder="roll no" min="0" class="i">
<span id="msg2"></span><br>
<input type="number" name="age" id="t3" placeholder="age" min="0" class="i">
<span id="msg3"></span><br>
<input type="submit" name="submit" id="submit" value="submit">
</form>
The val function
function val()
{
var status=true;
var name=$("#t1").val();
var age=$("#t2").val();
var roll=$("#t3").val();
if(name=="")
{
$("#msg1").text("*name cannot be empty");
status=false;
}
if(roll=="")
{
$("#msg2").text("*roll number cannot be empty");
status=false;
}
if(age=="")
{
$("#msg3").text("*age cannot be empty");
status=false;
}
return status;
}
the function that i need to work only if the val() return true
$("form").submit(function(e){
e.preventDefault();
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+"att_controller/add_stud",
data: $("#form").serialize(),
success: function(){
if(confirm("added")){
$(".i").val("");
}
}
})
})
Get rid of inline submit handler and use the val() method in the unobtrusive event handler.
$("#form").submit(function (e) {
e.preventDefault();
if (val()) {
$.ajax(....)
}
});

Type input characters in html form need match - jQuery?

How do I type in a HTML textbox and if the first 3 characters dont match a set variable - then display an error? I need to lose the error and display text next to the input after the 3rd character
I'm thinking jQuery, AJAX, PHP - not sure. I just don't want to use an alert box.
And this needs to be before a user enters the submit button...
<form>
<input type="text" id="test"/><br>
<input type="button" id="txt" value="Submit" />
</form>
$(document).ready(function(){
$("#txt").click(function(){
var text = $("#test").val();
var comparingText = "yes";
if (text != comparingText){
alert( $("#test").val());
}
});
});
It will show this alert after write yes.
you can use it as you want.
$( "#test" ).keyup(function() {
var test = $( "#test" ).val();
if(test == 'yes'){
alert( "your Error msg" );
}
});
You can use a <span> element, next to the <input> element to display an error message and, as you said, avoid using the alert box.
JS
HTML
<form>
<input type="text" id="test" oninput="submitData(this.value)"/>
<span id="textError"></span><br/>
<input type="button" id="txt" value="Submit" />
</form>
JS
function submitData(input) {
if (input != "yes") {
document.getElementById("textError").innerHTML = "Your Error MSG";
} else {
document.getElementById("textError").innerHTML = "";
}
}
JS + jQuery
In this case I'm taking Mamunur Rashid's answer to complement the code.
HTML
<form>
<input type="text" id="test"/> <span id="textError"></span><br/>
<input type="button" id="txt" value="Submit" />
</form>
jQuery
$(document).ready(function(){
$("#test").keyup(function(){
var test = $("#test").val();
if (test != "yes") {
$("#textError").html("Your Error MSG");
} else {
$("#textError").html("");
}
});
});

how to show error in jquery after clicking submit button

My problem is that after clicking on submit button the page will go to php file any way my html code is like this
<form action="register.php" method="post">
<input type="text" name="name" id="name"><div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
and my jquery code goes like this
$('#name').focusout(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter name")
}
});
$('#button').click(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter your name")
}
});
but after clicking submit button it redirects to php file and doesn't show any error and store blank data in the database.
Because your input type is submit you can either change the type to button or add event.preventDefault() to avoid automatic passing of form
use event.preventDefault()
$('#button').click(function(e) {
e.preventDefault();//this will stop form auto submit thus showing your error
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
}
});
Or
<input type="submit" value="submit" id="button">
change to
<input type="button" value="submit" id="button">//also prevent form auto submit thus will show the error
Well you need to stop the code to execute after error has been detected. For example you can simple use return false or return:
$('#name').focusout(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter name")
}
});
$('#button').click(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
return false;//add this
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="register.php" method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
I strongly recommend never to assign validation to a submit button click.
Instead assign the submit event handler of the form.
I also added trim and removed the content of the error from the code.
$(function() {
$('#name').focusout(function() {
var empty = $.trim($('#name').val()).length == 0;
$('#adiv').toggle(empty);
});
$('#form1').on("submit",function(e) {
$('#name').focusout();
if ($('#adiv').is(":visible")) {
e.preventDefault()
}
});
});
#adiv { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="register.php" method="post" id="form1">
<input type="text" name="name" id="name">
<div id="adiv">please enter name</div><br/>
<input type="submit" value="submit" id="button">
</form>
Please check this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="button" value="submit" id="button">
</form>
<script>
$(document).ready(function(){
$('#button').on('click',function(){
if($('#name').val() == ''){
$('#adiv').text("Please enter name!!");
}else{
$('#adiv').text($('#name').val());
}
})
})
</script>
try this..:D
function validateFunction(){
if(document.getElementByID('name').value.length==0){
document.getElementByID('adiv').innerHTML = "please enter your name";
return false;
}
return true;
}
<input type="submit" value="submit" id="button" onclick="return validateFunction();" />
$('your-form').on('submit', function(e) {
e.preventDefault();
//your code bere
});
preventDefault stop the normal submit behaviour of your browser so that you can trigger any event you want

how to send changing value under a "hidden" tag on a form

I have 9 pictures on each page, and when someone clicks on a picture the picture is opened in a fancybox, then if a person wants more information about the piece the click on a link inside the fancybox and the form opens inside a modal box.
All of the code works and the form is send through ajax then php.
The problem that I have is that all 9 pictures open the same form and when I client fills out the request form with their contact information, there is no way of me knowing which photo they are looking at.
It would be nice to add a "Hidden" value that is sent with the form so I can know which photo they are requesting the information.
I have looked around SO but to no avail
basic form
<div id="inline">
<form id="contact" name="contact" action="sendmessage.php" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send Request</button>
</form>
link to photo
<a class="fancybox" rel="gallery" href="inventory/inv_pictures/pic4.jpg"><img
src="inventory/inv_thumbs/thumb4.jpg" alt="Antique Furniture - Pic 4"
id="gallery"/></a>
I figured that maybe there is away to add a title tag or use the alt tag under the tag
that the form can pick up and send it as a "hidden" item. That way each photo can still access the same form but then I can know which item they are requesting for.
Sorry for not posting the whole code for fancy box.
but here it is:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
<link rel="stylesheet" href="../js/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />
<script type="text/javascript" src="../js/source/jquery.fancybox.pack.js?v=2.1.5"> </script>
<script type="text/javascript">
$(".fancybox").fancybox({
afterLoad: function() {
this.title = '<a class="modalbox" href= "#inline" >Request more information</a> ' + this.title;
},
helpers : {
title: {
type: 'inside'
}
}
});
</script>
<!-- Hidden inline form -->
<div id="inline">
<form id="contact" name="contact" action="sendmessage.php" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<input type="hidden" id="link" name="link" value="">
<button id="send">Send Request</button>
</form>
</div>
<script type="text/javascript">
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\ [[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var nameval = $("#name").val();
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var namelen = nameval.length;
if(namelen < 2) {
$("#name").addClass("error");
}
else if(namelen >= 2) {
$("#name").removeClass("error");
}
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4 && namelen >= 2) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p> <strong>Success! Your request has been sent. We will respond to it as soon as possible. </strong></p>");
setTimeout("$.fancybox.close()", 3000);
});
}
}
});
}
});
});
</script>
As I can see the link you are giving to fancybox is a direct link to a picture.
I am confused how you get a link to the form inside the modal as it doesn't seem to be coded here.
What I would suggest is, instead of giving direct picture link, create another page and code that page to collect a pic url/id from by GET/POST and display the corresponding pic and then embed this page into the fancybox.
So basically what I am saying is, pass the pic id/path from url that you pass to the fancybox, collect it and then further pass it to the form link

Javascript Automated Click?

I have the following function for a jquery login form and want to run it when php detects that the user is not logged in by echoing a javascript function that clicks the login button automatically
jq Code:
<script type="text/javascript">
$(document).ready(function() {
$('a.login-window, a.log').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
HTML
<div id="login-box" class="login-popup">
<img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" />
<form method="post" method="post" name="f" id="f" class="signin" action="login.php">
<fieldset class="textbox">
<label class="username">
<span>Username or email</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<button class="submit button" type="submit" name="Submit" value="<?php echo $lang['LOGIN'];" style="background:none;">Sign in</button>
<p>
<a class="forgot" href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
if you want to auto click a button, you are looking for .trigger
$('#some-id').trigger('click');
.trigger( 'event' ) explanation:
Execute all handlers and behaviors attached to the matched elements
for the given event type.
(as you are already using jQuery, hence)
<?php
if (!$lang['LOGIN']) {
echo '<script type="text/javascript">';
echo '$(function() {';
echo '$("a.login-window, a.log").trigger("click")';
echo '});';
echo '</script>';
}
?>
var loggedIn = isUserLoggedIn(); // check login status
if(!loggedIn){
$('a.login-window, a.log').trigger('click');
}
.trigger Docs

Categories