Javascript if statement not working as intended - javascript

If you look here and try to click on the voting arrows, you'll see my problem. Now compare that to the homepage (click logo). Try voting there. The arrows change image based on vote. I also use a in_array() function to determine what the user has voted on and it produces the correct voting icon. This all works fine on the submission page I linked to. However, again, if you try clicking on the links, it always defaults to the else statement in this Javascript function:
I'll only show the function for liking, as I'm having the identical problem for the dislike.
function getVote(filename, num, idnum, user)
{
var like = document.getElementById('like_arrow' + num);
var dislike = document.getElementById('dislike_arrow' + num);
if (like.src.indexOf('../vote_triangle.png')!=-1 && dislike.src.indexOf('../vote_triangle_flip.png')!=-1) {
like.src = '../vote_triangle_like.png';
(AJAX to alter rating here)
} else if (like.src.indexOf('../vote_triangle.png') != -1) {
like.src = '../vote_triangle_like.png';
dislike.src = '../vote_triangle_flip.png';
(AJAX to alter rating here)
} else {
like.src = '../vote_triangle.png'; // Always defaults to this
(AJAX to alter rating here)
}
}
In case you're wondering, the num variable is what I use on the front page to differentiate between the submissions, they increment by one for each one. In this though, I just made that value blank in the function so it shouldn't affect anything. Might be my problem though, but I can't see how.
Thanks!

like.src isn't going to contain ..\. It may be as simple as removing that part.

Related

If Else Statements in Javascript for LiveCycle

I am creating a form on Adobe LiveCycle that adds the numbers in different fields. I need to have the final field (Eligible Assets) add all the previous fields but exclude the sum of three of them and one in specific but only if it is greater than 60000. I've written the script as follows for the first part (to sum all the fields) this is in a field I've titled TotalAssets:
this.rawValue =Cash.rawValue+SavingsAccount.rawValue+ChildrensSavings.rawValue+CheckingAccount.rawValue+ValueHome1.rawValue+ValueHome2.rawValue+ValueVehicle1.rawValue+ValueVehicle2.rawValue+ValueVehicle3.rawValue+BusinessAccount.rawValue+BusinessAssets.rawValue+StocksBonds.rawValue+Retirement.rawValue+CDs.rawValue+OtherInvestments.rawValue+OtherAssets.rawValue;
This has worked fine, but the Retirement value if it is greater than 60000 should not be added into the calculation. This is what I've written (EligibleAssets):
if (Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
} else {
Retirement.rawValue == Retirement.rawValue ;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue+ValueVehicle1.rawValue +Retirement.rawValue);
When I save the form as a PDF the first total of the fields calculates correctly but the second field comes up blank.
If you can spot what I'm missing or doing wrong I would really appreciate any feedback. Thank you!
There are two simple problems that I see here.
First problem is that you are using == when you should be using =.
== - check if the left side is equal to the right side. Example: if(x == 5) {
= - set the left side to the value of the right side. Example: x = 5
In the first example we leave x alone, but in the second example we change x to 5.
So your code should look like:
} else {
Retirement.rawValue = Retirement.rawValue;
}
However, when you think about this, this code doesn't actually do anything. Retirement.rawValue will not change.
This leads us to the second mistake in the code, at least, it looks to me like a mistake.
if(Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
}
This actually changes Retirement.rawValue, which might potentially change what's inside the Retirement field of your form. Worse, its possible that the form would look the same, but act differently when some other field calculates, since you've changed its rawValue. That would be a very tough bug to catch.
The solution is to create a new variable: http://www.w3schools.com/js/js_variables.asp
So now we can create a new variable, set that variable to either the retirement amount or nothing, and then add that variable to the other rawValues at the end:
var retirementOrZero;
if(Retirement.rawValue > 60000) {
retirementOrZero = 0;
} else {
retirementOrZero = Retirement.rawValue;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue + ValueVehicle1.rawValue + retirementOrZero);
Now we have a number that we can name anything we want, and we can change it however we want, without affecting any code but our own. So we start by checking if our retirement value is greater than 60000. If it is greater, we set our variable to 0. Otherwise, we set our variable to the retirement value. Then we add that variable we made, to the home and value cost.
As a final question, is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 0;
}
or is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 60000;
}
Of course, if you are setting it to 60000 instead of setting it to zero, you probably want to name your variable cappedRetirementValue or something like that -- just make sure you rename it everywhere its used!
Hopefully that helps!
Edit: You said you're only adding retirement value if it is greater than 60k, so what you want is this:
if(RetirementValue.rawValue > 60000) {
retirementValueOrZero = RetirementValue.rawValue;
} else {
retirementValueOrZero = 0;
}

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

Trigger event not working or suspected passing on index

.full-arrow is an arrow that selects the next page. .full-navigation is a navigation bar, quite simply boxes in a line that change colour when you select them. The rest of the function isn't on here but you get the general idea.
When I create a trigger event to the function below the first one, it goes through okay but I'm unsure whether it's not picking up the index() or whether it's just not working at all. Weirdly, it works the first time but I think that's because the same_page variable is declared as 0 in the beginning.
The reason I'm also doubting whether it's the index() not being passed on is because the alert("foo"); isn't coming up.
$(".full-arrow").click(function() {
$(".full-navigation li:eq(" + same_page+1 + ")").trigger("click");
});
$(".full-navigation li").click(function(event) {
//alert("foo");
//alert(same_page);
same_page = $(this).index();
if(same_page == $(this).index()) { return false; }
});
Where are you getting the same_page variable from? Try using parseInt( same_page, 10 )--I have a hunch it's actually a string.

jquery masked input plugin to not clear field when errored

I'm looking at the http://digitalbush.com/projects/masked-input-plugin/
I'm calling it like this:
$(control).mask('999-999-9999');
And I don't want it to throw away the users input if something is wrong, e.g. they haven't finished
[407-555-____]
If you leave the field after having typed this much, it clears it. I'd like to leave it so they can finish later.
I'm new to jQuery, and I've looked through his source, but I can't find any way to do that, nor can I find any way to edit it to accomplish what I want, because the code is arcane to my eyes.
Set autoclear option to false.
$(control).mask('999-999-9999', {autoclear: false});
It looks like I should just make the whole mask optional:
mask('?999-999-9999')
That way the control thinks what the user has is "valid" and I can continue. Even though it isn't really the optional part of the mask.
You should delete statement input.val(""); in checkVal() function for a proper solution.
If you're using minified version, you should search and delete statement:
if(!a&&c+1<i)f.val(""),t(0,k);else
Try update file jquery.maskedinput.js
In function function checkVal(allow) set parameter allow on true. Its help for me.
function checkVal(allow) {
allow = true; ///add this command
//..............
}
In addition to removing the input.val("") in checkVal() you can also change the call to clearBuffer.
In the original code it is: clearBuffer(0, len); removing all user input.
if you change this to clearBuffer(lastMatch + 1, len); the user input will be displayed, followed by the mask placeholders that are still needed to complete correct input.
I have also added a user message in the .bind. This works for us, as we are using the MaskedInput for exactly one type of input. I'm checking for any input going further than position 7, because that's where the user input starts.
Here is what I did:
.bind("blur.mask", function() {
// find out at which position the checkVal took place
var pos = checkVal();
// if there was no input, ignore
if (pos <=7) {input.val(""); clearBuffer(0, len);}
// if the user started to input something, which is not complete, issue an alert
if (pos > 7 && pos < partialPosition) alert("Tell the user what he needs to do.");
if (input.val() != focusText)
input.change();
})
Adding Placeholder could solve the problem.
$(control).mask('999-999-9999');
Add an empty place holder into mask. see below
$(control).mask('999-999-9999', { placeholder: "" });
which would replace _ on the input text field by default. so there would bot be any _ left if the input length is dynamic and not fixed.
Looking for into the pluging script the unmask method.
$('#checkbox').unmask();

How to loop through elements and call onblur handler for certain elements

I have a case where I have a bunch of text boxes and radio buttons on a screen all built dynamically with various DIVs. There are onblur routines for all of the text boxes to validate entry, but depending on the radio button selection, the text box entry could be invalid when it was valid originally. I can't use onblur with the radio buttons because they could go from the radio button into one of the text boxes that was made invalid and create an infinite loop since I'm putting focus into the invalid element. Since each text box has its own special parameters for the onblur calls, I figure the best way to do this is to call the onblur event for the textboxes when the form gets submitted to make sure all entry is still valid with the radio button configuration they have selected. I also need it to stop submitting if one of the onblur events returns false so they can correct the textbox that is wrong. This is what I've written:
for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
{
if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount") // The first 3 characters of the name are a unique identifier for each field
{
if (document.forms[0].elements[intElement].onblur())
{
return false;
break;
}
}
}
return true;
I originally had (!document.forms[0].elements[intElement].onblur()) but the alert messages from the onblur events weren't popping up when I had that. Now the alert messages are popping up, but it's still continuing to loop through elements if it hits an error. I've stepped through this with a debugger both ways, and it appears to be looping just fine, but it's either 1) not stopping and returning false when I need it to or 2) not executing my alert messages to tell the user what the error was. Can someone possibly help? It's probably something stupid I'm doing.
The onblur method that is getting called looks like this:
function f_VerifyRange(tagFactor, reaMin, reaMax, intPrecision, sLOB, sIL, sFactorCode)
{
var tagCreditOrDebit;
var tagIsTotal;
var tagPercentageOrDecimal;
eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");
eval("tagIsTotal = document.forms[0]." + tagFactor.name.substr(0,3) + "IsTotal");
eval("tagPercentageOrDecimal = document.forms[0]." + tagFactor.name.substr(0,3) + "PercentageOrDecimal");
if (tagPercentageOrDecimal.value == "P")
{
reaMax = Math.round((reaMax - 1) * 100);
reaMin = Math.round((1 - reaMin) * 100);
if (parseFloat(tagFactor.value) == 0)
{
alert("Please enter a value other than 0 or leave this field blank.");
f_SetFocus(tagFactor);
return false;
}
if (tagIsTotal.value == "True")
{
if (tagCreditOrDebit.checked)
{
if (parseFloat(tagFactor.value) > reaMin)
{
alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
f_SetFocus(tagFactor);
return false;
}
}
else
{
if (parseFloat(tagFactor.value) > reaMax)
{
alert("Please enter a value less than or equal to " + reaMin + "% for a credit or " + reaMax + "% for a debit.");
f_SetFocus(tagFactor);
return false;
}
}
}
}
return true;
}
EDIT: I think I've figured out why this isn't working as expected, but I still don't know how I can accomplish what I need to. The line below:
if (!document.forms[0].elements[intElement].onblur())
or
if (document.forms[0].elements[intElement].onblur())
is not returning what the single onblur function (f_VerifyRange) is returning. Instead it is always returning either true or false no matter what. In the first case, it returns true and then quits and aborts the submit after the first textbox even though there was no error with the first textbox. In the second case, it returns false and runs through all the boxes. Even though there might have been errors (which it displays), it doesn't think there are any errors, so it continues on with the submit. I guess what I really need is how to get the return value from f_VerifyRange which is my onblur function.
This question is a bit too involved for me at this time of the night, but I will give you this bit of advice:
eval("tagCreditOrDebit = document.forms[0]." + tagFactor.name.substr(0,3) + "CreditOrDebitC");
This can be written in a MUCH better way:
tagCreditOrDebit = document.forms[0][tagFactor.name.substr(0,3) + "CreditOrDebitC"];
In javascript, anywhere where you can use dotted syntax, you can use square brackets.
document.body;
document['body'];
var b = 'body';
document[b];
Also, think about giving your forms some sort of identifier. I have no clue at all why document.forms[0] was the standard way to address a form for so long... if you decide to place another form on the page before this one, then everything will break!
Other ways to do it include:
// HTML
<form name="myFormName">
// Javascript
var f = document.myFormName;
or
<form id="myFormId">
var f = document.getElementById("myFormId")
You´re not getting any success with if (!...onblur()) because the return of onblur() is always undefined when used directly. OnBlur() is a Event Handler Function. Like you descovered, you have to create a workaround.
I ended up solving this with a global variable. I originally set a value g_bHardEditsPassed to true assuming we will have no errors. Then in f_VerifyRange, everytime I return a value, I put a line before it to set the g_bHardEditsPassed variable to match. Then I modified the loop to look like this...
g_bHardEditsPassed = true;
for (var intElement = 0; intElement < document.forms[0].elements.length; intElement = intElement + 1)
{
if (document.forms[0].elements[intElement].name.substr(3) == "FactorAmount")
{
document.forms[0].elements[intElement].onblur()
if (!g_bHardEditsPassed)
{
g_bHardEditsPassed = true;
return false;
}
}
}
return true;
Thanks for everyone's suggestions. I'm sure that the jQuery thing especially will be worth looking into for the future.
First, for the love of god and all that is holy, stop writing native javascript and help yourself to some of that jQuery :)
Second, start using a validation framework. For jQuery, jQuery Validate usually works really well. It supports things like dependencies between different fields, etc. And you can also quite easily add new rules, like valid ISBN numbers, etc.
Edit: As for your code, I'm not sure that you can use onunload for this, as at that point there's no way back, you can't abort at that point. You should put this code on the onsubmit event instead.

Categories

Resources