Radio button event not firing - javascript

I have 2 modal dialogs:
Contains items
Contains the versions of those items
When the user selects an item to view, the current versions of that item are retrieved. These versions are displayed in a table on modal dialog 2. Each row in this table holds 1 version. There are 2 columns:
Radio button to select the version
Version name
So, this table of the 2nd modal dialog is produced at run time. This is my code:
jQuery/JS
function showComponentVersionModal(assocComs ,p, comVersions, comVersionArray) {
$('#component-versions-modal .modal-body tbody').find('tr:gt(0)').remove();
var winW = window.innerWidth;
for (var j in comVersions) {
if (comVersions[j].title === p.text()) {
var newRow = '<tr>' +
'<td><input name="versionCheck" type="radio"/></td> ' +
'<td></td>' +
'</tr>';
if ($('#component-versions-modal .modal-body tbody tr:last td:nth-child(2)').text() !== comVersions[j].version) {
$('#component-versions-modal .modal-body tbody tr:last').after(newRow);
$('#component-versions-modal .modal-body tbody tr:last td:nth-child(2)').text(comVersions[j].version);
}
}
}
}
}
This function is executed when the user selects an item and, therefore, produces the 2nd modal dialog with it's versions.
$('input[name="versionCheck"]').on('change', function() {
if ($(this).prop('checked').length <= 0) {
...
} else {
...
}
});
When I click/change any of these radio buttons, it does not go into this function. Any help appreciated.

delegate the event to static parent:
$('#component-versions-modal').on('change', 'input[name="versionCheck"]', function() {
When the elements are dynamically created/added in the DOM then direct event binding doesn't register the events bound on it.
So, in this case you need to delegate the event to the closest static parent #component-version-modal which is in your case. Or $(document) which is always available to delegate the events.

try doing like this
$(document.body).on('change','input[name="versionCheck"]', function() {
//your code
});

Related

Event handler unbinded after first click

In Backbone marionette composite view, I am using following code .
events: {
'click th': 'doSort',
'click #selectAllGroups': 'allMembersSelected'
},
allMembersSelected: function(event) {
var selectAll;
if ($("#selectAllGroups").prop('checked') == true) {
selectAll = true;
} else {
selectAll = false;
}
var allCheckboxes = document.getElementsByName("selectGroupCheckBox");
for (var i = 0, n = allCheckboxes.length; i < n; i++) {
allCheckboxes[i].checked = selectAll;
}
},
where #selectAllGroups is actually checkbox to select and unselect all checkboxes in the list.
the function allMembersSelected is called only first time when the checkbox is clicked , it wouldn't be called on any subsequent clicks.
One Interesting point is that If I remove the below section from code, the click handler would be called on subsequent clicks and the issue wouldn't come.
if ($("#selectAllGroups").prop('checked') == true) {
selectAll = true;
} else {
selectAll = false;
}
You can update this function as:
allMembersSelected: function(event) {
event.stopPropagation(); // add this one too, as seems event is bubbling up.
$('input[type="checkbox"][name="selectGroupCheckBox"]')
.prop('checked', $("#selectAllGroups").prop('checked'));
},
It will mark check all the checkboxes named "selectGroupCheckBox" only when #selectAllGroups checkbox is checked.
This code block:
events: {
'click th': 'doSort', // 2. when event comes here all the elements on the row gets replaced by new rows.
'click #selectAllGroups': 'allMembersSelected' // 1. click on it bubbles up to the parent th
},
I find it that when you click on th it sorts all the rows and replaces all the elements with the new ones. So all the child elements inside every th if they have any event bound on it that will bubble up to the dom and that would cause in sort.
Same thing is happening with your #selectAllGroups checkbox as it is in the th or i would say that should be in the th so any event bound on it bubbles up to the th which causes in sorting and it feels that event is not working on checkbox but it does.

Using jQuery, how to have click event handler respond for selected table columns?

jQuery v1.11
Given an HTML table with 6 columns, I want the cells in the table in columns two, three, five and six to respond to click events. So if a user clicks on a cell in column one or four, the click event handler should not be called.
This prevents the event handler from being called when the user clicks in the first column:
$('#my-table').on('click', 'tbody td:not(:first-child)', function (e) {
alert("I've been clicked on!");
});
And his prevents the event handler from being called when the user clicks in column 4:
$('#my-table').on('click', 'tbody td:not(:nth-child(4))', function (e) {
alert("I've been clicked on!");
});
My question is, how do I modify the above so that the event handler is not called when a click occurs in either column one or four.
JSFiddle
Edit: #micnil answered my specific question and I will find knowing the pattern he suggested useful. However, #Oleg took the time to point out a better approach. Rather than binding the event handler to each cell, he suggested that I should bind an event handler to the table. In my case this proves to be better.
Using performance.now(), discussed here, I get the following results setting up the binding for a jQuery DataTable containing 1,000 rows in Chrome:
Binding the click event to cells took 0.14627581768183972 milliseconds.
Binding the click event to the table took 0.04619236347855349 milliseconds.
You can just put a coma inside the selector:
$('#my-table').on('click', 'tbody td:not(:nth-child(4), :first-child)', function (e) {
alert("I've been clicked on!");
});
I think the best choice in your case is to use the JQuery function index() that will give you the index of clicked td and you can do the condition you want based to the returned index, take a look at Your updated fiddle.
JS :
$('#my-table').on('click', 'tbody td', function () {
if($(this).index() < 4){ //click in td between 1 and 4
alert('td between 1 and 4 clicked');
}else{ //click in another td
alert('td between 5 and 6 clicked');
}
});
Hope that help.
It's important to understand, that the code like $('#my-table').on('click', 'tbody td:not(:first-child)', function (e) {...}); creates first jQuery wrapper with all <td> element which corresponds 'tbody td:not(:first-child)' selector and then bind the event handler separately to every from DOM elements in jQuery object.
I would recommend you to choose another way. You can make one binding of click on the whole <table>. The event bubbling will forward the click on the cell to the parent <tr> and later to the <table>. It's important that e.target get your the clicked <td>.
So the code could be the following:
var columnIndexesIgnore = [0, 3];
$('#my-table').on('click', function (e) {
var $td = $(e.target).closest("td"); // e.target can be <span> instead of <td>
if ($td.length > 0 && $.inArray($td[0].cellIndex, columnIndexesIgnore) < 0) {
// cellIndex is 0-based index. We display in alert 1-based column index
alert("I've been clicked on column " + ($td[0].cellIndex + 1) + "!");
}
});
I used cellIndex property of DOM of <td>. It's 0-based index of column of the <td> element. So you need ignore clicks if $td[0].cellIndex is 0 or 3.
See your demo after the modification: http://jsfiddle.net/OlegKi/spckrjvf/5/
You can check the desired condition by doing this.
$('td').click(function () {
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
if (col == 3 || col == 0) {
alert("I have clicked on column " + col);
} else {
alert("I have clicked on another column");
}
});

jQuery click event lost after appenTo

I am using appendTo to move list items between two list, upon a button click. The button resides in each li element. Each li has two buttons, of which only one is visible at a time, depending on the list the li currently resides.
Here is the function:
// 'this' is the first list
// Click Handler for remove and add buttons
$(this.selector + ', ' + settings.target + ' li button').click(function(e) {
var button = $(e.target);
var listItem = button.parent('li');
listItem.children("button").toggleClass("hidden");
if (button.hasClass("assign")) {
// Add Element to assignment list
listItem.appendTo(settings.target);
}
else
if (button.hasClass("remove")) {
// Remove Element from assignment list
listItem.appendTo(source);
}
})
As long as the list item reside in the original li, the click events in the buttons are triggered. However, once it is moved to the other list using listItem.apendTo. The click item no longer fires. Why is this the case? I cant find anything about this in the docs.
Sometimes jQuery won't be able to find something if it isn't present in the DOM when your script first loads. If it is a dynamically created element, try replacing your click event handlers with 'on'
Rather than:
$(".aClass").click(function(){
// Code here
})
Try:
$("body").on("click", ".aClass", function(){
Code here
})
http://api.jquery.com/on/
You should use on event.
$(".aClass").on("click", function(){
//Your custom code
})
on event is usful for Dynamically generated data + static data already in HTML.
As recommended by user 'apsdehal', a deleate was what i needed:
// Click Handler for remove and add buttons
$(source.selector + ', ' + settings.target ).delegate("li button", "click", function(e) {
var button = $(e.target);
var listItem = button.parent('li');
listItem.children("button").toggleClass("hidden");
if (button.hasClass("assign")) {
// Add Element to assignment list
listItem.appendTo(settings.target);
}
else
if (button.hasClass("remove")) {
// Remove Element from assignment list
listItem.appendTo(source);
}
});

Trigger click event on DOM element

I tried to trigger a click event on an selected DOM element but my code won't work.
You can see my attempt on JSFiddle.
<ul class="list-group">
LG GOLA 8M
LG 5-6M
LP 5-6M
</ul>
$(document).ready(function() {
// I get the string tr from URL parameters
var tr = "fix_LG%20GOLA%208M";
if (tr !== null) {
var terminrahmen = $('.list-group-item').filter(function() {
return $(this).text() === decodeURI(tr).substring(4);
});
// Trigger click event on .list-group-item
terminrahmen.click();
}
// The function to be executed
$('.list-group-item').click(function() {
alert($(this).text());
});
});
When the DOM was loaded I collect some data from URL parameters and compare the data with DOM elements. This part works fine.
After that I get an element and I would like to trigger an click event. The click event should "execute" a specified function.
Have anyone a good solution for me? Thanks in advance.
http://jsfiddle.net/azg2R/2/
Put the click event on top in the ready event.. The click event needs to be triggered after registering the event. It was not happening before
$(document).ready(function() {
// The function to be executed
$('.list-group-item').click(function() {
alert($(this).text());
});
// I get the string tr from URL parameters
var tr = "fix_LG%20GOLA%208M";
if (tr !== null) {
var terminrahmen = $('.list-group-item').filter(function() {
return $(this).text() === decodeURI(tr).substring(4);
});
// Trigger click event on .list-group-item
terminrahmen.click();
}
});
The problem is that you are triggering click event before attaching event handler to it. So you just need to move click handler before triggering click and everything would work as you expected:
$(document).ready(function() {
// The function to be executed
$('.list-group-item').click(function() {
alert($(this).text());
});
// I get the string tr from URL parameters
var tr = "fix_LG%20GOLA%208M";
if (tr !== null) {
var terminrahmen = $('.list-group-item').filter(function() {
return $(this).text() === decodeURI(tr).substring(4);
});
// Trigger click event on .list-group-item
terminrahmen.click();
}
});
JSFiddle

jQuery: How to undelegate a broad delegate on one table column?

Here's the scenario:
I am creating a dblclick delegate on a bunch of table cells that contain a class called 'canEdit'. In a specific instance, I want to remove this delegate, and add a column-based delegate that overwrites the existing one.
Here's what I have:
$('#' + tableID).delegate('tbody tr td.canEdit', 'dblclick', function () {
// Code Here
});
When a specific property is set, this is what is run:
$('#' + tableID).undelegate('tbody tr td.canEdit', 'dblclick');
$('#' + tableID).delegate('tbody tr td:nth-child(' + index + ').canEdit.select', 'dblclick', function () {
// Code Here
});
I am assuming one of the issues is that I'm removing the delegate on everything. Is there a way I can just overwrite and/or remove the first delegate only on the column? Any ideas of a workaround without having to create an entirely new class?
You could use a conditional to run different code within the handler
$('#' + tableID).delegate('tbody tr td.canEdit', 'dblclick', function () {
if( $(this).index()==7) ){
/* code for 8th column*/
}else{
/* code for other columns*/
}
});

Categories

Resources