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();
});
Related
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>
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);
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
jQuery function not binding to newly added dom elements
(13 answers)
Closed 6 years ago.
since I am new to JS / jQuery it is probably a obvious problem (but no exception thrown). I read that I can't use .onclick so i tried this approach with .on("click"...)
I try to build a table that adds new lines under the clicked line. This should also work for the newly created lines.
My html:
<tbody>
<tr id="line1"><td>Stuff1</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
<tr id="line2"><td>Stuff2</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
<tr id="line3"><td>Stuff3</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
<tr id="line4"><td>Stuff4</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>
</tbody>
My JS:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("tr").on("click",function(){
var childId = $(this).attr("id")+1;
if($("#"+childId).length){
$("#"+childId).toggle();
}else{
$(this).after('<tr id="'+childId+'"><td>Stuffxxxx</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>');
//AJAX
}
});
});
</script>
Thanks for your help! :)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("table").on("click","tr", function(){
var childId = $(this).attr("id")+1;
if($("#"+childId).length){
$("#"+childId).toggle();
}else{
$(this).after('<tr id="'+childId+'"><td>Stuffxxxx</td><td>Stuff</td><td>Stuff</td><td>Stuff</td><td>Stuff</td></tr>');
//AJAX
}
});
});
</script>
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.
I have 3 link images, which you're supposed to click, and then a caption will appear underneath, and also on a clickable button, which will take you to that site. All 3 go through the same button and caption, so it has to change based on which image you clicked. I am only allowed to use ONE function to make that work. So I did that, but it still doesn't do anything when I click the buttons.
I am NOT allowed to mess much with the structure - I must get ONE function of some kind to make all 3 of those linked images put out the 3 variables (caption, button, and target) depending on which image is clicked. I already made it work with 3 different functions, but now I have to do it with one.
I AM A TOTAL NEWBIE, so please show me how to do it as plainly as possible. thank you!
<html>
<head>
<script>
var caption1='My Blog';
var button1='My Blog';
var target1= 'http://iamunicorngirl.livejournal.com';
var caption2='Nail Polish Line';
var button2='Nail Polish Line';
var target2='http://mustachelacquer.etsy.com';
var caption3='Failblog';
var button3='Failblog';
var target3='http://failblog.org';
function ButtonFunction(caption1, button1, target3);
{
document.getElementById('linkbox').innerHTML=caption1;
document.getElementById('mybutton').innerHTML=button1;
document.getElementById('linkbox').setAttribute('onclick','window.location.href="'+ target3 +'";');
}
</script>
</head>
<table>
<table align="center">
<tr>
<td><img type="picture" src="blog.png" onclick="ButtonFunction(caption1, button1, target1)";></td>
<td><img type="picture" src="nailpolish.png" onclick="ButtonFunction(caption2, button2, target2)";></td>
<td><img type="picture" src="failblog.png" onclick="ButtonFunction(caption3, button3, target3)";></td>
</tr>
<tr>
<td><h3 type="text" id="linkbox"></h3></td>
</tr>
<tr>
<td><button id="mybutton"></button></td>
</tr>
</table>
</html>
I notice two problems with the code you provided:
1) You have a misplaced semicolon in your ButtonFunction. It should be like this:
function ButtonFunction(caption1, button1, target3) { ...
2) Your semicolons are outside your onclick definitions. They should be like this:
... onclick="ButtonFunction(caption1, button1, target1);"> ...
Working Example
Note that it is helpful to use a developer console in your browser. Javascript errors become easily identifiable. For example: SyntaxError: Expected token '{'