Comparing el.text() === "string" results in false, even when element contains "string" - javascript

In the below code, the else and not the if is always executed even though the alert tells me that state does in fact contain the string payment.
var state = $('.check-state').text();
alert(state); // payment
if (state === "payment")
alert('hello');
else
alert('not match')
Why is that?

I am guessing your HTML look sort of like this:
<div class="check-state">
payment
</div>
Then the .text() will return everything between the > and the <, including the whitespace. So what you get is "\n payment\n", not "payment".
The solution is to trim the whitespace away, using jQuerys $.trim():
var state = $.trim($('.check-state').text());
On a side note, I would recommend you to use console.log() instead of alert() for debugging. In most browsers, that would have allowed you to detect where the error was since you would have clearly seen the whitespace.

Related

Javascript RegEx causes message loop and crashes browser when set to anything other than /mg

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.

Multiple Selectors on If Statement

So, I'm trying to make sure a button is disabled to prevent a user from saving data from form field entries whenever two conditions are met:
The checkbox is checked
There's nothing inside the form field in question ( #read_return_response_rate_ids )
This is what I have to that end:
$('body').on("change","#tab3 #read_return_response_rate_ids", function(){
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
$('.create_read_btn').attr('disabled', 'disabled');
} else {
$('.create_read_btn').removeAttr('disabled');
}
});
The error it's giving me in the console is totally useless towards debugging purposes.
Uncaught SyntaxError: Unexpected token /
It's my thought that this is where the problem exists:
if ($(this).is('')) && ($('input:checkbox').is(':checked'))
Basically, I don't think I can have multiple selectors as I have them structured, but I don't know. Does anyone have any thoughts on why this is returning an error? I confirmed that this code block is where the error originates by selectively commenting out other blocks of code and whittling it down to this one.
There are syntax errors (parenthesis chars note required):
Change:
if ($(this).is('')) && ($('input:checkbox').is(':checked')) {
by
if ($(this).is('') && $('input:checkbox').is(':checked')) {
The argument to .is() must be a selector or jQuery collection; it tests whether the specified element matches the selector or is the same set of objects. If you want to test whether an input field is empty, you need to use .val() to get the value.
if ($(this).val() == '' && $('input:checkbox').is(':checked')) {

Cannot compare String returned by out.print()

I am using jsp as a server side script with HTML/JQuery for the client end.
I am doing a AJAX to the jsp file and everything works ok.
The problem starts when I am trying to compare the string returned by out.print() from jsp with in the jquery ajax result. The comparison never seems to result true!
It seems the out.print() is prepending a number of /n to the string.
$.post("jsp/login.jsp", { msg: $email.val() + "~" + $pass.val() }, function (result) {
if (result === "OK")
alert("Logged in");
else
alert("Invalid Credentials");
});
It seems the out.print() is prepending a number of /n to the string.
In this case you have two options. First, you can remove the extra whitespace in JS before using the value in a condition:
if ($.trim(result) === "OK")
alert("Logged in");
else
alert("Invalid Credentials");
Alternatively, and preferably, you could change your JSP code to return JSON. By definition this cannot have extraneous whitespace added to the values of its properties.
Remember how Java object comparisons work. In java a string literal "OK" in this case is itself an object and has it's own location in memory. When you do a comparison with another string object, result in this case, you aren't comparing the actual value of the two strings as you would with primitive types you're comparing the object location in memory. As such, you could use something like compareTo which is associated with String, something like this.
//Compare to returns an int, -1 for less then, 1 for greater then and 0 for equals
if(result.compareTo("OK") == 0){
//Do your code here
}

javascript variables always not equal

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.

Unable to detect empty paragraph

I am using the following code to check for an empty paragraph but it never returns true. Why?
var isEmpty = pageChildren[i].outerHTML.toUpperCase() === "<P></P>";
var isSpace = pageChildren[i].outerHTML.toUpperCase() === "<P> </P>";
var isNbsp = pageChildren[i].outerHTML.toUpperCase() === "<P>&NBSP;</P>";
if(!isEmpty && !isSpace && !isNbsp){
//do something
}else{
//do something else
}
This is a copy paste of what IE8 debug tools tells me is in the outerHTML: "<P></P>"
This is being read from an iFrame so i need to remove the <p></p> tags also as the function above this triggers off of the number of children elements in the body of the frame.
Additionally this runs in an HTA application on IE only. The userbase/configuration is highly controlled.
If you're sure your object is a paragraph, you should use innerHTML instead :
var isEmpty = pageChildren[i].innerHTML.trim().length==0;
(note that the MDN proposes a replacement for IE8 which lacks trim).
You could also use textContent but the downside is that you have to do a different test for IE.
Since trim() isn't supported by all browsers, I suggest removing all spaces with RegEx:
var isEmpty =
(pageChildren[i].innerHTML.replace(/\s/g, '').length == 0) ? true : false;
It seems that IE < 9 prepends a carriage return, line feed to the outerHTML result, so for example pageChildren[i].outerHTML.toUpperCase() === '\r\n<P></P>' returns true for an empty p element.

Categories