jQuery validate before page reload - javascript

So when I click submit it directs to error page. I'd like to validate before it redirects to error page, the plugin works like that. Is there a way to prevent the submission if there was something wrong with the user's input ?
<input type="submit" name="submit-contact" class="button" value="Send" />
$(document).ready(function(){
$(".button").click(function() {
var name = $('input#name').val();
if (name == ""){
$('#name').addClass('errro');
return false;}
else {
$('#name').removeClass('errro');}
});
});

After several minutes of staring at the question I think I know what you mean. You can do that by listening for the submit event and returning false when you think that there's something wrong with the user's input.
$(document).ready(function(){
$("#theForm").submit(function() {
var name = $('input#name').val();
if (name == ""){
$('#name').addClass('errro');
return false;
}
else {
$('#name').removeClass('errro');
}
});
});

input type="submit" name="submit-contact" class="button" onClick="Somejavascriptfunction" value="Send"
function Somejavascriptfunction()
{
Retrieve Username and password via $(".Username").val() and $(".Password").val()
Pass it to a ajax request page.
Get result back from ajax page.
If invalid then pop up message via jquery
if valid then submit.
}
AjaxPage
{
Do the verification(1. Empty username/password 2. Correct username and password..etc)
Return result back to calling function
}

Related

Check if textbox contains text, if it does then send

I have this email form, with "Sender, "Subject" and "Message".
But i haven't linked it to make sure they have written something, so if someone press the "Send" button without typing anyting, i get a blank email. So i want it to abort the email sending if the textbox is empty, and send it if it contains any text.
code for the send button:
<input type="submit" name="submit" value="Submit" class="submit-button" />
ID for the textbox is: textbox_text
You can use jquery to validate the form like this-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
Sender
<input type="text">
<br/>Subject
<input type="text">
<br/>Message
<input type="text" id="txtMessage">
<br/>
<input type="submit" value="Send" name="btnSend">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("input[name=btnSend]").click(function() {
var msg = $("#txtMessage").val();
if (msg == "") {
alert("Please enter the message");
return false;
}
});
});
</script>
Java Script function
<script type="text/javascript">
function IsEmpty()
{
if(document.forms['frm'].textbox_text.value == "")
{
alert('Message body is empty');
return false;
}
return true;
}
</script>
HTML
<form name="frm">
<input type="submit" name="submit" onclick="return IsEmpty();" value="Submit" class="submit-button" />
</form>
EDIT Check textbox2 in if condition
if(document.forms['frm'].textbox1.value == "" && document.forms['frm'].textbox2.value == "")
I dont know this is your exact answer but it will helps you to validate:
$('#checkSubmit').click(function(){
var chec=$("#textContent").val();
if(chec=="")
alert("Please add your content");
else
alert("successfully submitted");
});
check out this fiddle:
http://jsfiddle.net/0t3oovoa/
You need to check that on server side (with php) and you can also check it on client side(Javascript).
Client side test is good if you want the user to get fast response, but you still need to check it on server side because javascript on your website can ALWAYS be changed by user.
You could also just add "required" on your input elements.
for server side check with php:
<?php
//Check if variables exist
if(isset($_POST['sender']) && isset($_POST['subject']) && isset($_POST['message'])){
//Check if sender value is empty
if(empty($_POST['sender'])){
//If empty, go back to form.Display error with $_GET['error'] in your form page
header('location: backToFormPage.php?error=send');
}
//...
}
//Variables doesn't exist
else{
//Redirect to page or other action
}
?>
You can achieve it two ways:
1. Client Side( Which i recommend) use the form validation to validate the form data if it is empty tell them to fill it. You chose the submit button to trigger validation that is not recommended instead validation is triggered on form submission or on change of input elements(for real-time validation). Anyways below is an example for validation using the click event on submit button.
var validateTextBox = function(textBox) {
var val = textBox.value;
if(val=="") { // Check for empty textbox
return false;
}
return true;
}
documnet.querySelector('#SubmitButton').onclick(function () {
var textbox = document.querySelector("#SubjectORMessage").value;
if(validateTextBox(textbox)){
// Do something to let page know that form is valid
} else {
// Let the user know that he has done something wrong
alert("Please fill the content");
}
})
2. Server Side if unfortunately empty data is send to the server, then use server side validation (Server side validation requires a little more thing to do at more than one place, i.e., html, php/python/perl)

Prevent form submission in java script after displaying alert message

This is my coding in js
var ck_name = /^[A-Za-z0-9 ]{3,12}$/;
function validate(form)
{
var Name = document.getquote.name.value;
if (!ck_name.test(Name))
{
alert("Enter a valid FirstName containing alphabets ,numbers with minimum of 3 characters");
document.getElementById('name').focus();
return false;
}
}
Iam calling this function on form submit. After showing the alert message, I want the focus to be back on the name-textbox but the page get submitted after the alert. The "return false" command is not working.
You add this code when false occurs
$('#formID').attr('onsubmit','return false');
Another Way
$("form").submit(function () { return false; }); that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
#Sridhar R answer worked for me, with a little change, instead of 'onsubmit' I used 'onSubmit'
$('#formID').attr('onSubmit','return false');

Button click with jquery cancel form and redirect page

http://jsfiddle.net/nqCFL/
I'm trying to check the value of an input and if it's empty, redirect the page, if not empty, redirect to another page. It has no value as is and does not represent what I'm actually trying to do, it is just an experiment. This experiment is supposed to help me with the goal is to check the input and if it's empty, submit the form. If it's not empty, cancel the form and redirect to another page. I'm experimenting with Botcha and this is similar in idea. The problem is the page just continually refreshes on button click and never redirects according to the test I have above.
The experiment I have is:
<form action="" method="post">
<input type="text" placeholder="issue" class="issue-input" />
<button class="submit button" type="submit">Send</button>
</form>
$(".submit").click(function(){
if($(".issue-input").val().length == 0) {
window.location.href = "http://www.google.com";
} else {
window.location.href = "http://www.yahoo.com";
};
});
Because your button is submit button, so your click will submits the form, try use preventDefault method of jquery.
$(".submit").click(function (e) {
e.preventDefault();
if ($(".issue-input").val().length == 0) {
window.location.href = "http://www.google.com";
} else {
window.location.href = "http://www.yahoo.com";
};
});
try fiddle: http://jsfiddle.net/nqCFL/2/ , I modified the url to an error url, so you can see page is redirected.
try with :
$(".submit").click(function(){
if($(".issue-input").val() == ''){
window.location.href = "http://www.google.com";
} else {
window.location.href = "http://www.yahoo.com";
};
});

Displaying an image after pressing submit html

I have the following code to display an image after i press submit
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" onclick="$('#image1').show()"/>
Name is retrieved by
var y=document.forms["myForm"]["fname"].value;
Where fname is
<h4>Name: <input type="text" name="fname" size="61" /></h4>
Only problem is this is using Jquery, so I can't seem to pass it through any of my other
validations like checking if the name field is null.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
Is there a Javascript equivalent to this that I can stick in my else statement so it will only show it if the form actually submits properly passing the validation checks beforehand?
Thanks
do all that in jquery.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
else
{
$('#image1').show()
}
You should be using the .submit() event handler of jQuery instead of attaching an onclick property to the submit button. The onclick property will not fire its function in the event that a user submits the form via the enter key; however, the .submit() method will capture it as well.
$("form[name=myForm]").submit(function(e) {
//get value of name here.
var name = this.fname.value; //this refers to the form, because that is what is being submitted.
//Do validation.
if (name == null || name == "") {
//If failed, then prevent the form from submitting.
alert("First name must be filled out.");
e.preventDefault();
return;
}
//If validation passed, show image.
$("#image1").show();
});
First, remove the onclick attribute from the submit button:
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" />
Since you're using jQuery, attaching handlers to click events in JavaScript is a snap (and it's also a good practice).
I almost always use the following pattern for form validation (and on the submit of the form, rather than the click of the submit button because there are other ways to submit forms than clicking the button).
$(document).ready(function () {
var formIsValid = function formIsValid () {
// your validation routines go here
// return a single boolean for pass/fail validations
var name =document.forms.myForm.fname.value;
return !!name; // will convert falsy values (like null and '') to false and truthy values (like 'fred') to true.
};
$('form').submit(function (e) {
var allGood = formIsValid();
if (!allGood) {
e.preventDefault();
}
$('#image1').toggle(allGood); // hide if validation failed, show if passed.
return allGood; // stops propagation and prevents form submission if false.
});
});

jQuery form code error used for automatic submit

var inpt = $('#input-box').val();
if (inpt != '') {
$('form').submit();
alert('Voila!'); // (1)
} else {
alert('fill something man'); // (2)
}
I am using this code to automatically submit the form as soon as the page loads.
Here I am unable to use the jquery $(document).ready() function because I m in GreaseMonkey environment.
The form is automatically filled, I used (2) statement for exceptional cases.
I get no alerts! neither from (1) nor from (2).
UPDATE:
<label for="answer">Answer:</label>
<input type="text" name="answer" id="input-box" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
Try to put the alert before the submit.
var inpt = $('#input-box').val();
if (inpt != '') {
alert('Voila!'); // (1)
$('form').submit();
} else {
alert('fill something man'); // (2)
return false; // to stop submitting
}
If you want it to auto-submit after a user enter a value then you can do thsi:
$('#input-box').live('blur',function(){
var inpt = $('#input-box').val();
if (inpt != '') {
alert('Voila!'); // (1)
$('form').submit();
} else {
alert('fill something man'); // (2)
return false; // to stop submitting
}
});
alert('Voila!'); // (1)
Will never alert, because by this time the page has reloaded due to submit request being sent.
Try:
$('form').submit(function(){
alert('Voila!'); // (1)
}).trigger('submit');
Greasemonkey executes the code after onready, this should work. But is there a form on the page, and are you fetching the correct form? There's little information to go from here.
Try to check the function in firebug first, it should run there. greasemonkey needs some work to understand the jquery-thing. The easy way is to use var $ = unsafeWindow.jQuery; at the start, provided the page you're on has jQuery.

Categories