I've got the following jQuery (I've got it wrapped in the document ready function and all that, so please know I'm just showing you the inside of the function.
..
var itemIsSold = $("#itemIsSold").val();
alert(itemIsSold);
if(!itemIsSold) {
...
}
where itemIsSold is a hidden input field. I get the value False upper case F when it hits the alert but never enters my next if statement. I know this has to be something stupid simple.
If the input's value contains the string "False", that will not translate into a false boolean value. You will need to actually check for itemIsSold == "False".
Since the value of the hidden input field is a string, !"False" will be evaluated to false. Note that any string other than a string with the length of 0 is treated as true. So you should rather compare the string value to another string value like "False":
if (itemIsSold == "False") {
// …
}
Related
I have been given a Javascript code, and there is a sentence I cannot fully understand:
var isFaculty = (paramArray[0] == "yes"),
isFaculty variable is used afterthat in a equation, where more variables are involved. While the latter are defined along the code, the former is supposed to be defined (i.e. numerical value) by that sentence, as it depends on a parameterArray that the user should introduce (the parameter array is of size 3, anyway). For cell [0], paramArray can have two values, namely "yes" or "no".
I am wondering a possibility, but any help is welcome.
Thanks in advance,
/Jorge.
(paramArray[0] == "yes")
This is like a mini if statement that returns either true or false.
isFaculty is a boolean variable that captures that result.
Once the true or false is caught it can be used as a numeric 1 or 0 that even though is not recommended but could be multiplied by a number to turn it into a 0 if it's false or leave it unchanged if it's true
thanks for your help. The point is that isFaculty variable is involved in a formula as follows:
var xExample = 1/(1+Math.exp(-(-2 + 4*city - 0.11*gender + 0.6*isFaculty + 0.2*city*gender - 0.424885*city*isFaculty - 0.3*citygenderisFaculty)));
consequently, I understand that isFaculty gets value 1 or 0 depending on being true or false?
== is a comparator that will return a boolean value, so the code you have will assign true or false to isFaculty
The var name isXxxx would suggest to me that its value would be boolean.
So what you have is basically:
var isFaculty - for the variable isFaculty
= - assign the value of the following expression
paramArray[0] - take the first value from the array paramArray
== - check if it matches in content but not necessarily type with
"yes" - the string value that you are looking for to assign true
Implicitly this also means that if the content of paramArray[0] does not match with the content of the string value "yes" then the value of isFaculty will be false.
This could be used as a 'flag' later on by using false as 0 and true as 1.
I have a javascript: bookmarklet with the code
javascript:document.body.contentEditable = !document.body.contentEditable;
which should switch on and off an "editor" for the page (just for pranks on friends and such). But it does not acheive the desired outcome, nothing happens when I click the bookmark. Opening up the Javascript Console, I see that:
document.body.contentEditable
"false"
!document.body.contentEditable
false
Previously, I used javascript:document.body.contentEditable = true; and this makes the page editable but I cannot turn it off.
Like you probably noticed in the JavaScript Console, document.body.contentEditable is a String, not a Boolean. You can do this instead:
document.body.contentEditable = !(document.body.contentEditable == "true");
or just
document.body.contentEditable = document.body.contentEditable != "true";
The HTMLElement.contentEditable property is used to indicate whether
or not the element is editable. This enumerated attribute can have the
following values:
"true" indicates that the element is contenteditable.
"false" indicates that the element cannot be edited.
"inherit" indicates that the element inherits its parent's editable status.
https://developer.mozilla.org/en/docs/Web/API/HTMLElement/contentEditable
document.body.contentEditable is a string value and JavaScript considers non-empty strings to be truthy.
!"" == true
!"a" == false
The value of contentEditable is a string, not a boolean. It can have the values "true", "false" or "inherit" (therefore it can't be a simple boolean). A boolean inversion won't work. You need to explicitly assign one of these three strings.
Is contentEditable a text input? So you need to parse the texto into boolean:
javascript:document.body.contentEditable = !JSON.parse(document.body.contentEditable);
deceze is correct here, I (somewhat stupidly) thought that because you do
document.body.contentEditable = true;
you could also do
!document.body.contentEditable;
but this is not correct.
In the end, I decided to use the property that is actually a boolean, isContentEditable, like so:
document.body.contentEditable = !document.body.isContentEditable;
I'm very confusing about javascript operators. Look at this:
localStorage.setItem('isValidUserCpf', false);
alert(localStorage.getItem('isValidUserCpf'));
alert(!localStorage.getItem('isValidUserCpf'));
alert(!(localStorage.getItem('isValidUserCpf')));
if (localStorage.getItem('isValidUserCpf') == false){
alert('notEntering');
}
Why all alerts are printing "false"? And why my if condition is not working? I really don't know what is my problem.
Thanks.
You can only store strings in local storage, so when you tried to store false it is converted to a string "false".
Your first alert shows this string. The others shows this string applied to not operator (!"false" === false) and the false value is converted to a string and shown in the alert.
What you can do is serialize you data to store it in localstorage
localStorage.setItem('isValidUserCpf', JSON.strinify(false));
var isValidUserCpf = localStorage.getItem('isValidUserCpf');
alert(isValidUserCpf);
alert(JSON.parse(isValidUserCpf));
alert(!JSON.parse(isValidUserCpf));
if (isValidUserCpf == false){
alert('notEntering');
}
https://developer.mozilla.org/en/docs/JSON
localStorage.setItem('isValidUserCpf', false);
false is stored as a string.
alert(localStorage.getItem('isValidUserCpf'));
alert with the string value "false"
alert(!localStorage.getItem('isValidUserCpf'));
alert with the boolean !"false" which is also false in boolean
alert(!(localStorage.getItem('isValidUserCpf')));
same as above one
Please test with
localStorage.setItem('isValidUserCpf', true);
you will see "true", false, false
I am not sure for what environment you are testing, you can see the value of localStorage with console.log(localStorage)
The keys and values for local storage are strings as defined by the standard. Non-empty strings are true when evaluated as a boolean, thus negating it would result in a false result. Similarly the string "false" is not the same as the boolean false. If you change the condition to compare strings, it will evaluate as you expect - working fiddle at http://jsfiddle.net/79pF5/
if (localStorage.getItem('isValidUserCpf') === 'false') {
alert('notEntering');
}
I am dynamically adding text to the input field from facebook signup data, and then populating these data to the form field which has a display:none property. After getting all the data the form should show as in display:block. But that is not working. the code seems to be working on console but not on the browser.
I am checking if the input field is filled then show the form or else no.
Here is the jsfiddle. http://jsfiddle.net/kqHmR/1/
if ($("#firstname").val() == $("#firstname").val(dataCollection.first_name)) {
$("#profileEdit").hide();
} else {
$("#profileEdit").show();
}
What is wrong with it? It is supposed to show me the form when there is something in the input fields but it's not showing .
Couldn't you just check if dataCollection.first_name is empty?
Here's a one-liner
$("#profileEdit").toggle(dataCollection.first_name.length);
Reference: http://api.jquery.com/toggle/
Explanation: .toggle() can accept a boolean. true = show, false = hide.
If a string's .length is zero, it evaluates to false, thus passing false into .toggle(). Vice versa.
In case you really want to check the input field's value instead, then:
$("#profileEdit").toggle( $.trim( $("#firstname").val() ).length );
Translated in English would be: Get me the value of firstname, trim it, and give me the length of that string, then pass it into .toggle()
.val() when called with an argument, sets the value and returns the jQuery object it was called on (to facilitate chaining). It does not return the value as such, unlike when called without arguments.
This means your if condition
if ($("#firstname").val() == $("#firstname").val(dataCollection.first_name)) {
will always fail as the RHS is not the newly set value but the jQuery object $("#firstname") itself.
How to know that a particular input type is present or not in a div?
If I use
$("#inputId").val()
And there is no element present on this, then js gives an error.
So how could I know that the input element named inputId is present or not?
Reply me ASAP
You could check if
$('#inputId').length > 0
i.e. if the current selector matched any elements.
But if $('#inputId').length == 0 then $('#inputId').val() will be undefined. This is different from the scenario where the input exists, because val() would always yield a string, that is or isn't null.
Now, you would produce an error only if you're trying to do stuff with the value, that may or may not be undefined. For instance, the following would not work if #inputId does not exist in the DOM:
if($('#inputId').val().length > 0) { ... }
... since you'd be trying to access undefined.length. However, you could still do
if(!!$('#inputId').val()) {
// this code will only be executed if #inputId exists, and has a value that
// is not an empty string
}
If you're writing form validation, it might be more useful to do
if($('#inputId').val() !== '') {
// this code will be executed if #inputId has a value, or if it does not
// exist in the DOM at all
}
The former condition checks that the result of .val() resolves to true, which is not the case for an empty string or for undefined. (It is also not the case for null, NaN, false or 0, but .val() will never yield any of those results)
The latter checks that the result of .val() is not exactly an empty string, which is true for an actual value, as well as for undefined.
You can use the length property, which will tell you the number of elements in the current selector.
if ($("#inputId").length > 0)
{
// code that depends on inputId being present can go in here
}
if ($("#inputId").length) { }
No need to be verbose, checking whether length === 0 or greater than 0: length value itself is automatically casted as a boolean inside an if statement
Without jQuery:
var input = document.getElementById('inputId');
if (input) {
// the input exists
alert(input.value);
} else {
// the input doesn't exist
alert('Ooops! An input with id "inputId" doesn\'t exist.');
}