Calling a function iteratively inside a div from jquery [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Click event doesn't work on dynamically generated elements [duplicate]
(20 answers)
Event handlers on dynamically created elements? [duplicate]
(2 answers)
Closed 4 years ago.
I have a task for which on every click of the button some text is added or updated in the same div.
I have created a dummy code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn2").click(function(){
console.log("functionCalled");
var num = $("#numChange").text();
var numInc = num + "1";
var output = "<b>Hello world!</b><button id='btn2'>Set HTML</button><p id='numChange'>" + numInc + "</p>"
$("#changeMe").html(output);
});
});
</script>
</head>
<body>
<p id="test1">This is a paragraph.</p>
<div id="changeMe">
<button id='btn2'>Set HTML</button>
<p id='numChange'>1</p>
</div>
</body>
</html>
On one click of button, the text changes from 1 to 11, but nothing happens on second click and henceforth. I want it to keep changing everytime I click the button, i.e. it should change to 111, then next click 1111 and so on.
I am not able to figure out whats wrong or missing in the code

For the first time the button on which you are attaching the click event is present in the document. That's why the button click works as expected. But the button created dynamically does not have the event attached to it.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
Use on() for dynamically created element to work as expected:
$(document).ready(function(){
$(document).on('click','#btn2',function(){
console.log("functionCalled");
var num = $("#numChange").text();
var numInc = num + "1";
var output = "<b>Hello world!</b><button id='btn2'>Set HTML</button><p id='numChange'>" + numInc + "</p>"
$("#changeMe").html(output);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<div id="changeMe">
<button id='btn2'>Set HTML</button>
<p id='numChange'>1</p>
</div>

Instead of replace html just modify the button's text
var num = $("#numChange").text() + "1";
$("#numChange").text(numInc);

Related

How to select text on click input box in JavaScript? [duplicate]

This question already has answers here:
Selecting all text in HTML text input when clicked
(29 answers)
Closed 2 years ago.
I am new to JavaScript and building an application in which, using plain JavaScript, I would like to select the text (similar to right clicking and select all) upon click of an element on a web page if the element is of type input. Can this be done? If so how would I go about doing this. Any info would be appreciated.
You can add this script at the bottom of your body tag
<script>
document.querySelectorAll('.js-select-input').forEach(input => {
input.addEventListener('click', (e) => e.currentTarget.select())
})
</script>
and for every input that you would like to have this autoselect functionality add the class "js-select-input" as in this example:
<input class="js-select-input" value="foo">
Use select method to achieve this.
Use select method in the callback function of input's onfocus event.
For better understanding, see the following example:
function testFunc(focusedInput) {
focusedInput.select();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="test-input" type="text" name="test-input" value="default-value" onfocus="testFunc(this)">
<script>
function testFunc(focusedInput) {
focusedInput.select();
}
</script>
</body>
</html>

addEventListener vs onclick when callback function changes [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 4 years ago.
My HTML code is below:
My question is, why does it show "before" dialog when clicking Button 1, but show "after" dialog when clicking Button 2?
<html>
<body>
<button id="b1">Button 1</button>
<button id="b2" onclick="OnClick();">Button 2</button>
<script>
var OnClick = function(){alert("before");};
document.getElementById("b1").addEventListener("click", OnClick);
var OnClick = function(){alert("after");};
</script>
</body>
</html>
JSFiddle link: https://jsfiddle.net/72chrqnf/
Cause OnClick gets evaluated to the first function before you change the variable pointing to a different function. When this line gets evaluated:
document.getElementById("b1").addEventListener("click", OnClick);
it evaluates OnClick and results in:
document.getElementById("b1").addEventListener("click", [a reference pointing to the function])
and therefore changing OnClick does not affect it afterwards.

Can't add new cells using dynamically added buttons using jQuery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have HTML file with JavaScript code inside, which should add new cell to table with button when user click on any other buttons in document with class name addCell:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.addCell').click(function() {
addNewRow(this);
});
});
function addNewRow(Sender)
{
var tbl = document.getElementById('testt');
var r = tbl.insertRow(tbl.rows.length);
var c1 = r.insertCell(0);
c1.className = "addCell";
c1.innerHTML = "<button class=\"addCell\">New cell by " + Sender.innerHTML + "</button>";
}
</script>
</head>
<body>
<table border="1" id="testt">
<tr>
<td><button class="addCell">AddNew 1</button></td>
</tr>
<tr>
<td><button class="addCell">AddNew 2</button></td>
</tr>
</table>
</body>
</html>
When I click on the buttons with class addCell, saved in HTML document in design time, my code work well done.
But when I click on new buttons, added by my script in run time, with same class name, nothing happens.
I use class name, for add buttons by jQuery, onclick method, because, number of buttons is unlimited, and writing to all buttons, attribute onclick with name of function, is not the best way to optimize personal code.
What I make incorrect?
Please help me to change this code for well and right work.
I think you need to use event delegation for dynamic appended elements
https://learn.jquery.com/events/event-delegation/
Instead of
$('.addCell').click(function() {
addNewRow(this);
});
try this
$(document).on('click','.addCell',function(){
foo();
});

Javascript: How to copy content from a <p> element to hidden <input> element? [duplicate]

This question already has answers here:
contenteditable change events
(21 answers)
Closed 7 years ago.
Basically I have a element as is demonstrated here:
<!DOCTYPE html>
<html>
<body>
<p contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
</body>
</html>
The user can paste data into that field and therefore change the contents between the tags. The reason to do this is to get the metadata (like hyperlinks, etc.) that would be lost with a simple <textarea> element.
How can you copy this data into an <input type=hidden> element, if the content is changed by the user?
This question is unlike this question where there is no output of the data (a static text is shown, which does not indicate how to access the real data that the User has entered) and the input is of a different type (<div> vs. <p>)
HTML:
<p id="input" contenteditable="true" onKeyup="myFunction()">This is a paragraph. It is editable. Try to change this text.</p>
<input type="text" id="output">
Javascript:
function myFunction() {
document.getElementById("output").value = document.getElementById("input").innerHTML;
}
JSfiddle: http://jsfiddle.net/qw2oveuo/1/
You can combine the input event with the innerHTML to grab the data:
document.querySelector("p").addEventListener("input", function(e) {
document.querySelector("input[type=hidden]").value = e.target.innerHTML;
});
Working Example
This will update the hidden input any time the user changes the content of the p either by keypress or copy/paste.
You can use the jQuery .html() method to get the content of the p tag
<p id="my-contenteditable-p" contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
<input type="hidden" id="hidden-in"/>
like
var content = $('#my-contenteditable-p').html();
and after checking if the content is changed by the user, You can use jQuery .val() method to set the value to hidden field.
$("#hidden-in").val(content);
Just add a listener that gets your text and put it somewhere else:
var get = document.getElementById('getcontenthere');
var put = document.getElementById('putcontenthere');
var updateInput = function() {
put.value = get.innerText;
}
get.oninput = updateInput;
updateInput();
<!DOCTYPE html>
<html>
<body>
<p id="getcontenthere" contenteditable="true">This is a paragraph. It is editable. Try to change this text.</p>
<p>This is type=text so you can see it, but it could be hidden as well</p>
<input id="putcontenthere" type="text">
</body>
</html>

Removed DOM element still appears on the page [duplicate]

This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 8 years ago.
I'm trying to add/remove a DOM element (id ="result") dynamically. The addition seems to work fine but after removal the element still appears on the page.
What's happening here? What am I doing wrong?
Here is my code:
<!DOCTYPE html>
<html>
<body>
<script>
function clearResult() {
if (document.getElementById("result") != null){
alert("remove #result");
$("#result").remove();
if (document.getElementById("result") != null) {
alert("#result still exists");
}
}
alert("Exiting clearResult");
}
function search() {
clearResult();
if (document.getElementById("result") == null) {
alert("add #result");
$('<table id="result"><tr>I am a table</tr></table>').appendTo('#ex');
}
}
</script>
<div>
<button id="search" onclick="search()" value="Send">Search</button>
</div>
<div id="ex">
#*Add result table here dynamically*#
</div>
</body>
</html>
Your HTML is invalid. Content within a table needs to be in td tags. Without those, your code is being rendered as:
I am a table
<table id="result"><tr></tr></table>
You can see that then removing the #result element appears to do nothing, because the text does not disappear. If you change your code to include the td elements, it works fine:
$('<table id="result"><tr><td>I am a table</td></tr></table>').appendTo('#ex');
Example fiddle
Note that you can also massively simplify your code. You don't need to check for the existance of an element before removing it in jQuery. Also, you should use jQuerys event handlers, instead of outdated on attributes. Try this:
<div>
<button id="search" value="Send">Search</button>
</div>
<div id="ex"></div>
$('#search').click(function() {
$('#ex').empty().append('<table id="result"><tr><td>I am a table</td></tr></table>');
});
Updated fiddle
I use empty() here on the #ex element to save a selector, it has the same behaviour as remove(), except is performed on the children of an element, not the element itself.

Categories

Resources