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.
Related
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)
This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.
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');
I'm making a validation form like so:
<form id="registerform" method="post" onsubmit=return checkformdata();>
<input type="text" name="fname" value=""/>
<input type="text" name="lname" value=""/>
<input type="checkbox" name="privacy" value="1"/>
</form>
checkformdata() Validates only the first name and last name for the checkbox field, which is done using jQuery.
Here is the code that I tried:
jQuery(document).ready(function() {
// Handler for .ready() called.
jQuery('#registerform').submit(function() {
if (!jQuery("#privacy").is(":checked")) {
alert("none checked");
return false;
}
});
});
It is also working but the alert field is comes twice for example firstname is empty then alert for first name and alert for checkbox comes up. I want to show the alert for the checkbox after the checkformdata(); function. Is it possible to give the priority first for javascript then the jquery validation.
Thanks in Advance.
You should only have one functions, which is the second method you are using. Both functions are called now, which is not wat you want. Also, you can use $ instead of jQuery.
Dont use return false! Unless you know what you are doing. Use preventDefault():
$('#registerform').submit(function(event) {
var errorString = [];
// START VALIDATION
if ($("#privacy").is(":checked") ) {
errorString.push("none checked"); // Save for later
}
if ($('[name="fname"]').val).length===0) {
errorString.push("No firstname"); // Save for later
}
if ($('[name="lname"]').val).length===0) {
errorString.push("No lastname"); // Save for later
}
// CHECK IF ERRORS ARE FOUND
if( errorString.length !==0){
event.preventDefault(); // stop the submitting
// Do whatever you like with the string, for example;
alert( "Something went wrong: \n"+errorString.join("\n") ); // alert with newlines
}
// NO ERRORS FOUND, DO SOMETHING
else{
// all good. Do stuff now
}
});
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
}