Setting the onClick property dynamically - javascript

I am trying to set the onClick property of a dynamically generated div in a loop but the code below is not working beyond generating the divs. Can someone please help me out?
<script type="text/javascript">
function gengrid()
{
var i=0;
var num_stud=8;
var newdiv;
var divIdName;
var maindiv;
for(i=1;i<=num_stud;i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.onClick= function(){addit(i);};
newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
maindiv=document.getElementById('main');
maindiv.appendChild(newdiv);
}
}
gengrid();
function addit(picno)
{
alert(picno+'');
}
</script>

The onclick method should have a lowercase c.
See this fiddle: http://jsfiddle.net/MTpUV/
<script type="text/javascript">
function gengrid()
{
var i=0;
var num_stud=8;
var newdiv;
var divIdName;
var maindiv;
for(i=1;i<=num_stud;i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.onclick= function(){addit(i);};
newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
maindiv=document.getElementById('main');
maindiv.appendChild(newdiv);
}
}
gengrid();
function addit(picno)
{
alert(picno+'');
}
</script>

Related

focus is not working on textarea

I am creating a page in which a user can add a question and its solution, he can delete the problem and can also edit it dynamically using DOM in javascript. I want that whenever user clicks on edit button the textbox which appears get autofocus.
This the javascript code of my page...
var questionText;
var answerText;
var questionArray=[];
var answerArray=[];
var i=0;
var j=10000;
function addProblem(){
var body = document.getElementsByTagName('body')[0];
questionText = document.getElementById('questionId').value;
answerText = document.getElementById('answerId').value;
questionArray.unshift(questionText);
answerArray.unshift(answerText);
var myContainer = document.getElementById('container');
var myDiv = document.createElement("div");
var questionLogo = document.createElement("p");
questionLogo.id = "questionLogo";
var textNode = document.createTextNode("Question:");
var question = document.createElement("p");
question.id = "question";
var questionDetail = document.createTextNode(questionArray[0]);
var deleteButton = document.createElement("button");
deleteButton.innerHTML = "Delete";
deleteButton.id = i;
var editButton = document.createElement("button");
editButton.innerHTML = "Edit";
editButton.id = j;
var answerLogo = document.createElement("p");
answerLogo.id = "answerLogo"
var ansTextNode = document.createTextNode("Answer: ");
var answer = document.createElement("p");
answer.id = "answer";
var answerDetail = document.createTextNode(answerArray[0]);
var mybr = document.createElement("br");
if(i==0){
myContainer.appendChild(myDiv);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answerLogo.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
else if (i > 0)
{
myContainer.insertBefore(myDiv,myContainer.firstChild);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answer.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
i++;
j++;
myDiv.childNodes[7].addEventListener("click", function(){
var deleteElement = document.getElementById(this.id);
deleteElement.parentNode.parentNode.removeChild(deleteElement.parentNode);
});
myDiv.childNodes[9].addEventListener("click",function(){
var editElement = document.getElementById(this.id);
var quesEdit = editElement.parentNode.childNodes[1];
var quesEditText = quesEdit.innerHTML;
var ansEdit = editElement.parentNode.childNodes[4];
var ansEditText = ansEdit.innerHTML;
var editDiv1 = document.createElement("div");
editDiv1.id = "editDiv1"
var quesTextArea = document.createElement("textarea");
quesTextArea.innerHTML += quesEditText;
quesTextArea.focus();
var saveButton1 = document.createElement("button");
saveButton1.innerHTML = "Save";
editDiv1.appendChild(quesTextArea);
editDiv1.innerHTML += ' ';
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
var editDiv2 = document.createElement("div");
editDiv2.id = "editDiv2"
var ansTextArea = document.createElement("textarea");
ansTextArea.innerHTML += ansEditText;
var saveButton2 = document.createElement("button");
saveButton2.innerHTML = "Save";
editDiv2.appendChild(ansTextArea);
editDiv2.innerHTML += ' ';
editDiv2.appendChild(saveButton2);
ansEdit.parentNode.replaceChild(editDiv2,ansEdit);
});
}
I have tried to focus the textarea using
quesTextArea.focus();
but its not working where questextArea is the name of the textarea. Please help how i can do it.
For the element could be got focused, it must be in the DOM when you invoke focus on it. You should invoke focus function after replaceChild function
editDiv1.appendChild(quesTextArea);
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
quesTextArea.focus();
I've created a simple sample as below link, you could check it
https://jsfiddle.net/pd9c6c7a/3/
Add autofocus attribute to the textarea element. So that whenever it is appended to the DOM, will get cursor activated in it.
The 'textarea' has not been added to window to be shown, an element must be part of the document object tree. In case that didn't work, add a 50ms delay.
setTimeout(function(){e.focus();}, 50);
Try the following approach:
var body=document.getElementsByTagName('body')[0];
var quesTextArea=document.createElement("textarea");
var button=document.createElement("button");
button.innerHTML = "click Me";
button.addEventListener("click",function(e){
e.preventDefault();
quesTextArea.focus();
});
body.appendChild(quesTextArea);
body.appendChild(button);
<html>
<body>
<body>
</html>
Try to add preventDefault.
var div = document.getElementById('parent');
var txt = document.createElement('textarea');
div.appendChild(txt);
txt.focus();
<html>
<head></head>
<body>
<div id="parent">
<input type="text" value="" />
</div>
</body>
</html>
The element must be in the DOM when you invoke the focus function. Move your focus() function after the appendChild() is invoked.
quesTextArea.innerHTML += quesEditText;
var saveButton1=document.createElement("button");
saveButton1.innerHTML="Save";
editDiv1.appendChild(quesTextArea);
quesTextArea.focus();

Document write cause design flaw

I write a slider function. And base on value of slider function i print some messages in my document . When i use DW inside a slider after changing the value of the slider that messages are printed without style. How can i fix it?
$(function() {
$( "#slider-5" ).slider({
range:true,
min: parseInt(ctime[0]),
max: parseInt(ctime[ctime.length-1]),
values: [ parseInt(ctime[4]),parseInt(ctime[len])],
change: function( event, ui ) {
$( "#slidevalue" )
.val( "$" + formatDateTime(ui.values[ 0 ]) + " - $" + formatDateTime(ui.values[ 1 ]) );
new_var=ui.values[0];
document.write('<section id="cd-timeline" class="cd-container">')
var ctime = <?php echo json_encode($tweettimes); ?>;
for(var x=0; x<10; x++){
var datum = new Date(parseInt(ctime[x]));
document.write('<div class="cd-timeline-block">')
document.write('<div class="cd-timeline-img cd-location">')
document.write('<img src="img/cd-icon-location.svg" alt="Location">')
document.write('</div>')
document.write('<div class="cd-timeline-content">')
document.write('<h2>'+(x+1)+'</h2>')
document.write('<p>'+<?php echo json_encode($content); ?>[x]+'</p>')
document.write('<span class="cd-date">'+formatDateTime(datum)+'</span>')
document.write('</div>')
document.write('</div>')}
document.write('</section>')
}
});
});
Please don't use document.write. Use document.createElement() instead.
var body = document.getElementsByTagName('body')[0];
var section = document.createElement('section');
section.id = 'cd-timeline';
section.className = 'cd-container';
body.appendChild(section);
for (var x = 0; x < 10; x++) {
var datum = new Date(parseInt(ctime[x]));
var outerDiv = document.createElement('div');
outerDiv.className = 'cd-timeline-block';
section.appendChild(outerDiv);
var div = document.createElement('div');
div.className = 'cd-timeline-img cd-location';
outerDiv.appendChild(div);
var img = document.createElement('img');
img.src = 'img/cd-icon-location.svg';
img.setAttribute('alt', 'Location');
div.appendChild(img);
var div = document.createElement('div');
div.className = 'cd-timeline-content';
outerDiv.appendChild(div);
var h2 = document.createElement('h2');
div.appendChild(h2);
h2_text = document.createTextNode('foo');
h2.appendChild(h2_text);
var p = document.createElement('p');
div.appendChild(p);
p_text = document.createTextNode('bar');
p.appendChild(p_text);
var span = document.createElement('span');
span.className = 'cd-date';
div.appendChild(span);
span_text = document.createTextNode('foobar');
span.appendChild(span_text);
}
DEMO

Creating dynamic div using javascript

<script>
function selecteditems()
{
var i=1;
var val="";
while(i<=53)
{
if(document.getElementById('timedrpact'+i)!="")
{
val+=document.getElementById('timedrpact'+i).value;
document.getElementById('showselecteditems').innerHTML=val;
}
i++;
}
}
</script>
How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it.
Thanks in advance.
Check this Demo
<div id="output" class="out">
</div>
window.onload=function(){
var output = document.getElementById('output');
var i=1;
var val="";
while(i<=3)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
i++;
}
};
Look at document.createElement() and element.appendChild().
var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);
Because you will likely encounter this in the near future: You can remove any element with this code:
element.parentNode.removeChild(element);
Using createElement:
function selecteditems() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=53;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(fld.value));
container.appendChild(div);
}
}
}
Full version using cloneNode (faster) and eventBubbling
Live Demo
var div = document.createElement("div");
var lnk = document.createElement("a");
var img = document.createElement("img")
img.className="remove";
img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png";
lnk.appendChild(img);
div.appendChild(lnk);
function getInputs() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=5;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var newDiv = div.cloneNode(true);
newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value));
container.appendChild(newDiv);
}
}
}
window.onload=function() {
document.getElementById('showselecteditems').onclick = function(e) {
e=e||event;
var target = e.target||e.srcElement;
// target is the element that has been clicked
if (target && target.className=='remove') {
parentDiv = target.parentNode.parentNode;
parentDiv.parentNode.removeChild(parentDiv);
return false; // stop event from bubbling elsewhere
}
}
getInputs();
}
Syntax for dynamic create div:
DivId = document.createElement('div');
DivId.innerHtml ="text"

Give a box an ID, once clicked shows alert of that ID?

The idea is when the button is clicked it will generate as many boxes as there are clicks (ex: 20 clicks = 20 boxes on the page) However, I need it where when you click on the box an alert of a unique ID pops up. I'm not sure of how to assign each box a unique ID...
Here is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>E02W03_Q2</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="E03_Q2.css">
<script src="E03_Q2.js"></script>
</head>
<body>
<form>
<input type="button" id="addButton" value="Add Box">
</form>
<div class="clrBox">
</div>
</body>
</html>
The CSS code:
.clrBox {
background-color: red;
width: 50px;
height: 50px;
margin: 10px;
}
The JavaScript code:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
var box = document.getElementByTagName("div");
button.onclick = handleButtonClick;
box.onclick = handelBoxClick;
}
function handleButtonClick(e) {
var div = document.createElement("div");
div.setAttribute("class","clrBox");
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
function handelBoxClick(e){ <<This isnt quite finished yet since i'm not sure of how to assign each box a unique id...
var div = document.getElementById("");
alert();
}
this should do it:
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
var i=0;
function handleButtonClick() {
i++;
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.setAttribute("id","box"+i);
div.onclick=function(){handleBoxClick(div);}
var body = document.getElementsByTagName("body");
body[0].appendChild(div);
}
http://jsfiddle.net/kBMeJ/
If I understand your question, this is what you need to do. In handleButtonClick:
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.id = "some_id"; // probably something auto-generated, remember that it needs to be unique!
Pretty simple.
Try
var count = document.getElementsByTagName('div').length;
div.id = 'b' + (count + 1);
You could use the length property of the container to assign an incremented id to each div.
function handleButtonClick(e) {
var container = document.getElementsByClassName("clrBox")[0];
var div = document.createElement("div");
// Increment id
div.id = "box-" + container.getElementsByTagName("div").length;
container.appendChild(div);
}
http://jsfiddle.net/pA9QG/
Is that what you were looking for?
run this within your init handler (jsFiddle executes it onLoad):
http://jsfiddle.net/8sWgF/
document.getElementById("addButton").onclick = (function() {
var count = 0;
var addBox = function() {
var div = document.createElement("div");
div.setAttribute("class","clrBox");
div.id = "clrBox" + count++;
div.onclick = function() {
alert(this.id);
}
document.getElementsByTagName("body")[0].appendChild(div);
};
return addBox;
})();
If you use jQuery:
Bind the function to the event:
$(document).on('click', 'input#addButton', addBox);
The function:
function addBox() {
var newId=$('div.clrBox').length + 1;
var $newBox=$('<div id="'+ newId +'"></div>')
.addClass("clrBox")
)
$('body').append($newBox);
}

How to run a nested javascript function?

I am new to object orientated programming in javascript and am trying to understand some functions in a project I am working on.
How would I call/run the internal function (the one listed 'this.getFieldset = function() {') to execute?
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
var fieldset = document.createElement("DIV");
fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
return div;
}
}
var myFieldset = new Fieldset();
myFieldset.getFieldset();
First you should create an instance of Fieldset, then you'll be able to call its functions (called methods):
var myFieldset = new Fieldset();
myFieldset.getFieldset();
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
//var fieldset = document.createElement("DIV");
//fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
window.alert("test");
return div;
}
//add call to run function
this.getFieldset();
}

Categories

Resources