As stated in the topic I need to evaluate two fields, one from a drop-down menu item, and one for a text input type field. both in HTML of course. I want to test if the fields are empty, zero, whatever in that context.
I have tried to alter the code, but cannot seem to find the right code.
$(document).ready(function() {
$(function() {
$("#companyDialog").dialog({
autoOpen: false
});
$("#companyButton").on("click", function() {
$("#companyDialog").dialog("open");
});
});
// Validating Form Fields.....
$("#companySubmit").click(function(e) {
var comnpanyname = $("#companyname").val();
var editcompanyscombo = $("#editcompanyscombo").val();
if (companyname === '' || editcompanyscombo === '') {
alert("Please fill all fields marked with an *!");
e.preventDefault();
} else if (editcompanyscombo === '0') {
alert("Select comany to update!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});
<div class="container">
<div class="main">
<div id="companyDialog" title="Edit company">
<form action="" method="post">
<## CompanyEditCombo ##><br>
<label>New company name:</label>
<input id="companyname" name="companyname" type="text">
<input id="companySubmit" type="submit" value="Submit">
</form>
</div>
<input id="companyButton" type="button" value="Open Company Edit Dialog Form">
</div>
</div>
The fields pop up, but they do not alert if the values are zero or empty.
So far I could see from these snippets, please replace === '' and === '0' by == null
(Double equality comparison operator does not aimed to compare the types. That is why, one should use it because null is type object. s. Developer Mozilla)
Related
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();
I currently have these two input text fields with different search functions and I'm trying to make it so that only 1 search function can go through after an onclick -event, depending on which input field is empty.
HTML;
<form onsubmit="return false" id="searchForm">
<input type="text" id="searchGroup" placeholder="Search group" autocomplete="off">
<input type="text"id="searchRoom" placeholder="Search room" autocomplete="off">
</form>
<div id="navBtns">
<button type="button" class="navForward" id="plus" onclick="forward();"></button>
<button type="button" class="navBackward" id="minus" onclick="backward();"></button>
</div>
This is what I've tried in JavaScript, but I can't get it to work;
function forward() {
if (searchGroup.length === 0) {
roomForward();
} else if (searchRoom.length === 0) {
groupForward();
}
}
function backward() {
if (searchGroup.length === 0) {
roomBackward();
} else if (searchRoom.length === 0) {
groupBackward();
}
}
So, the idea is when text input searchGroup is empty, it only executes the function when searchRoom has some input and vice versa.
Any quick and effective ways I could solve this?
You need to add 'value' before the length property. So it should be 'searchGroup.value.length' for example.
I have a form that has a textarea field for input. I want an alert to pop up if the field is empty on submit.
I copied some code that works fine on an input field; however, it does not work for the textarea (it submits with no alerts whether empty or not).
I read through some other questions posted here and made some modifications.
Now, it alerts when empty, but it also alerts when there is text and does not submit.
I am new to this. I am using asp classic.
Code:
<form method="post" action="reasonProcess.asp" name="formName" onSubmit="return Validate()">
<table >
<tr>
<td>Please enter a reason for the change:<br>
<textarea style="width:675px;height:75px" rows="12" cols="10" name="changereason" > <%=dbchangereason%> </textarea></td>
</tr>
</table><br>
<input type=button value="Approve" onClick="javascript:saveAndSubmit()" class="btn" style="float:none;font-size:.78em;">
</form>
<script>
function saveAndSubmit()
{
// Check for reason entered.
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
var queryString = "reasonProcess.asp?Approve=Yes";
document.formName.action=queryString;
document.formName.submit();
// window.close();
}
</script>
This is line of code that works properly with the input text field:
if (!document.formName.changereason.value)
I have also tried:
if (!document.formName.changereason.value.length == 0)
and get the alert without text and with text.
Thanks for any help.
UPDATED
'!' is the logical not operator in JavaScript.
The condition in your code say if the value of changereason textarea is not empty show alert() because of the ! sign that mean not, but what you want is the contrary (if field is empty then show alert), so try just to remove the sign and it will work, do the follow change :
Replace :
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
By :
if (document.formName.changereason.value == '') //removing the ! sign in this line
{
alert("Enter a reason.");
return false;
}
See Working fiddle.
If that not work take a look at External simple page with the same code that is not a fiddle and it should work also in your machine, code of external example :
<!DOCTYPE html>
<html>
<head><title></title>head>
<body>
<form method="post" action="reasonProcess.asp" name="formName" onSubmit="return Validate()">
<table >
<tr>
<td>Please enter a reason for the change:<br>
<textarea style="width:675px;height:75px" rows="12" cols="10" name="changereason" > <%=dbchangereason%> </textarea>
</td>
</tr>
</table>
<br>
<input type=button value="Approve" onClick="javascript:saveAndSubmit()" class="btn" style="float:none;font-size:.78em;">
</form>
<script>
function saveAndSubmit()
{
// Check for reason entered.
if (document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
var queryString = "reasonProcess.asp?Approve=Yes";
document.formName.action=queryString;
document.formName.submit();
// window.close();
}
</script>
</body>
</html>
If that work and not the first example then maybe you have another part of code tha caused a problem and that is not referenced in the question.
Good luck.
change
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
to
if (document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
The ! means "not" - so you were saying if the value is not empty then alert.
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<textarea name="reviewValue"></textarea>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>
it wont submit even though the fields are not empty
here's the form:
<form id="form" role="form" method='POST' action="user_add-post.php">
<div class="form-group">
<p><label class="control-label">Title</label><br />
<input style="width: 40%" class="form-control" type="text" name="postTitle"/>
</div>
<div class="form-group">
<p><label lass="control-label">Description</label><br />
<textarea name="postDesc" cols="60" rows="10"></textarea>
</div>
<div class="form-group">
<p><label>Content</label></p>
<textarea name="postCont" cols="60" rows="10"></textarea>
</div>
<input type='submit' name="submit" class='btn btn-primary' value='Submit'></form>
and here's my jquery to check if the input fields are empty:
$('#form').submit(function() {
if ($.trim($("#postTitle").val()) === "" || $.trim($("#postDesc").val()) === "" || $.trim($("#postCont").val()) === "") {
alert('All fields required');
return false;
} });
now why won't it submit? it keeps on saying that all fields are required even though I already fill up the fields.
You have missed to add id in input boxes,
<input style="width: 40%" class="form-control" type="text" name="postTitle"/>
Change it to
<input style="width: 40%" class="form-control" type="text" id="postTitle" name="postTitle"/>
for next text box aswell ,Please Refer
you do not have define the ids so change the condition to
if ($.trim($('[name="postTitle"]').val()) === "" || $.trim($('[name="postDesc"]').val()) === "" || $.trim($('[name="postCont"]').val()) === "")
You have not given the ids to any of your form field, use global selector with condition
here is the working fiddle of your task
`$("input[name=postTitle]").val()` //name selector instead of id
If condition should be like this:
if ($("#postTitle").val().trim() == "" || $("#postDesc").val().trim() == "" || $("#postCont").val().trim() == "") {
See for any JS errors if you are getting. Also , try it on various browsers. You are not using ID attribute, but Name attritute, so it may not work on Firefox,Chrome and may work on IE7 and below. Hope this helps you
Provide Id to input element in html code.
Jquery code is fine
here is the correct code of html
<input style="width: 40%" class="form-control" type="text" name="postTitle" id="postTitle"/>
Yes like everyone else is saying if you are going to use selectors then you need those id's on the form fields. Or you can use the names like this:
$("[name=postTitle]").val()
$("[name=postDesc]").val()
$("[name=postCont]").val()
Here is your jquery with the above:
$('#form').submit(function() {
if ($("[name=postTitle]").val().trim() == "" || $("[name=postDesc]").val().trim() == "" || $("[name=postCont]").val().trim() == "") {
alert('All fields required');
return false;
} });
As others have said, the selectors are based on ID but using name attribute values. So you can add ID attributes, change the selector or use a different strategy.
Since the listener is on the form, this within the function references the form and all form controls with a name are available as named properties of the form. So you can easily test the value contains something other than whitespace with a regular expression, so consider:
var form = this;
var re = /^\s*$/;
if (re.test(form.postTitle.value) || re.test(form.postDesc.value) || re.test(form.postCont.value) {
/* form is not valid */
}
which is a lot more efficient than the OP.
Given the above, a form control with a name of submit will mask the form's submit method so you can't call form.submit() or $('#formID').submit().
I have a form that I want to validate using JQuery.
When the user leaves the form field without entering anything the class of that input changes to show an error by becoming red.
I have created a jsfiddle file
http://jsfiddle.net/mTCvk/
The problem I am having is that the it will only work on the first text input and the other text inputs will adjust according to the state of the first input.
The JQuery
$(document).ready(function(){
$('.text-input').focusout(function () {
if ($(":text").val().length == 0) {
$(this).removeClass("text-input").addClass("text-input-error");
} else {
$(this).removeClass("text-input-error").addClass("text-input");
}
});
});
Here is the HTML for the form
<form method="post" action="">
<div class="text-input">
<img src="images/name.png">
<input type="text" name="name" placeholder="*Name:">
</div>
<div class="text-input">
<img src="images/mail.png">
<input type="text" name="email" placeholder="*Email:">
</div>
<div class="text-input">
<img src="images/pencil.png">
<input type="text" name="subject" placeholder="*Subject:">
</div>
<div class="text-input">
<img src="images/phone.png">
<input type="text" name="phone" placeholder="Phone Number:">
</div>
<textarea name="message" placeholder="*Message:"></textarea>
<input type="submit" value="Send" class="submit">
It's a DOM issue. It needs to check the :text child for that specific element
$(document).ready(function(){
$('.text-input').focusout(function () {
if ($(this).find(":text").val().length == 0) {
$(this).removeClass("text-input").addClass("text-input-error");
} else {
$(this).removeClass("text-input-error").addClass("text-input");
}
});
});
Updated Fiddle http://jsfiddle.net/mTCvk/2/
It's easy, you have selected the first input type text found : $(":text").val().. You must select the input type type on the .text-input blured :
$(":text", $(this)).val()... // First :text, on $(this) parent
http://jsfiddle.net/mTCvk/1/
PS : for your class management, don't delete .text-input juste add and remove an other class .text-input-error when you have an error
You can use this:
$(":text").focusout(function () {
if ($(this).val().length == 0) {
$(this).parent().removeClass("text-input").addClass("text-input-error");
} else {
$(this).parent().removeClass("text-input-error").addClass("text-input");
}
});
Use following code....
$('.text-input, .text-input-error').focusout(function () {
if ($(this).find(':text').val().length == 0) {
$(this).removeClass("text-input").addClass("text-input-error");
} else {
$(this).removeClass("text-input-error").addClass("text-input");
}
});
I changed your code to use the .on method, and gave it the event blur. Then we create a variable for the closest text-input class (which would be its parent text-input div). Rather than checking the .length, we just check to see if it is an empty string. You would also need to wrap your textarea in the save text-input div for this to work properly.
http://jsfiddle.net/43e2Q/
$('input, textarea').on('blur', function () {
var $closestParent = $(this).parent();
if ($(this).val() == '') {
$closestParent.removeClass("text-input").addClass("text-input-error");
console.log('error');
} else {
$closestParent.removeClass("text-input-error").addClass("text-input");
console.log('valid');
}
});