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

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);
}

Related

How to make elements added in JavaScript react the same as added in HTML?

I am trying to add new elements in JavaScript, and when I hover my mouse over them I want to see how many letters are in the innerHTML. The function works on elements added in html, but the new ones not.
var input = document.getElementById("input")
var button = document.getElementById("button");
button.onclick = function () {
var p = document.createElement("p");
p.innerHTML = input.value ;
document.body.appendChild(p);
p.id="p";
}
var ar = document.getElementsByTagName("p");
for (var i = 0; i < ar.length; ++i) {
ar[i].title=ar[i].innerHTML.length;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="input"></input>
<button type="button" id="button"> click</button>
<p>p1</p>
<p>p2</p>
</body>
</html>
What I want to achive: number of letters of element I hover on,
What I get: number of letters of elements I hover on, but only these that were added in html.
You could change your click handler like this:
button.onclick = function () {
var p = document.createElement("p");
p.innerHTML = input.value ;
document.body.appendChild(p);
p.id="p";
p.title = input.value.length
}
it would be better to make a new function though, which will perform this code so that you have less code duplication, i.e. I'd rewrite it like this:
function applyFormatting(pElement) {
pElement.title = pElement.innerHTML.length
}
button.onclick = function () {
var p = document.createElement("p");
p.innerHTML = input.value ;
document.body.appendChild(p);
p.id="p";
applyFormatting(p);
}
var ar = document.getElementsByTagName("p");
for (var i = 0; i < ar.length; ++i) {
applyFormatting(ar[i]);
}
that way the "formatting" you want to apply to your already existing p elements is centralized in a function and you know that the elements will undergo the exact same transformation.
That happens because you are adding title only on page load. And titles are not added when new elements are created. You should do something like that on button click:
button.onclick = function () {
var p = document.createElement("p");
p.innerHTML = input.value ;
document.body.appendChild(p);
p.id="p";
p.title = input.value.length;
}

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();

how to assign a function to elements that where added dynamically after page load?

I have two buttons. I use them to add/remove div's (class="rect") from the 'main' tag. I want to be able to change each of the divs' background color when clicking on it. I managed to do that for all the divs I'm creating at the first time the page loads but the function doesn't work on the new divs I add. I know it's because in my code the function is inside the onload but when i take it out it doesn't work. Any help please?
HTML:
<body>
<div id="wrapper">
<header>
</header>
<div id="buttonscontainer">
<button class="button" id="add">+</button>
<button class="button" id="remove">-</button>
</div>
<main id="main">
</main>
</div>
This is my last js attempt:
window.onload=function(){
for(var i=0;i<6;i++){
var rectangle = '<div class="rect"></div>';
document.getElementById("main").innerHTML += rectangle;
}
document.getElementById("add").onclick = addRect;
document.getElementById("remove").onclick = removeRect;
var rectangles = document.getElementsByClassName('rect');
for(var i = 0; i < rectangles.length; i++) {
var rectangle = rectangles[i];
rectangle.onclick = function() {
this.style.backgroundColor = "red";
}
}
}
/*defines the behaviour of the addRect onclick*/
function addRect(){
var rectangle = '<div class="rect"></div>';
document.getElementById("main").innerHTML += rectangle;
}
/*defines the behaviour of the removeRect onclick*/
function removeRect(){
var rectangle = '<div class="rect"></div>';
document.getElementById("main").lastChild.remove();
}
thanks for the replies...i finally solved it with the following changes:
window.onload=function(){
for(var i=0;i<6;i++){
var div = document.createElement("div");
div.className = "rect";
document.getElementById("main").appendChild(div);
}
document.getElementById("add").onclick = addRect;
document.getElementById("remove").onclick = removeRect;
}
window.onclick = function func(){var rectangles = document.getElementsByClassName('rect');
for(var i = 0; i < rectangles.length; i++) {
var rectangle = rectangles[i];
rectangle.onclick = function() {
this.style.backgroundColor = "red";
}
}
}
Please use event delegation
add one event listener to the parent Element holding the rects then use event.target to get the actual rectangle that was clicked
var rectHolder = document.getElementById('main');
rectHolder.addEventListener('click', function(event){
var rectClicked = event.target;
rectClicked.style.backgroundColor = 'red';
});

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"

how to combine two vars in javascript?

i am trying to create dynamic textboxes. The textbox should be created only if the previous textbox is non-empty. So far i have done this
<!DOCTYPE html>
<html>
<head>
<script>
var i=0;
function myFunction()
{
var box = document.createElement("input");
box.type = "text";
var str=box+i;
if(i==0)
{
document.body.appendChild(box);
}
else if(document.getElementById('str').value!=0)
{
document.body.appendChild(box);
}
i++;
}
</script>
</head>
<body>
<input type="button" id="button" onclick="myFunction()" value="Show box" />
</body>
</html>
but str is not recognised as element id. Any help will be appreciated.
var i = 0;
function myFunction() {
var lastInput = document.getElementById('box' + i);
if (!lastInput) {
// always put first input
document.body.appendChild(createInput(0));
} else if (lastInput.value != 0) {
// append another one only if previous input content is non-null
i++;
document.body.appendChild(createInput(i));
}
}
function createInput(i) {
var box = document.createElement("input");
box.type = 'text';
box.id = 'box' + i;
box.value = 0;
return box;
}
Your wrongs:
str = 'box' + i;
Forget to assign box.id = str
Use getElementById(str) instead of getElementById('str')

Categories

Resources