!variable not working in javascript - javascript

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;

Related

CoffeeScript: toggle "true" and "false" of an attribute

I know that this should be pretty easy, but after searching around, I just don't seem to be able to find an answer.
I want to toggle the value of an aria attribute between true and false. I hoped there is some easy way for doing this, but I could only come up with the following:
if #container.attr('aria-hidden') == 'true'
#container.attr('aria-hidden', 'false')
else
#container.attr('aria-hidden', 'true')
I tried stuff with negating the values, but didn't succeed (I guess there's a problem between string booleans and real booleans, I mean false and "false").
I hoped that jQuery would offer something like this:
#container.toggleBool('aria-hidden')
There is no toggleBoolean method. All you can do is:
#container.attr 'aria-hidden', !/^true$/.test(#container.attr('aria-hidden'))
PS: And I still think that your snippet is more readable, so preferred.
Starting with jQuery 1.1, .attr() accepts a function as second argument, whose parameters are the index position of the element in the set, and the old attribute value. So, what about something like that (untested):
toggleBool = (index, attr) -> if attr='true' then 'false' else 'true'
[...]
#container.attr('aria-hidden', toggleBool)
If you find yourself doing this a lot, you could create a simple function to flip the strings 'truth value', assuming the string is always either 'true' or 'false':
flip = (x)->{'true':'false', 'false':'true'}[x]
. . .
#container.attr 'aria-hidden', flip(#container.attr('aria-hidden'))
but if it's neither, then it will return undefined, which may or may not be what you want:
coffee> flip('true')
'false'
coffee> flip('false')
'true'
coffee> flip('abcd')
undefined
I came up with this solution. At least it saves a few keystrokes.
handleEnterAndSpace: ->
#container.attr('aria-hidden', !#isOpen())
isOpen: ->
#container.attr('aria-hidden') == 'true'

Not operator not working on my javascript code

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');
}

Providing a default string parameter in JavaScript

I've always used the following syntax to ensure that the input variable isn't null.
function f(input){
if(input === null)
input = "";
...
}
Lately, I noticed that it's shorter to express it as follows.
function f(input){
input = input ? input : "";
...
}
But also, I've seen this syntax.
function f(input){
input = input || "";
...
}
Are those equivalent (not in what they do but in how they do it)?
Which is most recommended (readability etc.)?
Note that I'll be strictly working with inputs of strings such that it's either valid one or null (not provided at all). If I'd like to extend the protection to include other types, what additional issues should I take into consideration?
First, note that they aren't all the same. #2 and #3 have precisely the same result: unless input is truthy, set it to an empty string. #1 means says "unless input is null, set it to an empty string. So if false was provided, input would be false in #1 but '' in #2 and #3.
If nothing was provided to #1, (i.e. f(), input would be undefined, because that is the value that is passed when a parameter is missing, not null. One of these would fix this:
if(input === undefined)
if(input == null)
Otherwise, yes, they are functionally equivalent. For me, the best way to write it would be
input = input || "";
That is my preferred style. It may be yours; it may not. But, above all, be consistent.

Show form if input field has data or else dont show

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.

Check for bool in JavaScript

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") {
// …
}

Categories

Resources