trying to add variable for div id. is it possible? - javascript

i am trying to use variable inside body. just see below sample code
<body>
<div class="demo">
<script>
var count = 4;
for(i=1;i<=count;i++){
var varSlid = "A"+i;
$('.demo').append('<div id= varSlid ></div></br>');
}
</script>
</div>
</body>
but it is throwing errors. please check and tell me where the error is?

Try This
var varSlid = "A"+i;
$('.demo').append('<div id= ' + varSlid + '></div></br>');

The error is that .demo hasn't finished parsing yet, so you shouldn't be attempting to manipulate it. This can cause serious issues in older versions of IE ("operation aborted", anyone?). Move the script to just outside the <div> tag:
<body>
<div class="demo">
</div>
<script>
var count = 4;
for(var i=1;i<=count;i++){
var varSlid = "A"+i;
$('.demo').append('<div id='+varSlid+'></div><br/>');
}
</script>
</body>
As others have pointed out, you also need the quotation marks to work the variable into your HTML string, although this wouldn't have caused any errors - you would just end up with a bunch of elements all with the same id ("varSlid").

Maybe it's my lack of jQuery-fu... but shouldn't </br> be <br/>?
Also, you shouldn't create 4 elements <div id= varSlid > since the id attribute should be unique.
Edit: You probably intended to use the value of the variable varSlid as the id attribute, but rit now it's part of a hardcoded string literal. You'd want to something more like:
$('.demo').append('<div id="'+varSlid+"'></div><br/>');

Try this...
$('.demo').append($('div').attr('id', varSlid)).append('<br/>');
Also wrap this entire function in on dom ready like
$(function(){
//your code here...
});

change: $('.demo').append('<div id= varSlid ></div></br>');
to: $('.demo').append('<div id=' + varSlid + ' ></div></br>');

It's : $('.demo').append('<div id="' + varSlid + '"></div></br>');

I'm not real clear on the OP's original question, but this fits the title.
HTML5 has a data-* attribute, where the * represents your data. I've had luck with this passing Web.py (python) variables from the templator to js functions.
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
<!DOCTYPE html> <!--declare we are using HTML5-->
<html>
<head>
<script>
var jsVersionData = ''; //create a global variable for example simplicity
</script>
</head>
<body>
<div id="stored-variable" data-stored="7">
<script>
jsVersonData = document.getElementById("stored-variable"); //get the variable from the div
</script>
</div>
<script>
var myStr = jsVersonData.dataset.stored; // the variable
var myInt = Number(myStr); // convert the variable to int
alert(myInt + 1);
</script>
</body>
</html>

Related

Get value inside Div Javascript

ho,
I have a div that I access like so:
var gridcellrowvalue0 = gridcell0.innerHTML;
This returns to me the following div:
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
In my JS I would like to accesss the "DefaultText" variable and I have tried this:
gridcellrowvalue0.innerHTML;
gridcellrowvalue0.getAttribute("data-originaltext");
But none of them work. I'm assuming that getAttribute doesn't work because it is not really an element, it's innerhtml.
My goal is to use the "DefaultText" value in an IF-statement and therefore I simply need it.
I appreciate any pointers, my friends!
You could access your element directly from gridcell0 using gridcell0.querySelector('.DivOverflowNoWrap') instead, like :
var gridcell0 = document.querySelector('#x');
console.log( gridcell0.querySelector('.DivOverflowNoWrap').innerHTML );
Snippet:
var gridcell0 = document.querySelector('#x');
if (gridcell0.querySelector('.DivOverflowNoWrap') !== null) {
console.log(gridcell0.querySelector('.DivOverflowNoWrap').innerHTML);
} else {
console.log('Does not exist');
}
<div id="x">
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
</div>
With Javascript also it can be achieved but I am showing here using jQuery
$('document').ready(function() {
var div = $(".DivOverflowNoWrap");
var text = div.text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
The problem is how you access the div in the first place. If you do it like you described (with gridcell0.innerHTML). It will return a string. Not an HTML element.
Therefore you can't use .getAttribute or .innerHTML, because you try to apply it on a string. Access your div differently (querySelector or getElementBy...) and you will be able to use those.
You can use jquery:
$("[class='DivOverflowNoWrap']").text();
$("[class='DivOverflowNoWrap']").attr("data-originaltext")
It's pretty simple:
<html><head></head>
<div class="DivOverflowNoWrap Ellipsis" style="width:100%;" data-textwidth="50" data-originaltext="DefaultText" data-ingrid="1">DefaultText</div>
<script>
test();
function test(){
var x=document.getElementsByClassName("DivOverflowNoWrap Ellipsis")[0].getAttribute("data-originaltext");
alert(x);
}
</script>
</html>

How to use a Javascript var as an ID for a div?

What I have is a function that that generates string that get stored into a javascript var. What I want to do with that the var is assign it to be an id for a div on a page. I've been trying to get the variable set as the div ID but I have some difficulty in doing so.
<script>
var rand = "arandomstring"
</script>
<div id= $(rand) class = "outline">
<b>Some Sample Text</b><br>
</div>
Am I assigning the variable correctly? It seems that this makes the div id = "$(rand)" rather than "arandomstring".
Any help would be appreciated.
The code below will assign the value of the variable "rand" to your div's ID
HTML Code:
<div name="arandomstring" class="outline">
<b>Some Sample Text</b></br>
<div>
Javascript
<script>
var rand = 'some_data';
$(".arandomstring").attr("id", rand);
</script>
You cannot put JavaScript inside most attributes in HTML - only the onevent attributes (e.g. onclick="", onmouseover="") and href="" (with the javascript: URI scheme).
Instead, use an initial id="" value:
<div id="temp" class="outline"><b>some sample text</b></div>
var rand = getNewId();
var div = document.getElementById("temp");
div.setAttribute("id", rand);
Quotes are optional, so id= $(rand) translates to id= "$(rand)".
Also, you don't give Javascript in markup unless it is an event attribute like onclick, etc or href.
You can do
<div class = "outline">
<b>Some Sample Text</b><br>
</div>
<script>
var rand = "arandomstring";
document.querySelector(".outline").id = rand;
alert(document.documentElement.innerHTML);
</script>
From what I see looks like you are using jQuery. Here is how you assign this variable as an id:
<script>
var rand = "arandomstring";
$('.outline').attr('id', rand);
</script>
<div class="outline">
<b>Some Sample Text</b><br>
</div>
Fiddle: https://jsfiddle.net/Smartik/waoecL2a/

How to get label's id?

This is index.html
<html>
<head>
<script language="javascript" type="text/javascript" src="add.js"></script>
<script language="javascript" type="text/javascript" src="get.js"></script>
</head>
<body>
<div id="list">
<form id="programs" name="programs">
</form>
<input type="button" value="add" onClick="add();" />
<input type="button" value="delete" onClick="get();" />
</div>
</body>
</html>
This is add.js
var program_number = 0;
function add()
{
var program_name = "program_sample";
var formID = document.getElementById("programs");
var labelTag = document.createElement("label");
var inputTag = document.createElement("input");
var txtNode = document.createTextNode("program " + program_number);
var brTag = document.createElement("br");
// set input attribute
inputTag.setAttribute("type", "checkbox");
inputTag.setAttribute("name", program_name);
inputTag.setAttribute("value", "program" + program_number);
// set label attribute
labelTag.setAttribute("id", "program_label" + program_number);
labelTag.appendChild(inputTag);
labelTag.appendChild(txtNode);
labelTag.appendChild(brTag);
formID.appendChild(labelTag);
program_number++;
}
This is get.js
function get()
{
var programs = document.programs;
for(var i = 0; i < programs.length; i++)
console.log(programs[i].id);
}
Hello, I want to get the label's id dynamically. add.js code makes it. (below)
<label id="program_label0>
<input type="checkbox" name="program_sample" value="program0" />
program 0<\br>
</label>
If those run normally, the result can be "program_label1", "program_label2", "program_label3" ...
but the result of get.js is just a blank. What should I do to get label's id ..?
or Where my code is wrong ..?
Inside your 'get.js' you could try either
var programs = document.getElementById("programs");
or
var programs = document.forms["programs"];
or
var programs = document.forms[0];
The last one will work only if the form you are referring to is only presented first inside DOM tree.
I see a few problems:
Inputs in the beginning html are outside the form...(Please refer to w3schools form basics)
Instead of inputTag.setAttribute("type", "checkbox");, you should use inputTage.type = "checkbox";
There is no such thing as documents.programs. To access your programs DOM element, please do as in your add.js and document.getElementById("programs");
You do not seem clear on how basics work. - var formID = document.getElementById("programs"); will not return a formID... will return a DOM element. Please read more basic tutorials. Start at - w3schools
First: Why are you using setAttribute over setting the properties?
Second:
var programs = document.getElementById("programs");
More than likely you mean to access window.programs in your code, which only works had that element been in the document when you loaded the page.
When you create an element and add it to the DOM, it does not update the global object (here called window), with that new property name.
You should access form element with `document.programs.elements[i]. So you have missed "elements" which is collection of form elements.

Adding HTML to page based on conditional logic in JavaScript or jQuery

I have a div in which I have to fill some data in. I have to render the HTML based on conditions and I am adding data to that div using jQuery. Can someone please tell me how I can add the condition based insertion of HTML on the page?
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
$('.myDiv').after("<br/>"+data);
}
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
data = data + "<p>The JSVariable is present on page </p>"
}
data = data + "</div>"
$('.myDiv').append("<br/>"+data);
}
function AddData(){
if(typeOf(jsVariable)!=="undefined"){
var data = "<div><h1>My data</h1>";
data += " <p>The JSVariable is present on page </p>";
data += "</div>";
$('.myDiv').after("<br/>"+data);
}
}
this should do the trick, but some element with a class of myDiv will need to already exist for this to work
<div class="myDiv"></div>
What exactly are you trying to do?
If you simply want to add some extra html content depending on the variable, you are almost done. You just need to add the <p> part to the data (data += "<p>...</p>").
If you're trying to add all of the html based on the variable, put the if statement around the $(".myDiv").after (which should be $(".myDiv").append btw).
You'r code is not valid.
Could you explain what do you want to do with
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
If you want to add a html code at ending of a div, you should use
$('.myDiv').append('<p>Text text text text</p>');
simple usage:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("p").click(function() {
var a = $("#div1").text();
if (a == "one") {
$("#div2").text(a);
}
});
});
</script>
</head>
<body>
<div id="div1">one</div>
<div id="div2"></div>
<p>click me</p>
</body>
</html>
function addData(to)
{
var h1 = $('<h1>').text('My Data');
var data = $('<div>').append(h1);
if (window.jsVariable) {
$('<p>').text('JS Variable is present on the page').appendTo(data);
}
to.append(data);
}
addData( $('.myDiv') );
if (condition) {
$('div#yourDivID').html('<p>The JSVariable is present on page </p>');
}
In addition to .html(which places the html inside your div), you can use other things like append, prepend etc. Check out jQuery's documentation on DOM Insertion.
Here is a JSFiddle http://jsfiddle.net/va4n8/
function addData() {
var newDiv = $('<div>');
newDiv.append($('<h1>').html('My data'));
if ('jsVariable' in window) {
newDiv.append($('<p>').html('The JSVariable is present on page'));
}
$('.mydiv').after($('<br>')).after(newDiv);
}

Calculating a number using a textbox

I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks,
Traci
You will want to use the value property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent (or innerText to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.
Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/
In this line, you'll want to set the innerHTML of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p> to be <p>$x.xx</p>.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,
imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.

Categories