setting innerHTML for all browsers in javascript - javascript

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.

Related

Is it possible to pass variables to jquery's css function?

I'd like to set css of a div element dynamically using jQuery css() function instead of using string literals/ string constants for the css() function. Is it possible?
Instead of using the following codes with string literals:
$('#myDiv').css('color', '#00ff00');
I would like to use variables to set css for #myDiv element like
Version 1:
var propertyName = get_propery_name(myVariable1); // function get_propery_name() returns a string like 'background-color'
var value = get_value(myVariable2) ; // function get_value() returns a string like '#00ff00'
$('#myDiv').css(propertyName, value);
Version 2: (just hard coded to see if they work without calling custom functions like version 1 above):
var propertyName = 'background-color';
var value = '#00ff00';
$('#divLeftReportView').css(propertyName, value);
Both variable versions of codes do not work. Please help. Thanks.
Both of your examples will work just fine. I would suggest just a bit cleaner approach (personal syntax preference):
$(document).ready(function () {
$('#myDiv').css(get_propery_name(myVariable1), get_value(myVariable2));
}
Here's a working fiddle.
If you want to take it a step further, you can return a CSS map instead of strings:
$('#divLeftReportView').css(GetCssMap("foo"));
function GetCssMap(mapIdentifier) {
return { "background-color" : "#00ff00" }
}
Here's a working fiddle.
The code you posted here should work. I have done both versions of what you are trying to do several times. If it is not working, there is a good chance that something is wrong somewhere else in your javascript OR that you do not have the correct selector/id for the element(s) which you want to change.
Try adding alert("test"); immediately after $('#divLeftReportView').css(propertyName, value);. If you get the popup saying "test" then the problem is with your selector. If not, then the problem is a bug in your javascript.
Also try adding $('#divLeftReportView').css("background-color", "#00ff00"); in the same place. That will confirm whether or not the selector is working.
Seems to work fine at http://jsfiddle.net/gaby/6wHtW/
Make sure you run your code after the DOM ready event..
$(function(){
var propertyName = 'background-color';
var value = '#00ff00';
$('#divLeftReportView').css(propertyName, value);
});
otherwise your elements might not be present in the DOM..
You can also pass multiple CSS parameters within one variable as an array:
$(function(){
var divStyle = {'background-color': '#00ff00', 'color': '#000000'}
$('#divID').css(divStyle);
});
yes, using jQuery attr method you can change css dynamically
var height=$(".sampleClass1").innerHeight();
$('.sammpleClass2').attr('style', 'min-height:'+height+' !important');

How do I test if an element with a certain ID exists on a page in jQuery?

In jQuery, I have written a piece of code that appears on every page of my website.
var d = $('#someElement').offset().top;
However, not every page on my website has an element with an ID of "someElement". Unfortunately, on these pages that lack such an element, no jQuery code works.
To solve this problem, I want to test if an element on the page indeed has the ID of "someElement" and then only run the code snippet above if there is.
How do I perform this test? Will this test solve the problem? Thank you.
$('#someElement').length will return 1 if the element exists, 0otherwise.
Check the length of the jQuery object.
var element = $('#someElement');
if (element.length) {
var element_top = element.offset().top;
}
try this:
if($('#someElement').length>0){
var d = $('#someElement').offset().top;
}
Use if statemtent: if ($('#someElement').length) { do something }
Just an alternative way of solving it: You can run var d = $('#someElement').offset() without causing an error (it will just return null), even if the element does not exist. So try:
var d = $('#someElement').offset();
if (d) {
d = d.top;
}
Do not use jQuery for that! Use getElementById, since if the element is not in the DOM, the result will be null.
if (document.getElementById("someElement")) {
}

jquery / javascript - Simple split() problem

if ($(".productpage .description").html() != null) {
var textToHide = $('.productpage .description').html().split('<br class="breakHere">')[1];
var visibleText = $('.productpage .description').html().split('<br class="breakHere">')[0];
}
Works great in Firefox, but in IE and Chrome textToHide and visibleText are undefined. Did I miss something? Thanks
View your $('.productpage .description').html(), you may be getting <br />
Using split() against HTML isn't a good idea IMHO - it's too brittle, and is likely to suffer the same problems as using Regexp's against HTML.
Assuming that the elements you're trying to split are all siblings with the <br> element, try this:
var $el = $('.productionpage .description'); // find the element
var $br = $('br.breakHere', $el); // find the BR inside it
var $vis = $br.prevAll(); // contains everything before the break
var $hide = $br.nextAll(); // contains everything after the break
Note that this will give you jQuery objects containing those elements, not the HTML text of them.

How to get value of JavaScript into HTML span?

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

HTMLInputElement has no method 'val'

I'm looping through cells in a table row. each cell has a text box in it, and I want to take the value of the text box and push it onto an array.
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $(this).children('input')[0].val();
submitvals.push(val);
});
}
Theres more to the function, but this is all that is relevant. For some reason, when I run this code, I get "HTMLInputElement has no method 'val'." I thought that input elements were supposed to have a val() method in jQuery that got the value so this makes no sense. Am I missing something, or doing it wrong?
val() is a jQuery method. .value is the DOM Element's property. Use [0].value or .eq(0).val()....
.val() is a jQuery function, not a javascript function. Therefore, change:
var val = $(this).children('input')[0].val()
To:
var val = $(this).children('input:eq(0)').val()
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $($(this).children('input')[0]).val();
submitvals.push(val);
});
}
.val() is a jquery method. Using [0] returns the DOM element, not the jquery element
var val = $(this).children('input:first').val();
What I don't understand, is why none of the suggested syntaxes on this or other questions similar to this seem to work for me. I had to do trial and error and eventually had to use:
MySelectElement.value = x;
It also didn't help that the Visual Studio Intellisense suggestions offer a whole other range of unworking method names, such as ValueOf().

Categories

Resources