getting values and assigning them to a hidden field - javascript

I have the following function that is suppose to take a value from a field in a form and assign it to a hidden field when its called. for some reason its not working and I cant give you more details on why its not working simply because javascript doesnt really tell you much about whats wrong.
function clickChange(stype){
if(stype == '1'){
var fValue = document.getElementById('checkB1').value;
if(fCatValue == 0){
fCatValue = fValue;
}else{
fCatValue = 0;
}
document.getElementById('cat_1').value = fCatValue;
}elseif(stype == '2'){
var sValue = document.getElementById('checkB2').value;
if(sCatValue == 0){
sCatValue = sValue;
}else{
sCatValue = 0;
}
document.getElementById('cat_2').value = sCatValue;
}
}

You need to convert the values to integer, or treat them as a string:
either:
var fValue = parseInt(document.getElementById('checkB1').value)
if(fCatValue == 0){....
or
var fValue = document.getElementById('checkB1').value;
if(fCatValue =='0'){...

Because of the placement of your declaration of the variable sCatValue it looks like sCatValue goes out of scope (or doesn't get declared at all).It would probably be easier on you if you declare all of your function scoped variables at the beginning of your function and cut down on the number of nested if statements.
I'd also recommend you use self explanatory variable names to cut down on confusing yourself. Also I'd recommend walking through your code with the use of a javascript debugger like firebug or ie 9's built in one. (surprising I know). And using jshint to help out with the common rules.
I found some other bugs and cleaned things up a bit and this is what I got
function clickChange(stype) {
//declared at the start so no scope undefined issues
var sValue = document.getElementById('checkB2').value;
var fValue = document.getElementById('checkB1').value;
//changed the comparision op from == to ===
//in javascript '===' throws false if the types compared are not the
//same otherwise it attemps to preform implicit casting for you
if (stype === '1') {
//parsing to insure that the types are matching
//the 10 is a radix param. It insures your number is formatted as a decimal
if (parseInt(fCatValue,10)=== 0) {
fCatValue = fValue;
} else {
fCatValue = 0;
}
document.getElementById('cat_1').value = fCatValue;
} else if (stype === '2') {
if (parseInt(sCatValue,10)=== 0) {
sCatValue = sValue;
} else {
sCatValue = 0;
}
document.getElementById('cat_2').value = sCatValue;
}
}

Related

Assigning String to Variable with If Else Statements

sorry this is a super basic question, but I'm not too familiar with google script yet so finding answers to these simple tasks is proving to be difficult. In this code, I'm trying to set a string of numbers to a variable based on another variable. AppNaming is the variable I'm trying to assign the numbers to. AppType is already defined earlier in the code, and depending on the type, I need it to take only part of the variable AppNumber. Depending on the AppType, the AppNumber is separated by commas or slashes, hence the indexOf parts. Are if statements not allowed with var functions? I need the var AppNaming to change based on the AppType in order to name a file later on in the code. Thanks for all the help and sorry again if these questions are annoying; I'm still learning.
function AutoFill(e) {
// variables all defined earlier
//Naming code
var AppNaming = if( AppType == '1' ){
AppNumber.substring( 0, AppNumber.indexOf(","))
}
else if ( AppType == '2'){
AppNumber.substring( 0, AppNumber.indexOf("/"))
}
else ( AppType == '3'){
AppNumber.substring( 0, AppNumber.indexOf(","))
}
You can only assign values to variables. Unfortunately, if statements are not values so you can't say var a = if (...) { } but you can say var a = 3
An if statement controls the flow of the application.
var something = 20;
var a;
if (something > 20) {
a = "this block runs if something is greater than 20";
} else if (something < 20) {
a = "this block runs if something is less than 20";
} else {
a = "this block runs otherwise";
}
// The value of 'a' is 'this block runs otherwise' at this point
So in your example, you can assign App.Number.substring(0, AppNumber.indexOf(",") to a variable because that expression will return a value.
I would recommend you to learn the basics of JavaScript.

.length on array crashing when length is 1 (maybe issue with split)

I'm having trouble with this code. I've tried to troubleshoot it many times and seem to have isolated the issue, but can't figure out the cause.
If the variable called string is set to something in the form of "text v. text," the code runs fine and the first if-statement triggers the sentence. If the string contains text but no "v." i.e. nothing that meets the search separator value, the function fails and does not execute the second if-statement.
Link to Fiddle: http://jsfiddle.net/qsq4we99/
Snippet of code, there also would need to be a html div with ID "outputtext."
function brokenCode()
{
//Setting Relevant Variables
var string = "red";
var array = string.split("v.");
var number = array.length;
// Checking location of things
var findText1 = array[0].search("search text");
var findText2 = array[1].search("search text");
//Running Conditional Stuff
if(number > 1)
{
document.getElementById('outputtext').innerHTML = "2+ listed";
}
else if(number < 2)
{
document.getElementById('outputtext').innerHTML = "1 listed";
}
}
brokenCode();
In this simplified example there is no clear explanation why the search operations need to occur (they are there because in the real code they are needed... but something about them seems to be causing the problem (even in this simple example). If the two searches are removed, the code runs smoothly.
You can't start setting variables from the array without checking for length. Before setting findText1 & findText2, check to make sure the length of the array is greater than zero.
function brokenCode() {
//Setting Relevant Variables
var string = "red";
var array = string.split("v.");
var number = array.length;
if (number > 0) {
// Checking location of things
var findText1 = array[0].search("search text");
var findText2 = array[1].search("search text");
//Running Conditional Stuff
if(number > 1)
{
document.getElementById('outputtext').innerHTML = "2+ listed";
}
else if(number < 2)
{
document.getElementById('outputtext').innerHTML = "1 listed";
}
}
}
brokenCode();

JavaScript using isNaN to validate returns NaN

I have some code here that will make validations of whether or not the input from a text box is NOT an empty string and isNaN. When i do these validations on amounts entered, i would like it to add them up.. however when a user does not enter anything in one or more amount fields the program should just add entered fields. But instead i get NaN showing in the total field.
link to full code: http://jsfiddle.net/KxNqQ/
var $ = function (id) {
return document.getElementById(id);
}
var calculateBills = function () {
var myErrorFlag = "N";
for (i = 1; i <= 4; i++) {
AmountNumber = 'amount' + i;
AmountValue = $(AmountNumber).value;
if (AmountValue != "" && isNaN(AmountValue)) {
$(AmountNumber).style.color = "red";
myErrorFlag = "Y";
} else {
$(AmountNumber).style.color = "black";
myErrorFlag = "N";
}
}
if (myErrorFlag != "Y") {
var Amount = 0;
for (i = 1; i <= 4; i++) {
Amount += parseInt($('amount' + i).value,10);
}
$('total').value = Amount;
}
}
var clearFields = function () {
for (i = 1; i <= 4; i++) {
itemName = 'item' + i;
$(itemName).value = "";
}
for (i = 1; i <= 4; i++) {
amountName = 'amount' + i;
$(amountName).value = "";
}
$('total').value = "";
}
window.onload = function () {
$("clearfields").onclick = clearFields;
$("addbills").onclick = calculateBills;
}
I think you've got your requirements a little bit confused, or at the very least I was confused by them. So in order to answer your question, I'm going to rephrase the requirements so I understand them better. This is a useful exercise that I try to do when I'm not 100% sure of the requirements; if I can't get the requirements right, what's to say I'll get the code right?
So the requirements – as I understand them – are:
Given each amount input
When the input has a value
And that value is a number
Then add the value to the total
And make the input color black
But if the input does not have a value
Or that value is not a number
Then make the input color red
Going through your code, I can see a number of problems with it. First, I noticed that both AmountNumber and AmountValue are global variables, because they were not declared local with the var keyword. So before fixing our code, let's change that. Let's also change the variable names to something that more accurately describe what they are, hopefully making the code easier to understand:
var input = $('amount' + i);
var value = input.value;
Now, note that I chose to store the element in the input variable. This is so we don't have to look it up multiple times within the loop. Looking things up in the DOM can be expensive so we'll want to keep it to a minimum. There are other was to look up elements as well, such as getElementsByClassName, querySelector and querySelectorAll; those are left as an exercise for the reader to research and evaluate.
Next, in each iteration of the loop, you check that AmountValue is not a string and simultaneously is not a number:
if (AmountValue != "" && isNaN(AmountValue)) {
This will be true so long as AmountValue is truthy (which is the case for non-empty strings) and so long as isNaN thinks it's a number (which is the case for strings that contain numbers.) It really is rather confusing; if I understand your code correctly this clause is there to check for invalid input and if it is true should mark the input field red and set a flag. I.e. this is the but clause in the aforementioned requirements.
Let's rewrite this to be the when clause instead, we'll take care of the but later. Before we do that, let's look at the myErrorFlag. It's used – I think – to see whether all input is well formed and in that case, add it all up. Well, validation and summation can be done in one fell swoop, so let's get rid of the flag and sum the values while validating them. So we replace myErrorFlag with a total variable:
var total = 0;
Now, let's get back to our clause. The requirements say:
When the input has a value
And that value is a number
Then add the value to the total
In code, that should look something like this:
if (value && !isNaN(value)) {
total += parseInt(value, 10);
input.style.color = 'black';
}
There are a couple of things going on here. For one, the if statement has been turned on its head a bit from what it was. It first checks to see that value is truthy, then that it is a number. The second check can be a bit tricky to read, because it is essentially a double negation; in english it reads "is not not a number", i.e. "is a number". I'll leave it as an exercise for the reader to figure out whether there's a more easily understood way of writing this check.
Now what about the but clause in our requirements?
But if the input does not have a value
Or that value is not a number
Then make the input color red
Well, it's essentially the inverse of our previous statement, so let's simply add an else clause:
else {
input.style.color = 'red';
}
Because the requirements doesn't mention the total variable in this clause, it is simply ignored and doesn't show up in the end result.
Adding it all up (no pun intended) the code – with comments – looks like this:
var calculateBills = function () {
var total = 0;
for (i = 1; i <= 4; i++) {
// Given each amount input
var input = $('amount' + i);
var value = input.value;
if (value && !isNaN(value)) {
// When the input has a value
// And that value is a number
// Then add the value to the total
total += parseInt(value, 10);
// And make the input color black
input.style.color = 'black';
} else {
// But if the input does not have a value
// Or that value is not a number
// Then make the input color red
input.style.color = 'red';
}
}
$('total').value = total;
};
There are more things that could be learned from this to make for better code. For instance, this code will break if the number of inputs change, or if their id names change. This is because they are selected specifically by their IDs and as such, if those change then this code will no longer function.
Another potential issue is that we're setting inline styles on the inputs as we loop over them. This means that in order to keep this code up to date with the styling of the site, it'll have to change. Generally, mixing styling and functionality like this is not a good idea and should be avoided. One way of doing so is to use class names instead, and toggle these on and off. Incidentally, this could also help the previous problem I mentioned.
There are other problems as well, but we'll leave those for another day. Hope this helps!
Try this
var calculateBills = function () {
var Amount = 0;
for (i = 1; i <= 4; i++) {
var AmountElement = $('amount' + i),
AmountValue = AmountElement.value;
if (AmountValue != "" && !isNaN(AmountValue)) {
AmountElement.style.color = "red";
Amount += parseInt(AmountValue,10);
} else {
AmountElement.style.color = "";
}
}
$('total').value = Amount;
};
Demo
Anyway, instead of using elements with id like id="amount1", id="amount2", id="amount3", etc., you could use classes (e.g class="amount") and get them with .getElementsByClassName

keep add the value without overwrite the function

function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}

Getting the length of a textbox value or content using JavaScript

This is something that's driving me nuts:
I have this code and it works: I am trying to learn JavaScript before becoming addicted to JQuery. My sample project involves getting the value of the text-box, and validating according to it's length. the name of the form is membership.
Example: This works:
function validateForm()
{
var element = document.membership;
if(element.txtName.value == "")
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
But this doesn't:
function validateForm()
{
var element = document.membership;
var nameLenght = element.txtName.value.lenght;
if(nameLenght < 1)
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
Just an FYI: I am new to JavaScript but very familiar with the syntax. I just want to learn the basics and move up.
I even read some solutions on here but feel I am simply sinking deeper.
Thanks for your help.
May be it is just because of typo in length here:
element.txtName.value.lenght;
must be element.txtName.value.length;.
If you want it to run every time user presses key , then look here: How to check string length with JavaScript
you can use this function as well
var a = txtName.value;
if (a.length < 1) {
alert('your message');
return false;
}

Categories

Resources