textarea data entry check with alert if empty - javascript

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>

Related

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

How to direct to a different url if check box enable

with some advice from this forum below code is working for me when I type in the textbox and it will direct to a url.
<script src="jquery.min.js"></script>
<script>
function test() {
if(jQuery('#inputtext').val() == 'google'){
// alert('Input can not be left blank');
window.location.href = "https://www.google.com/";
}
if(jQuery('#inputtext').val() == 'yahoo'){
// alert('Input can not be left blank');
window.location.href = "https://www.yahoo.com/";
}
else if(jQuery('#inputtext').val() == ''){
alert('Input can not be left blank');
}else if(jQuery('#inputtext').val() != ['google'||'yahoo']){
alert("INVALID Entry");
}
}
</script>
<form id="main" name="main"><input type="text" name="inputtext" id="inputtext" placeholder="type here"/><input type="button" value="submit" onClick="test();"></form>
Is it possible to add a checkbox, and if checkbox is checked with text input it should direct to another url.
ex: now if I type google it directing google.com, Required if checked box is checked and if typed as google it should direct to gmail.com
form in below
<form id="main" name="main">
<input type="text" name="inputtext" id="inputtext" placeholder="type here"/>
<input type="checkbox" name="inputcheckbox" id="inputcheckbox">Redirect
<input maxlength="10" type="button" value="submit" onClick="test();" ></form>
Kindly advice..
For jQuery 1.6+ : You can use $('#inputcheckbox').prop('checked')) to check whether the checkbox is checked or not.
for jQuery < 1.6 :
$('#inputcheckbox').attr('checked')).
I am using change event to check the condition, so if you want to check your condition on submit click you can copy the code inside it to your submit event/function.
Below is my sample code.
$(function() {
$('#inputtext,#inputcheckbox').change(function() {
if ($('#inputtext').val() == 'google' &&
$('#inputcheckbox').prop('checked')) {
alert('redirecting to google...')
window.location.href = "https://www.google.com/";
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="main" name="main">
<input type="text" name="inputtext" id="inputtext" placeholder="type here" />
<input type="checkbox" name="inputcheckbox" id="inputcheckbox">
<input maxlength="10" type="button" value="submit" onClick="AddPrinter();">
</form>
I'm not sure I understood your problem, but it seems you want to change the redirect URL to www.gmail.com when the user types "google" and checks the checkbox.
You can achieve this the following way:
if($('#inputtext').val() == 'google' && $('#inputcheckbox').isChecked) {
window.location.href = "https://www.gmail.com/";
}
PS: You can use $ instead of jQuery in your code, it has the same effect and keeps the code cleaner.
add checkboxes with different IDs
<input type="checkbox" id="isAgeSelected"/>
then use script
if(document.getElementById('isAgeSelected').checked) {
window.location.href = // Some URL
}
another way is
$('#isAgeSelected').click(function() {
window.location.href = // Some URL
});
<script>
function test() {
if(jQuery('#inputtext').val() == 'google' && jQuery('#inputcheckbox').isChecked){
// alert('Input can not be left blank');
window.location.href = "https://www.google.com/";
}
if(jQuery('#inputtext').val() == 'yahoo' && jQuery('#inputcheckbox').isChecked){
// alert('Input can not be left blank');
window.location.href = "https://www.yahoo.com/";
}
else if(jQuery('#inputtext').val() == ''){
alert('Input can not be left blank');
}else if(jQuery('#inputtext').val() != ['google'||'yahoo']){
alert("INVALID Entry");
}
}
</script>
I hope my answer will help you.

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

Validating input length using JavaScript

I want to show an error if user enters less than 4 letters in text box.
Here is the code I'm currently using now, it is somewhat working. The problem is - it is showing the error and then it is submitting the value also.
I want to stop it submitting if user enters less than 4 letters.
JavaScript
<script type="text/javascript">
function check(what)
{
var length=what.search_text.value.length;
if (length >3 && length < 21)
what.submit();
else
alert("Your nick should be 4-20 characters long.");
}
</script>
HTML
<form method=post action=''><input type=hidden name=todo value=search>
<p align=center>
Enter Your Name:
<input type=text name=search_text value='$search_text'>
<input onclick=check(this.form); return false; type=submit value=Search>
</p>
</form>
<script type="text/javascript">
function check(what)
{
var length=what.search_text.value.length;
if (length >3 && length < 21){
what.submit();
}
else {
alert("Your nick should be 4-20 characters long.");
return false;
}
}
</script>
<?php
echo "<form method='post' action='' onsubmit='return check(this);'><input type=hidden name=todo value=search>
<p align=center>Enter Your Name: <input type=text name=search_text value='$search_text'><input type=submit value=Search></p><br>
</form>";
?>
Changes :
onsubmit='return check(this);' added in form tag
Removed onclick from button submit
return false; added in else condition of js function
Suggestion : Always try to use jQuery, It is simple and will reduce your code length.
in case of invalid values you need to
return false;
so that form submission is cancelled
u can achive this by using RegularExpressionValidator control
design your textbox like this example i am using.
<asp:TextBox ID="txtCityCode" runat="server" Width="147px" CssClass="txt" MaxLength="2"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCityCode" runat="server" ErrorMessage="City Code is required information."
ControlToValidate="txtCityCode" Display="None" ValidationGroup="Save" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revCityCode" runat="server" ErrorMessage="Numbers and special characters not allowed in 'City Code' field."
ControlToValidate="txtCityCode" ValidationExpression="^[a-zA-Z\s]+$" ValidationGroup="Save"
Display="None" SetFocusOnError="True"></asp:RegularExpressionValidator>
Just Change the ValidationExpression according to your needs
<script type="text/javascript">
function check(what)
{
var length=what.search_text.value.length;
if (length >3 && length < 21)
{ what.submit(); return true; }
else
{alert("Your nick should be 4-20 characters long.");
return false;}
}
</script>
and in HTML
<input onclick='return check(this.form)' type="submit" value="Search">

Javascript form validation not working

I can't understand why my javascript isn't working... Do i need to declare a variable somewhere?
<script type="text/javascript">
function validation(form) {
      
if(form.first_name.value == '' ) {

alert('Please enter your first name');
 form.first_name.focus();
return false;
}
if(form.00N30000006S4uq.value == '') {

alert('Please enter the high end of your budget');
 form.company.focus();
return false;
}
return true;
}
</script>
<form action="https://www.salesforce.com/servlet/servlet.WebToLead" method="POST" onsubmit="return validation(this);">
As mentioned by #ReturnTrue, the NAME must begin with a letter. That is why your script is failing.
In your case since the field is auto-generated, if you know the flow of the elements in the form then you can reference the form elements array, like this...
form.elements[2].value
where form.elements[2] is form.00N30000006S4uq. That will do the job.
Example:
function validation(form) {
if(form.elements[0].value == '' ) {
alert('Please enter your first name');
form.first_name.focus();
return false;
}
if(form.elements[2].value == '') {
alert('Please enter the high end of your budget');
form.company.focus();
return false;
}
return true;
}
<form action="" method="POST" onSubmit="return validation(this);">
<input type="text" name="first_name" />
<input type="text" name="company" />
<input type="text" name="00N30000006S4uq" />
<input type="submit" name="submit" />
</form>
Form names need to begin with a letter. "00N30000006S4uq" fails because it begins with a number.
See: http://www.w3.org/TR/html401/types.html#type-cdata

Categories

Resources