I wonder if anyone could give me a pointer with some pre-population in JSP:
So I am attempting to pre-populate a checkbox depending on the value in the customers database record. The checkbox would be checked if there is a 1 in the field, the other option would be a 0 – where the checkbox should be empty.
I am currently using this code within the input:
<%if (UPDATEDPREFERENCES != null)
{
if (ISNEWSLETTER != "0") {
out.println("checked");
}
}
%>
so it would be:
<input type='checkbox' class="newsletter" name='temp_ISNEWSLETTER_FIELD' id="temp_ISNEWSLETTER_FIELD" <%if (UPDATEDPREFERENCES != null)
{
if (ISNEWSLETTER != "0") {
out.println("checked");
}
}
%>/>
As it stands, it pre-populates fine. However, it also populates if the field is 0. If I change it to read:
if (ISNEWSLETTER == "1")
then the checkbox is empty whether it’s a 1 or 0.
Am I missing something obvious? I am not a developer, I am in NYC and my support is in Belgium – they’ve all left for the day.
Strings are objects, not primitives. Use
equals(), not==/!=. The==/!=won’t check if they contain the same value, but if they point to the same object reference. Theequals()will check if they contain the same value.So, instead of
if (ISNEWSLETTER != "0")you should useand instead of
if (ISNEWSLETTER == "1")you should useThis problem is not related to JSP. You would have exactly the same problem when doing so in a normal Java class (where this kind of code actually belongs).
As an alternative, since they represent numbers, you could also just convert
ISNEWSLETTERto anint. It’s a primitive, so you should be able to use==/!=the usual way. You can if necessary convert aStringto anintusingInteger#parseInt(). Or, even more, if it actually represents a boolean state (it can only betrueorfalse), then you should rather usebooleaninstead. You can just use it straight in theifcondition without any need for comparisons.