Javascript IF ELSE statement stopping short - javascript

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");
}

Related

How to count filled text box in angular 2

I have six text boxes and I want to count the number of filled boxes
<input type="text" #tb1 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb2)" />
<input type="text" #tb2 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb2)" />
<input type="text" #tb3 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb3)" />
<input type="text" #tb4 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb4)" />
<input type="text" #tb5 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb5)" />
<input type="text" #tb6 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb6)" />
{{counter}}
counter: number = 0;
counterfunc(tb){
// need help here
if (tb.value != '') {
this.counter++;
}
}
I found this plunker plunkr but this is for checkboxes. how can I count the number of the filled text boxes? and a number of counts should decrease one if user empty the box. Thank you
I don't see the point of declaring seleveral variables for a component (well, input) that behaves exactly the same in any case. You should declare a list of inputs, not a variable for every input.
Use the children decorator for that
<ng-container *ngFor="let i of [0, 1, 2, 3, 4, 5]">
<input type="text" #textboxes placeholder="Weight" class="form-control" (input)="input()"/>
</ng-container>
<p>{{filledCount}}</p>
In your TS
filledCount: number = 0;
#ViewChildren('textboxes') textboxes: QueryList<ElementRef>;
input() { this.filledCount = this.textboxes.filter(t => t.nativeElement.value).length; }
Here is a working stackblitz.
try this and just take this as a key
counter: number = 0;
counterfunc(tb){
if (tb.value != '' && tb.value.length == 1) {
this.counter++;
}
if(tb.value == '')
{
this.counter--;
}
}
Create a form and add validation to the form. On every change count the valid or invalid fields

Javascript check if an input is a Long or not [duplicate]

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?
Below is the input field as part of my form:
<input type="text" id="sessionNo" name="sessionNum" />
Is it using something like maxSize or something like that?
maxlength:
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field
will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.
The simplest way to do so:
maxlength="5"
So.. Adding this attribute to your control:
<input type="text"
id="sessionNo"
name="sessionNum"
onkeypress="return isNumberKey(event)"
maxlength="5" />
Add the following to the header:
<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</script>
<input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);"
onKeyUp="limitText(this,5);"" />
Make it simpler
<input type="text" maxlength="3" />
and use an alert to show that max chars have been used.
According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.
Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway
<input type="text" maxlength="5">
the maximum amount of letters that can be in the input is 5.
Maxlength
The maximum number of characters that will be accepted as input.
The maxlength attribute specifies the maximum number of characters allowed in the element.
Maxlength W3 schools
<form action="/action_page.php">
Username: <input type="text" name="usrname" maxlength="5"><br>
<input type="submit" value="Submit">
</form>
I always do it like this:
$(document).ready(function() {
var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
maxChars.on('keyup', function(e) {
length = new Number(maxChars.val().length);
counter = max_length - length;
$("#sessionNum_counter").text(counter);
});
}
});
Input:
<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>
You can use
<input type = "text" maxlength="9">
or
<input type = "number" maxlength="9"> for numbers
or
<input type = "email" maxlength="9"> for email
validation will show up
<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">
function maxLengthCheck(object) {
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}
The following code includes a counted...
var count = 1;
do {
function count_down(obj, count){
let element = document.getElementById('count'+ count);
element.innerHTML = 80 - obj.value.length;
if(80 - obj.value.length < 5){
element.style.color = "firebrick";
}else{
element.style.color = "#333";
}
}
count++;
} while (count < 20);
.text-input {
padding: 8px 16px;
width: 50%;
margin-bottom: 5px;
margin-top: 10px;
font-size: 20px;
font-weight: 700;
font-family: Raleway;
border: 1px solid dodgerblue;
}
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80" class="text-input" name="bikeTitle" ></p>
<span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
Late to the party, but if you want a full proof way to restrict numbers or letters that is simply javascript and also limits length of characters:
Change the second number after .slice to set the how many characters. This has worked much better for me then maxlength.
Just Numbers:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);
Just Letters:
oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'').slice(0,20);"
Full example:
<input type="text" name="MobileNumber" id="MobileNumber" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);"/>
Use maxlenght="number of charcters"
<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>

dijit ValidationTextBox how to add minlength and maxlength

I would like to know how (with simple working example) to add maxlength and minlength to input tag generated by
dijit/form/ValidationTextBox
Example of desired output:
<input maxlength="10" minlength="2" class="dijitReset dijitInputInner" data-dojo-attach-point="textbox,focusNode" autocomplete="off" name="title" type="text" tabindex="0" id="Image-1-title-LabelValidationTextBox" aria-required="undefined" value="Title text for image Image-1" aria-invalid="false">
try this example with regex constraint
<input type="text" value="someTestString" required="true"
data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="regExp: '[a-zA-Z0-9$%!_]{2,10}', invalidMessage: 'The value must be at least 2 character and maximum 10'" />
ValidationTextBox has the properties minLength and maxLength. They are used in the following why in a declarative manner.
<input data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="required:true,
maxLength:5,
minLength:2"
type="text"
name="exmaple" />
Here's another solution:
registry.byId("validationTextBox").validator = function(value, constraints) {
if(value) {
return value.length >= 2 && value.length <= 10;
}
return true;
}

Generate 7 random letters into 7 form fields

I am in need to generate 1 random letter into 7 form fields. An example of the fields would look like below.
The letters can repeat, but only based on the letter and an amount of times that letter can repeat
For instance
a x 7 (a can repeat only 7 times)
b x 5 (b can repeat only 5 times)
c x 2 (c can repeat only 2 times)
and so on
<input type="text" name="1" maxlength="1" />
<input type="text" name="2" maxlength="1" />
<input type="text" name="3" maxlength="1" />
<input type="text" name="4" maxlength="1" />
<input type="text" name="5" maxlength="1" />
<input type="text" name="6" maxlength="1" />
<input type="text" name="7" maxlength="1" />
So far I have
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 1;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>
Im a little lost because this will only place it in one field. I am not sure how to optimize my javascript so that it can generate all the letters (1 into each field) AND make sure the letters dont repeat beyond what they are allowed too.
Any ideas?
document.randform.randomfield.value = randomstring;
randomfield is not specified in the block you give. I suspect that either it's interpreted as 0, in which case you might get the first field. Or you might initialize it to a particular field in a section of code you didn't provide. Or (most likely, from my limited knowledge of JavaScript) it's really the name of a field that isn't shown in your HTML snippet.
Regardless, this is likely where your error is. You need to change the location where you want to save the value if you want to save the value to multiple locations.

Javascript to validate element values and checkboxes

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;
}

Categories

Resources