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
Related
I have a multiple field input and I want to remember the input values after submitting it , how can I do that using php or maybe another language if it is possible?
I have this input:
<input type="text" name="passport[]" class="form-control" aria-describedby="basic-addon1"required/>
I have tried something like this :
value="<?php if(isset($_POST['passport'])) { echo $_POST['passport'][$i]; } ?>"
but nothing works.
You can use browser local storage to keep the value after form submission.
<form method="post" action="" onSubmit="return saveElement();">
<input type="text" name="passport[]" id="password"/>
<input type="submit" name="submit" value="save"/>
</form>
<script type="text/javascript">
document.getElementById("password").value = localStorage.getItem("password");
function saveElement() {
var passValue = document.getElementById("password").value;
if (passValue == "") {
alert("Please enter a password first!");
return false;
}
localStorage.setItem("password", passValue);
location.reload();
return false;
}
</script>
I 'm beginner, In dynamically added Input fields Reference From: Validate Dynamically Added Input fields, when passed Validation and submit cannot to another page
Follow script sample.
<script src="js/jquery-3.1.1.min.js"></script>
<script src="js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
when passed validation click submit butt cannot to action="/action_page_post.php"
And HTML code
<form class="commentForm" method="get" action="/action_page_post.ph">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Changes I made
changed on('submit') to submitbutton.onclick
added $('.commentForm').submit(); inside the if condition which execute if the validation is true
Reason : Since you are using event.preventDefault(), it will prevent the default behaviour of the form and so did not go to next page. So You have to submit the form manually using $(form).submit();
The below code will work on normal page but not on SO Snippet
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('input.submit').click(function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
});
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
$('.commentForm').submit();
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
<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.min.js"></script>
<form class="commentForm" method="get" action="action_page_post.php">
<div>
<p id="inputs">
<input type="text" class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
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.
I have a form with the action set to "/resutls". But i have a txt input and i want to check if that is not empty to redirect to another location than "/results". Is this possible?
Code example as below:
<form id="results" action="/results" method="get">
<select id="country" name="country">
....
</select>
<input type="text" name="id">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Any ideas? Can this be done with jquery?
Sure you can do that in the submit handler. Warning: I wouldn't give a form control a name of id. It does cause confusion: if this refers to the form, should this.id refer to the id of the form or the text field with name="id"?
if( !!this.somefield.value ) { //did not want to write this.id.value !!!!
this.action = '/other-url';
} else {
this.action = '/results';
}
$(function() {
$('#results').on('submit', function(e) {
e.preventDefault(); // just so we can see that form action changes
if( !!this.somefield.value ) {
this.action = '/other-url';
} else {
this.action = '/results';
}
alert( this.action );
//$(this)[0].submit(); //now submit the form
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="results" action="/results" method="get">
<select id="country" name="country">
</select>
<input type="text" name="somefield">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Yes it is possible. Just set the form element's action property using jQuery .prop().
As a simple example:
var valid = false;
// go though validation here
if (false === valid) {
$('#results').prop('action', '/some/url/to/redirect/to');
}
HTML5 provides the "required" attribute wich will prevent the form for being posted, use it like this
<input type="text" name="id" required="required">
or, if you prefer to redirect to other page instead, you can do this
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$("#results").submit(function (e){
e.preventDefault();
if($("#results input[name='id']").length < 1){
window.location.href = "your detiny url";
}
else{
this.submit();
}
});
</script>
How can I change the code below so instead of a text input type with a submit button I want multiple submit buttons each with their own unique value? Everything I try just ends up with submit's value being undefined. Any help would be great!
Code source: Submit Search query & get Search result without refresh
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
You can add multiple submit buttons and attach to all of them onclick event listener. When button was clicked - get the value and send with a POST request.
<script>
$(function(){
$('input[type=submit]').click(function(){
$.post('db_query.php', {value:$(this).val()}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="">
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
</form>
If you want to use multiple submit buttons, you can catch the click event and determine which button was clicked. then run different Ajax submit. this also works when enter is hit.
//submit buttons
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str" />
<input type="submit" value="v1"/>
<input type="submit" value="v2"/>
//...more submit buttons
</form>
//submit func
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val){
case 'v1':...;
case 'v2':...
}
});
});
Here is my version - which now looks very much like Bingjies because it was written while I was testing out his version
DEMO
<form id="lets_search" action="" >
Search:<input type="text" name="q" id="q">
<input type="submit" value="Google" name="send" id="google">
<input type="submit" value="Bing" name="send" id="bing">
</form>
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val()) {
case "Bing" :
$("#lets_search").attr("action","http://www.bing.com/search");
break;
case "Google":
$("#lets_search").attr("action","https://www.google.com/search");
break;
}
});
});
Here, I would prefer to Vamsi's solution n Why not Sanjeev mk?
Give some extra thought on prefering the solution.
case: If there are mulitple submit buttons
If the user is in the text field and hits enter, the system will assume the first submit button was hit.
So, here, it would be good to go for not having mulitple submit
buttons for end user point of view
You can have multiple submit buttons in the form, no problem. They may have the same name, type etc, but just assign them different values. Like Submit Button 1 can have value="hi" and Button 2 can have value="bye".
Then when the action function is called for the button, all you have to do when entering the function is do a check with: $(this).val
HTML:
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
jQuery:
$(function() {
$("#lets_search").bind('submit',function() {
var value = $(this).val();
if(value == "hi")
do_something;
else
do_something_else;
});
});