I would like to dynamically add a button control to a table using jQuery and attach a click event handler. I tried the following, without success:
$("#myButton").click(function () {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before('<tr><td>' + test.html() + '</td></tr>');
});
The above code successfully adds a new row, but it doesn't handle adding the button correctly. How would I accomplish this using jQuery?
Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
});
var parent = $('<tr><td></td></tr>').children().append(test).end();
$("#addNodeTable tr:last").before(parent);
});
Or,
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
}).wrap('<tr><td></td></tr>').closest('tr');
$("#addNodeTable tr:last").before(test);
});
If you don't like passing a map of properties to $(), you can instead use
$('<button/>')
.text('Test')
.click(function () { alert('hi'); });
// or
$('<button>Test</button>').click(function () { alert('hi'); });
Quick fix.
Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () {
var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
alert('hi');
}).end();
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before(test);
});
Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.
$("#myButton").click(function () {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed
var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
var td = $('<td>').append(test).appendTo(tr);
});
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.
You were just adding the html string. Not the element you created with a click event listener.
Try This:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<table id="addNodeTable">
<tr>
<td>
Row 1
</td>
</tr>
<tr >
<td>
Row 2
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);
});
</script>
Related
It shows a message 'Hi' when I click on 'ShoW',
But when I click on the next option 'ShoW', it does not show a message.
$('.btn').on("click", function () {
alert('Hi');
$('.box .btn').remove();
$('.btn').clone().appendTo('.box');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>
What code should I add for JS?
This is because the event handler you created is bound to objects that existed when it was created:
$('.btn').on("click", function () {
This will only work for .btn elements that were already available at the time this line of code ran - it is not evaluated by jQuery again.
Instead, use this format for binding the event, which will pick up dynamically created elements:
$(document).on('click', '.btn', function () {
Seen here in this working snippet:
$(document).on('click', '.btn', function () {
alert('Hi');
$('.box .btn').remove();
$('.btn').clone().appendTo('.box');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>
You have to set event once more again after clone.
then, you can declare your event callback as a function, and set event again after cloning on the cloned element, like this:
function appendShowButton() {
alert('Hi');
$('.box .btn').remove();
var newEl = $('.btn').clone().appendTo('.box');
newEl.on('click', appendShowButton);
return false;
}
$('.btn').on("click", appendShowButton);
$(function(){
$("#selector").on("someevent", function(){
let variable = some_value;
$("#anotherselector").click(function(){
//code involving variable here
if(condition){
$(this).off(reference to click event here);
}
});
});
});
Is there any way to turn off an event from inside its handler? I'm trying to do something like the code above, and I need it to turn off ONLY that specific click event (each click event is different).
To reference the click event, you can simply pass it 'click' and the selector for which to disable the event:
$(function(){
$("#selector").on("someevent", function(){
$("#anotherselector").click(function(){
if(condition){
$('#anotherselector').off('click');
}
});
});
});
let numHandler = 0;
$('#register').click(function () {
let counter = 0;
let num = ++numHandler;
$('#clickme').click(function handler () {
counter++;
console.log(`Handler ${num} clicked!`);
if (counter == 3) $('#clickme').off('click', handler);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="clickme">Click me!</button>
<button id="register">Register new handler</button>
You can read more about the off function in the jQuery documentation.
I am learning javascipt and now i have a piece of code but i am unable to get this to work, javascript isn't executed. I have already searched the web but i can't find an answer. Maybe you guys can help me with this.
HTML
<html>
<head>
<title>Text Game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<button><span id="click">0</span></button>
</body>
</html>
Javascript
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
You have a couple of issues here:
Issue #1:
The element does not exist in the DOM to bind to yet, so do any or all of the following:
Move your script tag to the footer, right before the closing </body> tag (generally best practice anyway).
Use event delegation to bind to events on future elements.
Put all the JavaScript in the ready handler.
Issue #2:
You should not bind a click event handler on an element inside a button, it will not work in specification compliant browsers as the button consumes the event, and it not propagated to children.
See the HTML5 spec for button for reference:
Content model:
Phrasing content, but there must be no interactive content descendant.
Instead, bind the click event handler to the button itself.
// Variables
var waarde = {
amount: 2
};
$(document).ready(function(){
updateValues();
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
// Binding to the button element using event delegation.
$(document).on('#button').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button"><span id="click">0</span></button>
Also, unless you need the span element for something else, you could get rid of it and just use:
document.getElementById("button").innerHTML = waarde.amount;
You should put this code:
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
Inside of $(document).ready(function(){}) function. $('#click') isn't in the DOM yet..
You have to write "Click" event in document.ready
var waarde = {
amount: 2
};
$(document).ready(function () {
$('#click').click(function () {
waarde.amount = waarde.amount + 1;
updateValues();
});
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
The problem with your code is you are not assigning an event handler when javascript loads the js file. It should be called in the ready function.
var waarde = {
amount:2
};
$(document).ready(function(){
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
You should wrap it inside the ready method!
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
Here's a codepen link http://codepen.io/anon/pen/vKXQza
Two points:
You should put your jQuery event listener inside the document.ready.
There is no guarantee to work click event on span.
// Variables
var waarde = {
amount:2
};
$(document).ready(function(){
updateValues();
$('#click2').click(function(){
waarde.amount++;
updateValues();
});
});
function updateValues(){
document.getElementById("click2").innerHTML = waarde.amount;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button id="click2">0</button>
You can see your problem solution is here
You are missing button click event in $(document).ready(function(){}(;
I have a script that produces a number of buttons with a class and I want it to alert the data attribute on click but it's not working.
Here is the output of HTML
<button class="request box-button" data-value="18492500814">Request</button>
jQuery code
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).data('value'));
});
});
});
Since your elements don't exist when the page loads, the event won't be bound to them. Fix that by using event delegation:
$(document).ready(function(){
$(document).on('click','.request', function () {
alert($(this).data('value'));
});
});
JS Fiddle demo with dynamically generated elements
Note: Here, I used $(document).on() because I don't have your page's structure. But if you insert the buttons in a container that already exists in your HTML, use this instead: $('#myContainer').on(). It won't be noticeable, but it is best for performance.
Why not just have the listener on request, instead of inside of the loop. Also use the attr to get the data-value
$(document).ready(function(){
$('.request').click(function () {
alert($(this).attr('data-value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>
Try with attr method.
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).attr('data-value'));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>
I have this code tied to a button that when clicked, executes code to hide a table row:
<script>
$(function hideinstr() {
$('tr.parent td').on("click", "input.instr", function () {
var idOfParent = $(this).parents('tr').attr('id');
$('tr.child-' + idOfParent).toggle('slow');
});
});
</script>
I would like this code to execute by default when the page loads, and let the user click the button if the want to reveal the table row. How can I do this when the 'click' is built right into this code?
Your solution never executes the function hideinstr(). Also, consider using $(document).ready if your code is executed in the <head>. Add extra parentheses to execute the function, or remove the surrounding function (function hideinstr).
<script>
$(document).ready(function hideinstr() {
$('tr.parent td').on("click", "input.instr", function () {
var idOfParent = $(this).parents('tr').attr('id');
$('tr.child-' + idOfParent).toggle('slow');
});
}());
</script>
or
<script>
$(document).ready(
$('tr.parent td').on("click", "input.instr", function () {
var idOfParent = $(this).parents('tr').attr('id');
$('tr.child-' + idOfParent).toggle('slow');
});
);
</script>
And to execute the event script directly, use $('tr.parent td').click();.