If I have a much simplified JavaScript method such as this:
function myfunction() {
var i = 9;
}
Is there any way I can get the value of i into HTML such that when the web page with this method is called, the value 9 is displayed in a div or span element?
You can write document.getElementById("some ID").innerHTML = i
Hi :D you can try the following using JQuery:
var i = 9;
$('#spanId').text(i);
or the classic old-fashion way:
var tmp= document.getElementById('spanId');
tmp.textContent = id;
I hope this helps.
You can use innerHTML to embed the i value in a div or span element.
myfunction() current does not return its value. However, if you want to get the value when the page is "called" (loaded) you can do this:
function myfunction() {
var i = 9;
return i;
}
And in the markup:
<body onload="document.getElementById('id_of_your_div').innerHTML = myfunction()">
Please note that innerHTML has cross-browser issues, so you may want to use a library function such as jQuery's html() for reliable results.
Yes, you can assign an id to your <div> or <span> and set its innerText/textContent property to your value.
window.onload = function() {
var content = myfunction();
var tag = document.getElementById('displayVar');
if(typeof tag.innerText == "undefined") {
tag.textContent = content;
} else {
tag.innerText = content;
}
}
Do not use innerHTML if you do not want the HTML code of your value to be parsed (or if you don't expect any HTML value).
And no, you do not need a 31kb library to do that kind of work (just in case there's a bunch of "jQuery can do that!" answers).
Note that you must also modify myfunction() so that it returns the current value. A simple return i; statement in the function will do the trick.
JavaScript:
function myFunction() {
var i = 9;
return i;
}
$('myElement').innerHTML = myFunction();
HTML:
<span id="myElement"></span>
you can also use jQuery to simplify the syntax following are the three ways you can do that using jQuery,
1) $('span').text(i)
2) $('#someid').text(i) //someid = value of id attribute of span tag.
3) $('.someclassname').text(i) //someclassname = class name for the span tag.
Also using jQuery means forcing the users have to download addition jQuery lib when the page loads. That might slow down the page depending on the connection speed of the users. You might want to consider that while selecting between jQuery and plain JavaScript
Related
I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.
if (this.ButtonColor != "") {
var button = document.getElementbyId('modal-close');
button.style.backgroundColor = this.ButtonColor;
}
The function is document.getElementById(), not document.getElementbyId()
It is simply a typo, the function you are looking for is getElementById.
By with a capital B instead of by.
here is a reference to that method.
Instead of using this.ButtonColor did you try
var button = document.getElementById("modal-close");
button.style.backgroundColor = "the color you want rather than using "
i tried to search throught the html code for an element named scope using javascript. After that it should show a alertbox with the value of this element.
if($('[name=scope]').length > 0){
var scope = $(this).value();
alert(scope);
}
But that doesn't work for me. What can i do to fix this?
Thanks!
You need val() instead of value(), there is not value function in jQuery
var scope = $(this).val();
Or simply use this.value, that would be simple and faster
var scope = this.value;
Edit based on comments
$('[name=scope]').each(function(){
alert(this.value);
});
I'm building an HTML page that receives data from another page with the below code
$arrayPosition = $_POST['arrayPosition'];
echo '<span id = "arrayPosition">'.$arrayPosition.'</span>';
I'm then trying to use javascript to get the value of the element and pass it to a function with the below code
var initialPosition = document.getElementById('arrayPosition').value;
function displayWork(position){
$("#displayArtwork").detach()
.append(holdImages[position])
.hide()
.fadeIn("fast");
}
When I alert the value of initial position to the screen it informs me that null is its value, however, when I inspect the element it looks like this
<span id="arrayPosition">4</span>
Am I making some really stupid error, or misunderstanding the way to access this posted data?
Thanks for your help!
Since arrayPosition is a span, it has no value. You can get its innerHTML:
var initialPosition = document.getElementById('arrayPosition').innerHTML;
Or using jQuery:
var initialPosition = $('#arrayPosition').text();
A span-element has no value. Only form-elements can contain the value-attribute. To get the text inside your span you can use the innerHTML-porperty:
var initialPosition = document.getElementById('arrayPosition').innerHTML;
Demo
As you are already using jQuery you can also use it's text()-function:
var initialPosition = $('#arrayPosition').text();
here you can also use:
$(document.getElementById('arrayPosition')).text();
Harder to maintain and more difficult to read but faster than the jQuery-Selector. (see here)
Demo 2
Reference
.innerHTML
.text()
I have:
$elements = $('.elements');
$element = $('.element');
function appendText(element){
element.append('<em> appended text</em>');
}
appendText($element);
$('button').on('click', function(){
$elements.append('<span class="element">Span Element Appended after load</span>');
appendText($element);
});
The appendText function, after button click, appends only to the initial element and that is due to JS cache I presume.
I know that I can do appendText($('element')); and the problem will be solved, but I don't want to change all my code now.
Is there any way to make jQuery consider this $element variable as not a cached element and look into the full DOM each time I call that variable?
Please find the jsfiddle if you wish to play or understand better: http://jsfiddle.net/adyz/733Xd/
If you add this:
$element = $('.element:last-child')
before
appendText($element);
I think will solve your problem
jsFindle here: http://jsfiddle.net/733Xd/5/.
Best regards!
That is an expensive thing to do. I would advise against it for performance reasons.
I did this pluggin in the beggining of last year https://github.com/fmsf/jQuery-obj-update
It doesn't trigger on every call, you have to request the update yourself:
$element.update();
The code is small enough to be pasted on the answer:
(function ( $ ) {
$.fn.update = function(){
var newElements = $(this.selector),i;
for(i=0;i<newElements.length;i++){
this[i] = newElements[i];
}
for(;i<this.length;i++){
this[i] = undefined;
}
this.length = newElements.length;
return this;
};
})(jQuery);
I think below one will solve your problem
appendText($element); //here you always referring to the node which was there initial.
http://jsfiddle.net/s9udJ/
Possible Solution will be
$(function(){
$elements = $('.elements');
$element = $('.element');
function appendText(element){
element.append('<em> appended text</em>');
}
appendText($element);
$('button').on('click', function(){
$elements.append('<span class="element">Span Element Appended after load</span>');
appendText($elements.find('span').last());
});
})
I don't think what you're asking is easily possible - when you call $element = $('.element'); you define a variable which equals to set of objects (well, one object). When calling appendText($element); you're operating on that object. It's not a cache - it's just how JS (and other programming languages) works.
The only solution I can see is to have a function that will update the variable, every time jquery calls one of its DOM manipulation methods, along the lines of this:
<div class='a'></div>
$(document).ready(function()
{
var element = $('.a');
$.fn.appendUpdate = function(elem)
{
// ugly because this is an object
// also - not really taking account of multiple objects that are added here
// just making an example
if ($(elem).is(this.selector))
{
this[this.length] = $(this).append(elem).get(0);
this.length++;
}
return this;
}
element.appendUpdate("<div class='a'></div>");
console.log(element);
});
Then you can use sub() to roll out your own version of append = the above. This way your variables would be up to date, and you wouldn't really need to change your code. I also need to say that I shudder about the thing I've written (please, please, don't use it).
Fiddle
I want to load contents of a DIV dynamically in javascript.I used this code
var strHtml="<h3>Test</h3>";
var div = $("#divPrice");
div.innerHTML=strHtml
This works in IE. But not in firefox.Whats the alternative of this which works on all browsers ?
Try it this way:
var strHtml="<h3>Test</h3>";
$("#divPrice").html(strHtml);
It looks like you are using jquery, so you can use:
var strHtml="<h3>Test</h3>";
var div = $("#divPrice");
div.html(strHtml);
I take it you're using a JavaScript Framework based on $(). Looking at your other questions, it looks like you're using jQuery, in which case you can do
$("#divPrice").html(strHtml);
Just for reference, jQuery's html() command does the following
jQuery.fn = jQuery.prototype = {
html: function( value ) {
return value === undefined ?
(this[0] ?
this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
null) :
this.empty().append( value );
}
}
I assume you use pure javascript, not jquery.
var div = $("#divPrice");
should be
var div = document.getElementById("divPrice");
Others are fine.