Adam Smith Adam Smith - 4 days ago 5
HTML Question

How do you compare JavaScript innerHTML return values, when there's a special character involved?

I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.

A checkmark might be set by code like this:

if (whatever) checkLocation.innerHTML = CHECKMARK;


Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.

function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);

// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}

// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}


Here's the problem: this works so long as the const
CHECKMARK
contains something simple, like
"X"
. But specs call for a special HTML character to be used: in this case
&#x2713;
, or ✓. When I do the comparison (in the
if
line) it ends up comparing the string
"✓"
to the string
"&#x2713;"
. Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)

Thanks.

Answer

Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:

function encodeHtml(character) {
    var element = document.createElement("div");
    element.innerHTML = character;
    return element.innerHTML;
}

Then I can compare to what it returns, since it automatically changes "&#x2713;" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)

Thanks all for the help.

Comments