I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.
Related
I've created a script (my first) that accepts input text and then runs about 30 regular expressions on the text, outputting discovered values into an HTML table. The purpose is for me to be able to paste in text containing specification information for products and have them uniformly outputted so I can paste them into a spreadsheet.
I've had it working really well and I've been tuning the regexes as I've pasted data with different variations/layouts in. However, I've hit an impasse and need some assistance:
One of the regular expressions searches for the product part number (sku) and returns the value in a column. Some of the source data includes more than one match because there are regional variations to the products. In all cases the first match is the only one that I want. I've tested the RegEx on RegEx101 and it returns the first match only with the 'global' flag switched off. However, the same RegEx running in my script causes it to return console messages infinitely before crashing. It's immediately unresponsive so I can't see any error messages.
Here's a sample of the regex section in my script. sku being the one that's causing problems:
let wallMountable = /(?<wallmountable>[Ww]all [Mm]ount)/mg;
let sku = /^.*\((?<sku>\d\d\w\w[\d\w]+?).+?\).*$/m;
function parseData() {
// Execute the Regular Expressions on the text in 'specSheet'
let specSheet = document.getElementById("specSheet").value;
let wallMountableToken = wallMountable.exec(specSheet);
let skuToken = sku.exec(specSheet);
do {
// If Token isn't null, then test to see if the regex group value is undefined. If either are true, do nothing, otherwise write the value to the document.
if (wallMountableToken !== null) {
if (wallMountableToken.groups.wallmountable !== undefined)
{document.write(`${wallMountableToken.groups.wallmountable}`);}
else {}
}
else {}
if (skuToken !== null) {
if (skuToken.groups.sku !== undefined)
{document.write(`${skuToken.groups.sku}`);}
else {}
}
else {}
}
// Loop through the script until a condition is met.
while (
(wallMountableToken = wallMountable.exec(specSheet)) !== null,
(skuToken = sku.exec(specSheet)) !== null
);
}
The while loop may not be necessary and in truth I'm not entirely sure what purpose it serves here, but it seemed to consistently appear in the reference material I was studying. I have included it here because it's part of the script, but please note that the script works if I change the second regex to /mg instead of /m, however, it returns multiple values and I only want it to return the first capture.
I know there's a lot wrong with the script, but this particular question is about why the regex is causing an infinite loop, so any help toward that goal is much appreciated.
I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.
Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}
commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
I've got an two if() statements, for which the conditions are both met with the default values in the <select> and <input> form fields I've tested this by assigning the values to a variable and writing the variable. (0 and Url).
However, it seems that neither if() statement's contents execute properly.
Here's a link to my JSFiddle: http://jsfiddle.net/cfRAk/2/
Any edits/answers as to why this is happening would be greatly appreciated!
Change this line:
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
To this:
var geo_select_val = parseInt($('select[name=g_country\\[1\\]]').val());
The thing is geo_select_val is actually "0" and not 0. Converting a string to boolean will only result in false if string is empty. "0" is not empty, so it was being evaluated as true. Since you are going !geo_select_val, it never goes in.
Caveat: this fix will only work if you make sure all values are numbers. If that's not the case, check for equality with "0"
Here's the code you're asking about:
$('#post-form').click( function() {
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
if(!geo_select_val) {
var geo_url_val = $('input[name=g_url\\[1\\]]').val();
if(geo_url_val != "http://google.com") {
$('#notification').html("You need to enter a valid url");
}
}
});
When I set a breakpoint in this click function and then click on the Post Form div, geo_select_val comes back as "0" which means that if(!geo_select_val) will fail because geo_select_val does have a value so the first if condition will never be executed.
Perhaps you want the first if condition to be:
if (geo_select_val != "0") {
which will tell you if some other value besides the default has been selected (assuming you add other options to that select tag with different values).
What am I doing wrong here? I even tried it with case instead of if and it does not work
function updateResultPage(the_resp,r) {
var to_alert="s";
if(the_resp=="11"){
to_alert="Thank you!!";
}
else if(the_resp=="22"){
to_alert="Error:.";
}
else if(the_resp=="33"){
to_alert="ERROR 234dfR,.";
}
alert("c "+to_alert+the_resp);
}
I get an alert that displays C s22
Why is it skipping past all the if() statements?
EDIT:
Ok, I added this code to see the exact value of resp: alert("d "+to_alert+" *"+the_resp+"*");
and the second * is coming on the next line, so it looks like i have a trimming problem...
Add
the_resp = the_resp.replace(/^\s*|\s*$/g,""); // will trim it.
at the beginning of your function.
Remove this
alert("c "+to_alert+the_resp);
or add an else
else{
alert("c "+to_alert+the_resp);
}
Might be worth checking to make sure you are passing in an actual string or string object (as opposed to say an int). May also be worth making sure there isn't any non-printing whitespace in your input by trimming appropriately..