Why does quoting matter with getElementById? - javascript

I have a dom object like this within an html page:
<textarea id="owctl7fzk">​foo</textarea>
When I try to access it with getElementById without quoting the id, it returns null.
window.document.getElementById(owctl7fzk)
but when I put the id within single or double quotes, it selects the object:
window.document.getElementById('owctl7fzk')
window.document.getElementById("owctl7fzk")
Why does the quotation matter in this case? In general, when you can you omit and when can you not?
Edit In the code I presented above, the id is a hexatridecimal number. I previously had a decimal number without quotes as id, and it had no problem. Why was that?

getElementById(owctl7fzk) selects the element whose id attribute is equal to the value of the owctl7fzk variable:
var owctl7fzk = "the_id";
var element = document.getElementById(owctl7fzk);
owctl7fzk is definitely not the same as "owctl7fzk", because the former is a variable name, while the latter is a string.
This is how JavaScript works. Just because you can omit the quotes in HTML doesn't mean that you can do the same in JavaScript.

It's because when the ID is within a quote, its a string that is used to identify the ID attribute, otherwise it's reference as a variable. If you are performing window.document.getElementById(owctl7fzk), javascript is searching for a variable named owctl7fzk. If you used var owctl7fzk = 'owctl7fzk', it shall work

It should be in quotes because you are passing a string parameter to the getElementById method. Strings need to be in quotes.

In javascript, as in most languages, the parser understands a quoted value to be a "string" and an unquoted one to be an identifier (this is oversimplifying, and in reality, it's the lexer, not the parser).
Specific to your question, an element's id is a string, and so must be represented as a string in your source. You can use a variable (represented in code by an identifier of your choice) to hold this string or to hold the element itself:
var my_id = "owctl7fzk";
var elem = document.getElementById(my_id);
alert( my_id + " is the same as " + elem.id );

Related

Remove first character with jQuery

How would I go about removing the first character from this.className in the below line?
The first variable will be _ and then a number. I just want the number to be assigned to className.
className = this.className;
Furthermore I am changing "$('.inter').html(window[link[className]]);" to use an array instead of the className variable. Is the below code the correct way to use an array with the index as a variable?
$('.inter').html(window[link[className]]);
No need to use jQuery for that, just plain ol' javascript using .substring
var trimmed = this.className.substring(1);

jQuery .text() returned string isn't behaving like string

I am working in a backbone.js in coffeescript and I am trying to select a model out of a collection using the 'where' function. I am passing in a string variable as the second argument and the string is assigned by the return of a jQuery .text() function on a span element.
I do get a string out of the .text() function, but it isn't behaving like a normal string. I can only use a variable as a where() argument if I assign it manually.
Edit: I changed $('e.target') to $(e.target), turns out that what I actually have in my gist. I just mis-typed it in summarizing my question. You can see below what return values I am getting on the right.
value = $(e.target).text() # value => 'target text'
value.charAt(0) # =>*nothing at all!*
value = "manually assigned text" # value => 'manually assigned text'
value.charAt(0) # =>* 'm'
Here's my snippet for further inspection: https://gist.github.com/4215344
Try this instead:
value = $(e.target).text();
no quotes around e.target.
The problem is not .text(), it's your selector; 'e.target' is not a valid selector. You probably meant to do:
value = $(e.target).text();
As is, calling .text() on an empty object returns blank.
By removing the quotes, you are actually referencing the target property of the event object, which corresponds to an element directly. What you had before was a selector string for <e> elements with class='target', which is obviously not what you want.
Turns out that inspecting value.length was the key. It was something like 36 characters for some reason. I tried in my haml template to call .strip on the variable there, but the extra whitespace wasn't coming from the ruby side.
I just ended up using jQuery's .trim() function.
Here's my new assignment:
fontName = $(e.target).text().trim()

Pass multiple values with onClick in HTML link

Hi Im trying to pass multiple values with the HTML onclick function. Im using Javascript to create the Table
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
But in my Javascript function the userName is undefined and the valuationId is a string with the valuationId and the UserName combined
function ReAssign(valautionId, userName) {
valautionId;
userName;
}
If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
Re-Assign
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo 'Re-Assign';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
Solution: Pass multiple arguments with onclick for html generated in JS
For html generated in JS , do as below (we are using single quote as
string wrapper).
Each argument has to wrapped in a single quote else
all of yours argument will be considered as a single argument like
functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument
with single quote, give a separator comma in between and then start next argument with a
single quote. (This is the magic code to use '\',\'')
Example:
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}
Please try this
for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"
That is because you pass string to the function. Just remove quotes and pass real values:
Re-Assign
Guess the ReAssign function should return true or false.
A few things here...
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.
Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.
Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...
Re-Assign
There are a few extra things to note here, if you want more than a quick solution.
You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).
Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:
.runjs {
cursor: pointer;
text-decoration: underline;
color: blue;
}
This lets you leave out the href attribute which you weren't using anyways.
Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...
var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
links[i].onclick = function() { ReAssign('valuationId', window.user); };
While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.
function ReAssign(valautionId, userName) {
var valautionId
var userName
alert(valautionId);
alert(userName);
}
Re-Assign

Using a variable when traversing elements in JQuery

Very quick and hopefully simple question.
I am trying to select a hidden input by value with some predefined variable.
var id = $("#puid").val();
$('input[value=id]').closest('tr').css({'background-color':'red'});
I thought the above code would have worked, however its not processing id as a variable. What is the right notation to do this? (I have tested the code by replacing id with the actual number and the rest of the code works fine).
remove it from the quotes, so the variable is concatenated into the string. They way you have it, it's looking for the literal value "id", and has no way of knowing that you're talking about a variable.
$('input[value='+id+']')
edit: more info - you could put double quotes around the id part, inside the strings, as in Nick's answer, which would make it safe to use with non-numeric ids. I omitted them since your example doesn't need them, as you said your ids are numeric.
Concatenate the string selector with the variable, like this:
var id = $("#puid").val();
$('input[value="' + id + '"]').closest('tr').css({'background-color':'red'});
Currently, it's looking exactly for this: value="id", but you want your variable there.

Javascript confusion

var allRapidSpells = $$('input[value^=RSW]');
Can anyone tell me what that does?
I would venture to guess that you're using MooTools, a JavaScript framework. The $$() function is used to select an element (or multiple elements) in the DOM.
More specifically, the $$('input[value^=RSW]'); syntax is selecting all input elements whose value attribute starts with RSW.
Other attribute selectors include:
= : is equal to
*= : contains
^= : starts-with
$= : ends-with
!= : is not equal to
~= : contained in a space separated list
|= : contained in a '-' separated list
Edit: It looks as though Prototype, another JavaScript framework, uses the same syntax.
Return all inputs that hava value starting with RSW
It calls the function named '$$' with the parameter 'input[value...' and assigns the returnvalue of that function to the var allRapidSpells.
Javascript doesn't consider the '$' to be a reserved character, which jQuery makes excellent use of.
It looks like it uses some CSS selectors using some javascript library, the CSS selectors return all input tags where the value begins RSW.
calls a method on the windows object called $$ and passes a string argument to it, which appears to be an xpath expression.
which returns input tags that contain an attribute called value starting with RSW.

Categories

Resources