I have two input fields one is file the other is textarea
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
User has to either upload a file or type text. If the user leaves blank both of the inputs, it should say like "choose a file or type info" if he/she fills both, it is ok.
My JQuery:
$(function(){
$(".input_field").prop('required',true);
});
I have this code. How can we implement something like if else condition to make it required one of the fields?
See this fiddle https://jsfiddle.net/LEZ4r/652/
I modified your code to each all the elements with a class of input_field when the form is submitted.
$(function(){
$('form').submit(function (e) {
var failed = false;
$(".input_field").each(function() {
if (!$(this).val()) {
failed = true;
}
});
console.log(failed);
if (failed === true) {
e.preventDefault();
}
});
});
Based on your question, there are only two possible conditions:
if either one field or both fields are filled, user passes validation
if no fields are filled, user fails validation
This can be easily done by checking for the value of either input. As long as one is not empty, user passes the test. This if/else condition can be written as:
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
// Passed validation
} else {
// Failed validation
}
A simple pattern to check for errors is to create an error flag, which will be raised when one or more validation checks have failed. You evaluate this error flag at the end of the script before manual form submission:
$(function(){
$('form').on('submit', function(e) {
e.preventDefault();
// Perform validation
var error = false;
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
alert('Passed validation');
error = false;
} else {
alert('Please fill up one field');
error = true;
}
// Check error flag before submission
if(!error) $(this)[0].submit();
});
});
See working fiddle here: http://jsfiddle.net/teddyrised/LEZ4r/653/
Check inside your form If atleast one is done break the loop and go for submit else return false
$(function(){
$('form').on('submit',function(e){
var doneOnce = false;
$(this).children().each(function(){
if($(this).val()){
doneOnce = true;
return false;//return false will break the .each loop
}
});
alert(doneOnce)
if(!doneOnce){
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
<input type=submit />
</form>
You can write codes in Javascript to validate form. You have to make an onclick or onsubmit function, and the function will check whether any of the input field is empty. You can write something like the following code:
<script>
function validateForm() {
var fstname=document.getElementById("fname").value;
var lstname=document.getElementById("lname").value;
if(fstname===null || fstname===""){
alert("Plese choose a file.");
return false;
}
else if(lstname===null || lstname===""){
alert("Plese type file info.");
return false;
}
else{
return confirm("Your file: "+fstname+" and it of type "+lstname);
}
}
<body>
<form action="text.php" name="myForm" onsubmit="return validateForm()">
First Name: <input type="file" id="fname" name="FirstName">
Last Name: <input type=text" id="lname" name="LastName"><br/>
<input type="submit" value="Submit">
<form>
</body>
Related
I am trying to check if all form fields are filled on click a button & if valid then i am trying to add a check an alert using jquery.
jQuery("button#btn_place_order").click(function(event){
jQuery("form").validate({
submitHandler: function(form) {
alert('ok');
}
});
});
This is what i have tried but its not working, i just want to check if all fields are ok valid & filled & there is no form related error then just console or alert to check. Webpage has two or more html forms. Is their any way we can check using jquery ?
Thanks
First of you will have to prevent the default behavior of a form submit. Afterwards add a event listener to your button and check for validation of each input. (whatever that means for you). Is this what you wanted?
var el = document.getElementById("form");
el.addEventListener("submit", function(event) {
event.preventDefault();
}, true);
document.getElementById("btn").addEventListener("click", validate);
function validate(){
let valid = true;
[...document.getElementById("form").elements].forEach((input) => {
if(input.value.length == 0){
valid = false;
}
});
if(valid) alert("valid");
}
<form id="form">
<input type="text" name="TEST" id="test">
</form>
<button class="button" name="Send" value="Send" id="btn">Check</button>
I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.
I have a page that loads a loading gif when a button is clicked. It works fine if required text has been entered.
If the required text has not been entered the browser indicates that the text is missing but the loading gif still kicks in.
Is there a way of js knowing that a required field has not be completed so that I can stop the loading gif from displaying?
Stripped down I have:
An HTML form that looks like this:
<form action="...">
<input type="text" required>
<button>Submit</button>
</form>
and I some js that looks like this:
$("button").click (function(){
// Display a loading gif;
});
What I want is something like this:
$("button").click (function(){
if (all required fields are complete) {
// Display a loading gif;
}
});
Any ideas?
How about using a filter on the fields like this:
$('input').filter('[required]')
function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
$('#confirm').click(function() {
alert(checkInputs());
});
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})
checkInputs()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input required>
<input required>
<input required>
<button id="confirm">check</button>
</form>
Credit goes to: Here
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)
I have a webpage where a user submits a form containing an email field and a confirm email field.
How do I check to make sure both of these fields equal the same thing?
<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>
With jQuery, but no error handling, I'd suggest:
$('form').on('submit', function() {
return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});
Ridiculously simple JS Fiddle demo.
Easiest way would be to use Javascript as you can stop form submission before it goes to your php file. However it is still good practice to verify the data entered with the php file as well as there are some programs that will allow you to change data being submitted in a form after javascript checks are made.
<script>
function checkMatch() {
var email = document.getElementById('email').value;
var emailConfirm = document.getElementById('emailConfirm').value;
if (email != emailConfirm) {
alert("Email addresses are not the same.");
return false; //Returning 'false' will cancel form submission
} else {
/*
place the return true; at the end of the function if you do other
checking and just have if conditions and return them as false. If
one thing returns false the form submission is cancelled.
*/
return true;
}
}
</script>
And change your form to have onSubmit
<form method="post" action="submit_query.php" onSubmit="checkMatch()">
Add id's to your email inputs such as: email and emailConfirm. You can change them if you wish but just for an example I used those.