My DOM skills are weak and I can't work out why a javascript variable is assigned this object pointer value rather than the string value itself.
Short story is that I am making an AJAX call for some screen data and it returns html and populates a div.innerHTML with the following :
<input id="page_tag_add_input"></input>';
<span class="page_tag_add">Add</span>
The doTagXhr function is a YUI connection manager AJAX call.
When the user clicks add, firebug shows me that the newTag variable is stored as "[object HTMLDivElement]", yet when the alert(newTag) javascript kicks in (above), it shows the value correctly as the input text string?? I've exhausted Google searches :-(
Are there any gurus out there that can point me in the right direction? Thanks.
You're assigning newTag to a DOM Element property. I think you've mistaken what Firebug reports it as, that code indicates it's clearly not an element reference, and unless you're manipulating it in the xhr function ( which you didn't paste the code to ) then it's still a string.
Edit:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function doTagXhr(page, input) {
window.input = input;
$.ajax({
url:page,
type:'POST',
data:input
});
}
</script>
<input id="page_tag_add_input" value="test">
<span class="page_tag_add">Add</span>
This always stays a string. I don't know what else it could be other than your xhr function that's reassigning the variable.
Related
I've got a script in good working order that checks to see if a visitor has been assigned a coupon code but wanted to add functionality that retrieves the coupon code that they were assigned and displays it. Both rely on the localStorage property. The problem I'm running into is that when I display the stored value, it's returning [object HTMLSpanElement] instead of the value that should be assigned.
Pretty much everything I've found on the issue is due to scope, but I don't see how I have a scope issue...even tried making the variables global in scope and that didn't seem to do anything.
Here is the JS:
if(localStorage.getItem("visited") != "true"){
localStorage.setItem("visited","true");
var codeValue = document.getElementById("code");
localStorage.setItem("code",codeValue);
}
else {
var savedCode = localStorage.getItem("code");
document.getElementById("message").innerHTML = "You've already been assigned coupon code " + savedCode;
}
Here is the relevant HTML:
<span id="message">Your coupon code is: <span id="code">CODE1234</span></span>
When you return to the page after already visiting it, I expect the span text to display You've already been assigned coupon code CODE1234, but instead it is returning You've already been assigned coupon code [object HTMLSpanElement]
Note that part of the script was something I had created before and put in production, and I'm basically piggybacking off of that functionality. Previously, if getItem("visited") != "true" returned false, it popped up an alert box and said you'd already been given a code, then redirected you to another page.
You are storing the element itself (which is an object) in the localStorage. You should store the text of the element.
Change
var codeValue = document.getElementById("code");
To
var codeValue = document.getElementById("code").textContent;
Please Note: According to Window.localStorage
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
you need to access the text inside the element, here you are storing the html element inside the localstorage.
change the code to access the text
document.getElementById('code').innerText
I have a variable that I want saved so that multiple functions can use it. I followed w3schools's directions but it doesn't work. Am I forgetting something? Thank you in advance.
var name = document.getElementById('name').value;
function complete() {
document.getElementById('demo').innerHTML = name;
}
There are a few things to consider:
If you have code that attempts to find an element, but that element hasn't even been read by the browser yet, the browser won't be able to find it. So, make sure that your code only runs AFTER the full DOM has been loaded
by placing the script just before the closing body tag.
Don't attempt to get the value of a form field as soon as the page
loads because the user hasn't typed anything into it yet, so the
value will be nothing. You need to set up your code so that your function gets called at the right time (after the user has had a chance to type in the form field) so only get the value when that moment has come.
Don't give any element the name name because the Global window
object has a property called name that defaults to an empty string
and when you attempt to access name, it could incorrectly attempt
to get the window.name instead of your element called name.
Only form fields have a value property. All other elements have
.textContent (used when the string does not contain any HTML or you
want the actual HTML code displayed, rather than parsed) and
.innerHTML (used when the string does contain HTML and you want
that code parsed).
Lastly, do yourself a favor and don't use W3Schools. It is well known to have outdated or flat out wrong information on it. Instead use the Mozilla Developer's Network, which is recognized as one of the best resources for client-side web development documentation.
<input type="text" id="userName">
<input type="button" value="Click Me!" id="btn">
<div id="demo"></div>
<script>
// Set up the button's click event handling function
document.getElementById("btn").addEventListener("click", complete);
// Only get a reference to the element, not its value because, at this point,
// the user hasn't had a chance to type anything into it.
// Also, getting a reference to the element is the best approach because, if
// you decide you want some other property of the same element later, you'd have
// to scan the document for the same element again.
var theName = document.getElementById('userName');
function complete() {
// Now, just get the current value of the textbox at this moment in time
document.getElementById('demo').textContent = theName.value;
}
</script>
EDIT: This question is not a duplicate, I am aware that at this point foo has not been inserted into the DOM. My question is whether or not is is possible to access the elements declared in the string assigned to foo without inserting it into the document object.
In the following code, we declare an HTML element as a JavaScript variable.
<script>
var foo = "<td id = 'bar'>";
</script>
Now, after the <script> tag but before the </script> tag, how do I access the value of id in the table cell?
Eg. calling console.log(foo.id) obviously prints undefined.
how could I call the console.log() function (or any other function to access the value of id) to give us the correct value, "bar"?
Im using <td> as an example but I assume this applies to any html tag declared with JS.
In your case you'd get what's between the first and second ', which coincidentally happens to be the id by doing:
foo.split("'")[1] // -> bar
However that is not too useful or reusable. You could push an element to memory and set the innerHTML of that node to your string, however the string in your example is not valid HTML, so it would not work.
var temp = document.createElement('html')
temp.innerHTML = str
temp.getElementsByTagName('td')[0].id // -> bar
Can't imagine your use case though, so maybe none are perfect.
<script>
function myFunction() {
var name = "some_string";
var display = "{{ python_function(name) }}";
alert(display);
}
</script>
Above Javascript is writen in jinja2 template. It is supposed to pass javascript variable (i.e. var name) value to python function in macro. I know above code won't solve my purpose as I am not passing javascript variable value correctly to macro. Does anybody have method on passing javascript variable to macro in jinja2 template?
You cannot pass values from javascript to the template that way because the template is going to be rendered before the response goes back to the browser for the javascript engine to evaluate. The only way the template renderer would be able to resolve the value of name specified in the javascript code would be to interpret the string embedded in <script></script>.
Update. Let's look at your second attempt, the one that you say has worked. You have:
<body>
<button onclick="js_fn('{{ py_fn('some_string') }}')">Click me</button>
<script>
function js_fn(variable) {
alert(variable);
}
</script>
</body>
Presumably this is in some partial (say _index.html). A view that has py_fn in scope, loads _index.html, evaluates the string "py_fn('some_string')", and replaces {{ py_fn('some_string') }} with the result of that evaluation. Let's say py_fn is the identity function on strings: it's a unary function that takes a string and immediately returns it. Then, the result of evaluating "py_fn('some_string')" will be the string 'some_string', which will be substituted back, obtaining the final, so-called "rendered" template:
<body>
<button onclick="js_fn('some_string')">Click me</button>
<script>
function js_fn(variable) {
alert(variable);
}
</script>
</body>
This string will be part of the response body of the request, so the browser will dump the button on the window, evaluate the js code inside the script block, which will create a global variable js_fn on the window, which will take something and alert it. The button, when clicked on, will call js_fn with the constant some_string, always. As you can see, there is no passing of values from JS to Python/Flask.
I am trying to pass a variable in javascript. I create a link in the following manner and everything seems to be working.
label.innerHTML = ' link';
However when I create the link in the following way where the link would also pass an associated object I get the following error from firebug -> "missing ] after element list"
label.innerHTML = ' link';
Is this an acceptable way to pass an object to a function. The problem is that I am creating this link within a function. The function creates links like this based upon an object that is passed to it. Therefore I cannot have this "object" as a global scope.
You are building the script by mashing together strings, as such you can only work with strings and object will be automatically stringified.
Use DOM instead.
var link = document.createElement('a');
link.href = "#"; // Have a more sensible fall back for status bar readers and middle clickers
link.appendChild(document.createTextNode(' link');
link.addEventListener('click',function () { show_box(this, object); },false);
label.appendChild(link);
… but use a library that abstracts away the non-standard event models that some browsers have.
What you're trying to do is pass the contents of object to output. Since it's an object, the string representation will be something like [object Object]. The output HTML would look like:
link
which is invalid. Don't try to concatenate the object, just pass it along as another argument to the function, like this. Or, better yet, use jQuery:
<!-- somewhere in the head, or at least after the object is defined -->
<script type="text/javascript">
$(function() {
$('#thelink').click(function() { show_box(this, object); });
});
</script>
...
link
If your object is simple variable like numeric or string variable than it will be Ok but if you are passing html object it will not work because it will be something like below.
link