Javascript to validate element values and checkboxes - javascript

I want to use js to check a form in the case that none of my checkboxes are checked and the input field hasn't been filled. When this is the case, the user should get a message that tells them to make at least one choice or formulate their own.
The form elements...
<input type="checkbox" name="checkboxA" id="checkboxA" value="X" />
<input type="checkbox" name="checkboxB" id="checkboxB" value="Y" />
<input type="checkbox" name="checkboxC" id="checkboxC" value="Z" />
<input type="text" id="Text" class="textfield" value="please enter text." maxlength="100" size="40" onblur="if (this.value == '') {this.value = 'please enter text';}" onfocus="if (this.value == 'please enter text') {this.value = '';}" />
...are checked by this js function when the POST method is performed:
function checkFormElement() {
if ((document.getElementById("text").value == "please enter text.")
&& (document.getElementById("checkboxA").checked == false)
&& (document.getElementById("checkboxB").checked == false)
&& (document.getElementById("checkboxC").checked == false)){
alert("Please choose out of X Y Z or formulate your own choice .");
document.getElementById("checkboxA").focus();
return false;
}
return true;
}
I guess using jQuery should be much easier but I still love to know how to solve this in pure js.

Case matters with ID values so change this:
document.getElementById("text").value
to this to match what you have in your HTML:
document.getElementById("Text").value
Once I fix the case issue and put in code to actually call checkFormElement(), it seems to work fine here: http://jsfiddle.net/jfriend00/9DHxF/

You're missing a submit or similar type of button\option that will run checkFormElement().
Once you include something that calls this function, you shouldn't experience any problems.

You have a few errors in your code. Mostly mismatched IDs and such.
Working example here: http://jsfiddle.net/E8SBq/
This should work for you:
<input type="checkbox" name="checkboxA" id="checkboxA" value="X" />
<input type="checkbox" name="checkboxB" id="checkboxB" value="Y" />
<input type="checkbox" name="checkboxC" id="checkboxC" value="Z" />
<input type="text" id="Text" class="textfield" value="please enter text" maxlength="100" size="40" onblur="if (this.value == '') {this.value = 'please enter text';}" onfocus="if (this.value == 'please enter text') {this.value = '';}" />
<input type="submit" value="Submit" onClick="checkFormElement()" />
And the JS function:
function checkFormElement() {
if (document.getElementById("Text").value != null
&& document.getElementById("checkboxA").checked == false
&& document.getElementById("checkboxB").checked == false
&& document.getElementById("checkboxC").checked == false) {
alert("Please choose out of X Y Z or formulate your own choice .");
document.getElementById("checkboxA").focus();
return false;
}
return true;
}

Related

how to focus back when textbox is empty

I would like to switch back to the previous textbox when current textbox is empty.
I can go next textbox when current textbox is filled but i can not go back when i delete characters (length == 0) in to the textbox.
Here is my textboxes:
<input id="txt_1" type="number" maxlength="3" onKeyDown="if(event.KeyCode != 8){if(this.value.length == 3){window.setTimeout(function (){document.getElementById('txt_2').focus();},0);return false;}}">
<input id="txt_2" type="number" maxlength="3" onKeyDown="if(event.KeyCode != 8){if(this.value.length == 3){window.setTimeout(function (){document.getElementById('txt_3').focus();},0);return false;}}">
<input id="txt_3" type="number" maxlength="3" onKeyDown="if(event.KeyCode != 8){if(this.value.length == 3){return false;}}">
I can go (on filling) like:
txt_1 > txt_2 > txt_3
I can't go back (on deletion) like:
txt_3 > txt_2 > txt_1
To have the textbox value when you get to the event, you should use keyup event instead of keydown.and it should work for you, however I have suggested another solution no repeating the code for each element:
$('.forward').on('keydown', function(e){
if($(this).val().length === 3 && e.which != 8) e.preventDefault();
});
$('.forward').on('keyup', function(e){
if($(this).val().length === 3)
{ if($(this).data('next')) $($(this).data('next')).focus();}
if($(this).val() === '')
{if($(this).data('back')) $($(this).data('back')).focus();}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txt_1" type="number" maxlength="3" data-next="#txt_2" class="forward" />
<input id="txt_2" type="number" maxlength="3" data-next="#txt_3" data-back="#txt_1" class="forward" />
<input id="txt_3" type="number" maxlength="3" data-back="#txt_2" class="forward" />
You can try this
if( $("#txt_1").val() === ''){
$("#txt_1").focus();
}

javascript isn't running in my JSP

I'm trying to make it so that i can validate the input when the user submits the form, but for some reason the javascript in my jsp isn't being implemented. any one have any idea?
code is posted below
Javascript:
function validate()
{
if(document.updateForm.fName.value == "")
{
alert(" Please provide your first name." );
document.updateForm.fName.focus();
return false;
}
{
if(document.updateForm.lName.value == "")
{
alert(" Please provide your last name." );
document.updateForm.lName.focus();
return false;
}
HTML:
<h1>People Library - Update a Person</h1>
<form name="updateForm" action="updatePerson" onSubmit="return validate()" method=get>
<Label>
Person ID:
</Label>
<input type=text name=personID value="<%= person.getPersonID() %>"/>
<br />
<Label>
First Name
</Label>
<input type=text name=fName value="" />
<Label>
<br />
Last Name
</Label>
<input type=text name =lName value="" />
<Label>
<br />
age
</Label>
<input type=text name=age value="<%= person.getAge() %>" />
<br />
<input type=submit name=submit value="Update the Person" />
</form>
There are several obvious syntax errors you would not get if you learned to properly indent code. Every time you open a curly bracket {, tab everything inside it over to make it clear where blocks begin and end.
Having done so, I find your code looks like this:
<script language="javascript" type="text/javascript">
function validate()
{
if(document.updateForm.fName.value == "")
{
alert(" Please provide your first name." );
document.updateForm.fName.focus();
return false;
}
{
if(document.updateForm.lName.value == "")
{
alert(" Please provide your last name." );
document.updateForm.lName.focus();
return false;
}
</script>
You've obviously got some missing closings }, and some stray openings {. The stray opening may be due to forgetting to type else.

Javascript IF ELSE statement stopping short

So we have here my code for a GPA calculator. Ive got everything in line but I cant seem to figure out why my IF ELSE statement is stopping short and converting all letter grades to a value of "4".
I have tried putting the statement outside of the for loop that is handling the grades and pushing them to to gVals[] I have tried putting them completely outside of the function in their own function. I have tried alot of different things except apparently the thing that works.
I know there are simple ways of doing this but I am trying to execute this app with a minimalist mentality.
The code:
function calcGPA() {
//Variable Sections
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be capitol letters A,B,C,D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
//Grab the Letter grades and process them
//Should validate all inputs in the letGrade div to capitol A, B, C, D or F
//Should Convert all inputs in the LetGrade div to A = 4,B = 3,C = 2,D = 1,F = 0
//Should push resulting conversion to gVals[]
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (grades[i].value == "A"){
gVals.push("4");
}
else if (grades[i].value == "B"){
gVals.push("3");
}
else if (grades[i].value == "C"){
gVals.push("2");
}
else if (grades[i].value == "D"){
gVals.push("1");
}
else if (grades[i].value == "F"){
gVals.push("0");
}
//Should validate all inputs in the conHours div to 1, 2, 3, 4 or 5
//Should push all resulting values to cVals[]
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
cVals.push(contacts[i].value);
}
console.log(gVals, cVals);
document.getElementById("cumGPA").innerHTML = (gVals[0] * cVals[0]);
};
The issue I am having is that the IF ELSE statement to do the conversion from letter grade to quality point value is returning everything back as 4 instead of matching it with its resulting letter grade componant.
Thank you for any help with this in advanced and please if you could dont answer the question outright please explain where I went wrong so I can learn from this.
EDIT: ADDED HTML FOR PROSPERITY! AND "FIXED" JAVASCRIPT!
<div id="calcWrapper">
<form id="calc" name="calc" onsubmit="calcGPA(); return false;">
<div id="letGrade">
<input tabindex="1" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="3" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="5" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="7" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="9" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="11" type="text" maxlength="1" placeholder="Letter Grade..." />
<label>Cumulative GPA:</label><output id="cumGPA" type="text" />
</div>
<div id="conHours">
<input tabindex="2" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="4" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="6" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="8" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="10" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="12" type="text" maxlength="1" placeholder="Contact Hours..." />
<input type="submit" value="Calculate" />
</div>
</form>
</div>
The reason why it's not working is because in your if statement, you're using a single equals. A single equals is setting grades[i] equal to 'A' - it's not actually evaluating grades[i] == 'A'.
You want to change single = to == for comparison
if (grades[i] == 'A'){
Something like this in your code:
if (grades[i] == 'A'){
gVals.push("4");
}
else if (grades[i] == 'B'){
gVals.push("3");
}
else if (grades[i] == 'C'){
gVals.push("2");
}
else if (grades[i] == 'D'){
gVals.push("1");
}
else if (grades[i] == 'F'){
gVals.push("0");
}
Note:-
Double equality == is used for comparison and single = is used for assignment in Javascript.
Also as Andy well pointed that in comments that your both the for loops are using the same index i which may cause problem to you(atleast not a good practice). It would be better if you create a new variable for second for loop. It is unclear what you want to achieve with both the for loops but I think that it can be done with single for loop also.
As it was pointed in other answers you should use comparison operator == instead of assign operator = in if conditions, and also don't forget that grades[i] are DOM objects and not some plain values - so you have to compare with some property of this objects (if you want to compare with input's text use value property)
if (grades[i].value == "A"){
gVals.push("4");
}
else if (grades[i].value == "B"){
gVals.push("3");
}

how to adapt this script to include a checkbox check if checked

I'm a total noob at javascript. I use this script between my head tags that will force the user to scroll through a textarea before hitting submit button
<script language="JavaScript">
<!--
function textareaAtEnd(textareaObj)
{
return ((textareaObj.scrollTop + textareaObj.offsetHeight) > textareaObj.scrollHeight);
}
function formValidation(formObj)
{
if (textareaAtEnd(formObj.licenseAgreement))
{
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
// -->
</script>
my <form> looks like this:
<form action="step2.php" method="post" onSubmit="return formValidation(this);">
<textarea name="licenseAgreement" rows="20" cols="90">Very long license agreement text</textarea>
<br />
<input name="agree" type="checkbox" value="yes" /> I have read and agreed the above license agreement
<br />
<input type="submit" value="CONTINUE">
</form>
How can I adapt this javascript to also check if <input name="agree" type="checkbox" value="yes" /> is checked and if not to echo a message to the user? I'm a total noob, it's my first time using javascript.
do
function formValidation(formObj) {
if(!formObj.agree.checked) {
alert ("Please agree to terms.")
return false;
} else if (textareaAtEnd(formObj.licenseAgreement)) {
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
Demo: Fiddle
Use the checked property :
var checkbox = document.getElementsByName("agree")[0];
if(checkbox.checked)
alert("Check that");
Here you go:
if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
}
Using ID's is a best practice I would always recommend using for client-side code.
So you would change your validation function to:
function formValidation() {
if (textareaAtEnd(document.getElementById('licenseAgreement')) == false) {
alert ("Please scroll to the end to move on.")
return false;
}
else if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
return false;
}
else {
return true;
}
}
Also be sure to add an id="agree" to your <input type="checkbox" and id="licenseAgreement" to your textarea...
So it should look like this:
<input name="agree" id="agree" type="checkbox" value="yes" />
...
<textarea name="licenseAgreement" id="licenseAgreement" rows="20" cols="90">
And your form tag, you can remove the this parameter:
onSubmit="return formValidation();"
Replace
<input name="agree" type="checkbox" value="yes" />
With
<input name="agree" id="agree" type="checkbox" value="yes" />
Add id=agree attribute for checkbox.
if(document.getElementById("agree").checked == false)
{
alert("Checkbox is not checked , please select checkbox");
}

Validation of the text field for search problems

I have a search box that has a default value as "Search",i need to write some javascript that checks if the value in the search box is either "Search" or empty, then i should not sent the request and i need to display "Please enter a keyword"`
Here is the code
<div id="search">
<form action="/" style="" method="post" name="searchForm" id="searchForm" onSubmit="grabSearch();">
<img src="/images/bg_search_left.jpg" id="search_box_left" width="5" height="32" alt="" />
<input id="search_box" type="text" value="Search" onblur="if (this.value == '') {this.value = 'Search';}" onfocus="if (this.value == 'Search') {this.value = '';}"/>
<input type="image" id="search_arrow" src="/images/bg_search_right.jpg" width="34" height="32" />
<input type="hidden" name="_page" value="SEARCH" />
<input type="hidden" name="_action" value="SEARCH" />
<input type="hidden" name="searchTerm" value="" />
</form>
</div>
function grabSearch(){
var search=document.getElementById('search_box').value;
if(search="Search"||search=""){
document.getElementById('search_box').value="Please Enter a keyword"
}
search=encodeSearch(search);
document.forms['searchForm'].searchTerm.value = search;
}
On form submit i am checking it and displaying the message "Please Enter a keyword". Although the message is displayed in the text field but the request is sent(which i don't want to happen) and also on focus of the text field i want the message(please enter a keyword)to go way too
In addition to Jeaffrey's answer, you are not using the correct comparison operators. It should be:
if(search === "Search" || search === ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}
After that change, you need to return that value from your onSubmit -
<form action="www.google.com" style="" method="post" name="searchForm" id="searchForm" onsubmit="return grabSearch();">
Have you tried to return false?
if(search == "Search" || search == ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}

Categories

Resources