dynamically created button is only appearing once [duplicate] - javascript

This question already has answers here:
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Closed 7 years ago.
I am tring to create the update status box like facebook using Javascript/jQuery.
When i click on post button the div element is created but the button that i have appended inside it is appearing only once.
This is my script code:
var hello = function() {
var post = $.trim($("#status_message").val());
if (post.length != 0) {
$('<div id="hi">').text(post).prependTo('.posts');
$("#status_message").val(" ");
$("#hi").append($("#delete"));
$("#hi").append($("#comment"));
}
}
html code:
<input type="button" id="post" name="submit" value="Post" class="btn btn-primary" onclick="hello()">
<div class="counter"></div>

By using .append($('#delete')); You are simply moving an existing div called $('#delete') and appending it to the #hi element. So only one will be used...
However, some of the stuff you are doing doesn't make any sense anyways... You shouldn't use id if you are going to have more than one of them as a rule of thumb. If you have multiple elements with the same name you should have them identified as a part of a class and use the class attribute. If there is only one element then you should use id.
You would want to do something like this...
function hello() {
var post = "test";
var content = $('<div class="hi">');
content.text(post)
.append($('<div class="delete">delete</div>'))
.append($('<div class="comment">comment</div>'))
.prependTo('.posts');
}

Related

Adding a textbox to div without losing values [duplicate]

This question already has answers here:
InnerHTML append instead of replacing
(3 answers)
Closed 6 years ago.
i've a div container and a button. Whenever i click the button, an empty textbox is added to the div. Now, my problem is whenever i click the button, the textbox is added, but the values of all others are removed.
The function is made like this:
function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}
I think it help you:
var child = document.createElement('input')
document.getElementById("txtList").appendChild(child);
You could achieve the same thing as the snippet below:
function addTextBox() {
var input = document.createElement("input");
input.type = "text"
document.getElementById("txtList").appendChild(input);
}
document.getElementById("addTxtBoxBtn").addEventListener("click",addTextBox);
<input type="button" id="addTxtBoxBtn" value="add TextBox"/>
<div id="txtList">
</div>
Why you can't achieve the same thing with innerHTML?
This happens because:
The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.
While the valueof an ipunt element is not an attribute of the element but a property (please have a look here).
If you want to check it in action, please try the following snippet:
function addTextBox() {
var txtList = document.getElementById("txtList");
console.log(txtList.innerHTML);
txtList.innerHTML += "<input type='text'/>" ;
}
document.getElementById("addTxtBoxBtn").addEventListener("click",addTextBox);
<input type="button" id="addTxtBoxBtn" value="add TextBox"/>
<div id="txtList">
</div>
What is happening under the hood here is that when you append the DOM as text using innerHTML you are simply rewriting that section of HTML. Editing your textList innerHTML will execute a new paint of that element and all information will be parsed again. This means you loose your user interaction.
To update your DOM elements successfully there are methods which enable you to do that. namely document.createElement and document.appendChild.
By appending the DOM element as opposed to concatenating the innerHTML(text) your are forcing a limited paint of the specific area. This leaves the rest of the DOM in tact.
Your code here
function addTextBox() {
document.getElementById("txtList").innerHTML += "<input type='text'>";
}
Becomes more like the following
function addTextBox() {
var textEl = document.getElementById("txtList");
var input = document.createElement("input");
input.type = 'text';
textEl.appendChild(input);
}
When you change append to innerHTML as a string, another string gets created (they are immutable). Browser than has to re-render the whole thing.
The other answers show appendChild, but since in your original question you used a string, maybe you want to keep doing so. If that's the case, you can use insertAdjacentHTML with 'beforeend' as first argument.
document
.getElementById('button')
.addEventListener('click', () => {
document.getElementById('txtList')
.insertAdjacentHTML('beforeend', '<input type="text">');
});
JSBin link is here.

Cant use find on element textarea which is child of td [duplicate]

This question already has answers here:
`find()` undefined is not a function
(4 answers)
Closed 6 years ago.
I get an error on the line targetTD[6].find('textarea').text() saying targetTD[6].find is not a function. (In 'targetTD[6].find('textarea')', 'targetTD[6].find' is undefined)
$(document).ready(function () {
$(document.body).on('click','.edit',function () {// use button class ince ID has to be unique per button
var targetTD;
if( $(this).find('i').hasClass('glyphicon-edit'))
{
targetTD = $(this).parents('tr').find('td'); // gives all TDs of current row
if (targetTD[6].firstChild.children.length) // the value cell is what we want
{
// targetTD[6].firstChild.children.item().setAttribute('readonly','false');
alert(targetTD[6].find('textarea').text());
}
I am trying to find a text area within a <td><div> <textarea readonly> some text </textarea><div><td>. How can I remove the readonly property ? Why cant I use find ?
Try to replace:
targetTD[6].find('textarea').text();
With:
$(targetTD[6]).find('textarea').text();
Because targetTD is an array with not wrapped elements. Also, to remove readonly property use:
$(targetTD[6]).attr("readonly", false);
targetTD[6] is a native JavaScript node. You need to wrap it in a jQuery selector $()
Like so: $(targetTD[6]).find

Getting the content of dynamic div after clicking the back button

I have a couple of divs that I created dynamically, which are added for documents that the user already seen.
doc_html.innerHTML = '<div id=' + doc_id + ' class="seen-doc"> <h5>You\'ve already seen this document.</h5></div>' + doc_html.innerHTML;
I also have this code to run when the user clicks the back button while on document, to return to the main menu. (I got this from https://stackoverflow.com/a/19196020/1122229)
<input type="hidden" id="refresh" value="no">
<script>
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? update_seen_docs() : $input.val('yes');
});
</script>
What I need update_seen_docs() to do is look at the dynamic divs that I created earlier (with id equal todoc_id) and check if they exist or not. I already have the list of doc_ids that I want to check their existence. What I need is a way to check whether these dynamic div been created successfully by my earlier code.
I have tried putting this in my update_seen_docs()
doc_html = document.getElementById(doc_id);
if (doc_html){
# do stuff
}
but since the divs with doc_id are dynamic, doc_html is always null.

How to replace text in DIV tag that only has class no id, using Javascript that is injected into a WKWebView [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 7 years ago.
I am trying to replace some text in a DIV tag using JavaScript, but the tag only has a class not an ID. I have tried:
document.getElementByClassName('theClassName').innerHTML = 'text i want to insert in place of the existing text';
This has not worked, I also tried the above but using getElementById but that didn't work either.
UPDATE:
I think I need to explain more (sorry im a n00b coder). What I am doing is loading a website into a WKWebView using Swift, I am then injecting a .JS file at the end of the page loaded. Within that .JS file I am then trying to do the above with no success. I can find a DIV and hide it so far but being able to replace the text is proving hard.
Here is what I tried last but this did not work either:
var classes = document.getElementsByClassName("title-random");
for(var i=0;i<classes.length; i++) {
if(classes[i].innerHTML == "The old text") {
classes[i].innerHTML = "the new text";
break;
}
}
I have even tried generic "find this text" and replace it code but with no effect
Hi if u have the class on several divs u have to access via array like this:
<!DOCTYPE html>
<html>
<body>
<div class="example">First div element with class="example".</div>
<div class="example">Second div element with class="example".</div>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>

Javascript: Dynamic Generation of a Div

I have several vertically stacks divs and I want to have a div appear when I click a button within each of these divs. The div that I want to appear will be the exact same for each appearance with the exception of an id associating it with the outer div. How do I do this in Javascript?
I assume I should use the createElement() within Javascript, but how do I append it to the end of a specific element. Also, when creating an element, I have to hardcode the html in the Javascript file. Is there anyway to leave the element within the html design file. I want to seperate design from code as much as possible.
Clone Node
var clone = myDiv.cloneNode();
Example (live demo):
HTML
<div>
<input type="button" onclick="functionClone(this);" value="Dolly"/>
<input type="button" onclick="functionClone(this);" value="Dolly_1"/>
</div>
Javascript:
functionClone = function(subject){
var clonenode = subject.cloneNode(true);
subject.value = subject.value + '\'s been cloned!';
subject.disabled = true;
insertElementAfter(subject, clonenode);
}
insertElementAfter = function(subject, newElement){
subject.parentNode.insertBefore(newElement,subject.nextSibling);
}
To append an element below your div use this:
subject.parentNode.appendChild(clonenode)

Categories

Resources