This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I am creating group of check boxes dynamically and one extra check box also for selecting all group at once that one too is generated dynamically
this is html output
<input type="checkbox" id="all">all
<br>
<input type="checkbox" name="question">a
<br>
<input type="checkbox" name="question">b
<br>
<input type="checkbox" name="question">c
<br>
<input type="checkbox" name="question">d
this is jquery
$("document").ready(function() {
$("#all").on('change', function() {
if ($(this).is(":checked")) {
$("input[type=checkbox][name=question]").prop('checked', true);
} else {
$("input[type=checkbox][name=question]").prop('checked', false);
}
});
});
this is implementation.
It works fine when checkboxes are not generated dynamically
But when they are generated dynamically code has bug
I am able to check whole group but
I am not able to check single checkbox
This is dynamically generated code
$('#demo3').on('change', function() {
if ($('input[type=checkbox]:checked')) {
var value = $('input[type=checkbox]:checked').val();
alert(value);
$("#demo3").hide();
$.getJSON("json/question.json", function(jd) {
var size = jd.length;
var table = "<table><tr><th><input id=\"" + "selectall" + "\" type=\"" + "checkbox" + "\"/>" +
"</th><th>Question</th><th>Option A</th>" + "<th>Option B</th><th>Option C</th>" +
"<th>Option D</th><th>Answer</th></tr>";
for (var n = 0; n < size; n++) {
table += "<tr><td>" + "<input name=\"" + "question" + "\" type=\"" + "checkbox" + "\" value=\"" + jd[n].questionid + "\"/>" +
"</td><td>" + jd[n].question + "</td>" + "<td>" + jd[n].a + "</td><td>" + jd[n].b + "</td>" + "<td>" + jd[n].c + "</td>" +
"<td>" + jd[n].d + "</td>" + "<td>" + jd[n].ans + "</td></tr>";
}
table += "</table>";
$('#demo4').html(table);
});
}
});
$('#demo4').on('change', function() {
if ($("input[type=checkbox][id=selectall]").is(":checked")) {
$("input[type=checkbox][name=question]").prop('checked', true);
} else {
$("input[type=checkbox][name=question]").prop('checked',false);
}
});
As far as I understand demo4 and demo3 are container elements like div in which you are adding a table which has dynamic HTML.
You could try
$('#demo4').on('change','#<checkboxid>',function() {
checkboxid will be the id that you want to track.
Hope that helps!
Related
Currently, i have this program which asks the user for a couple of inputs (entered using a modal), one of the inputs being of type file, restricted to images only. All of the inputs are shown in a dynamic table. I need to be able to enlarge the image within the table upon hovering over it (mouseover). Here is an example of how it is suppose to look when working;
below is my jQuery for adding the inputs to the HTML table:
//function that adds input values to the table
function addToTable() {
//add tbody tag if one is not present
if($("#inputTable tBody").length == 0) {
$("#inputTable").append("<tbody></tbody>");
}
$(function() {
$('#insertImage').on('change', function()
{
var filePath = $(this).val();
console.log(filePath);
});
});
var imageLocation = $("#insertImage").val().replace(/C:\\fakepath\\/i, "images/");
//append inputs to the Table
$("#inputTable tbody").append(
"<tr>" +
"<td>" + "<img src=" + imageLocation + " class=image" + ">" + "</td>" +
"<td>" + $("#addName").val() + "</td>" +
"<td>" + $("#addSurname").val() + "</td>" +
"<td>" +
"<button type='button' " +
"class='btn'><i class='fas fa-user-edit' id='pencilIcon'></i></button>" +
"<td>" +
"<button type='button' " +
"onclick='openModal(); deleteData(this);'" +
"class='btn'><i class='fas fa-dumpster' id='dumpsterIcon'></i></button>" +
"</button>" +
"</td>" +
"</tr>"
);
}
Below is the input asking for the image (HTML):
<div class="form-group">
<label for="insertImage">Insert Image</label>
<input type="file" class="form-control-file" data-toggle="popover" data-html="true" data-placement="bottom" name="insertImage" id="insertImage" accept="image/x-png,image/gif,image/jpeg" aria-describedby="inputHelp">
</div>
Here is the jQuery function i planned on using to get this popover working:
$(document).ready(function(){
$('[data-toggle="popover"]').popover({
//trigger: 'focus',
trigger: 'hover',
html: true,
content: function () {
return '<img class="img-fluid" src="'+$(this).data('img') + '" />';
},
title: 'Toolbox'
})
});
If anyone has any idea on how i may be able to incorporate the above function to work with my code, id greatly appreciate it!
I can't figure this out for the life of me. Jquery keeps closing the form that I create (instead of <tr><form> ... <td></td> ... </form></tr> it creates <tr><form></form>... I've looked at lots of questions regarding this and each suggestion is to use an intermediate string, which I am. Hopefully someone can pick up on something I'm missing :)
var my_table = $("#output_table").find("tbody");
// Loop over JSON data and create table rows
$.each(json.data, function(index, field) {
var html_string = "<tr><form action='addtoDB.php' method='POST'>" +
"<input type='hidden' name='instructor' value=" + field.instructor + ">" +
"<input type='hidden' name='section' value=" + field.section + ">" +
"<input type='hidden' name='course_id' value=" + field.course_id + ">" +
"<input type='hidden' name='course_name' value=" + field.course_name + ">" +
"<td class='row_head'>" + field.instructor + "</td>" +
"<td>" + field.section + "</td>" +
"<td>" + field.start_time + " - " + field.end_time + "</td>" +
"<td>" + field.weekdays + "</td>" +
"<td>" + field.total + "/" + field.capacity + "</td>";
if (field.open) {
html_string += "<td><input type='submit' value='open to enroll' class='disabled' disabled></td>";
} else {
html_string += "<td><input type='submit' value='Notify me' class='enabled'></td>";
}
html_string += "</form></tr>";
my_table.find('tr:last').after(html_string);
});
I've tried removing <form> and <tr> from the string entirely and adding it at the end with:
my_table.append("<tr><form>" + html_string + "</form></tr>"); but I get the same effect. So confused!
This is actualy not a jquery problem but a browser one. Browsers won't let you do that because the only elements allowed to be children of tr are th and td.
Source : w3c documentation
Dynamically generating rows by jquery
$("#showbtn").on("click", function() {
var tblRow;
$.getJSON('multimob.action', $("#mobileno").serialize(), function(data) {
if (data.mobileno === null) {
alert("Wrong Mobile No.,please Check");
} else {
$.each(data.ls, function(index, value) {
var count = index;
tblRow = $("<tr><td> <input type='radio' id='chk' name='chk' onclick='copyrecord('" + count + "');'/></td><td id='fidrow" + count + "'>" + value.id + "</td>"
+ "<td>" + value.name + "</td>" + "<td>"
+ value.mobileno + "</td>" + "<td>" + value.addres + "</td></tr>");
alert(count + tblRow.toString());
$("#farmTable tbody").append(tblRow);
});
});
The data rows are dynamically created ,Once I select the radio button, it should take the data from that row and it has to be copied to the textfields in the same page .
Help me to get rid of this iisue.
Try this example
Use class
<input type='radio' id='chk' name='chk' class="chk"/>
HTML
$(document).on('click','.chk',function(){
var text=[];
$(this).parents('tr').find('td:not(:first)').each(function(){
console.log($(this).text())
text.push($(this).text())
});
$('#name').val(text[0]);
$('#no').val(text[1]);
$('#add').val(text[2])
});
DEMO
As per your comment: I can change the id and name as 'chk"+count+"' something like this. But how can I copy the row data on selecting the row by radio button
You can get it this way:
$("#farmTable").on('change', '[id^="chk"]', function(){
var tblVals = $("#farmTable tr").map(function(){
return $(this).find('td:not(:first)').text();
});
console.log(tblVals);
});
I am facing an issue with my jquery. I have used jQuery to add controls to table, along with a remove button to remove that particular row in table. here is my code on how i am creating controls in table.
HTML
<table id="controls" cellpadding="10" cellspacing="10">
</table>
<input id="btnAdd" type="button" value="Add" />
my jquery code looks like this
jquery
$(document).ready(function() {
$("#btnAdd").click(function() {
var field = $("#field").val();
var year = new Date().getFullYear()
var DDL_fromProfession = "<select name='ParametersFromProf' id='DDL_FromProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToProf' id='DDL_ToProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_ToProfession += "</select>";
var newRow1 = "<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
var input = "<input name='parameters' id='field' type='text' />";
var input1 = "<input name='parametersCompany' id='field' type='text'/>"
//var inputCurrent="<input name='Current' id='Currfield' type='hidden'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " + input1 + "</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
to remove last row i am using.
jquery
$(document).ready(function() {
$("#controls").delegate("#btn_rmv", "click", function() {
$(this).closest("tr").remove();
return false;
});
});
clicking on remove button refresh the page and remove all the rows that i have added instead of last one.
NOTE: What i ahve digged out is .delegate is server side and it refresh the page. i am unable to remove last row with $("#btn_rmv").click(function() on my page
Please point me to right direction.
Thanks in advance
The code in question does not work as k is not defined, as used in the line
value='" + k + "'
If this error is corrected then the next problem is that you are creating multiple elements with the same id, as seen here
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
which in invalid HTML and will cause problems for jQuery in finding the element with the unique id.
By changing k for 0 and changing the id to a class, the remove code will only remove the current row with the button on. I assume that you really want to remove that row and also the preceding 2 rows.
$('#controls').delegate('.btn_rmv', 'click', function() {
var index = $(this).closest('tr').index() + 1 // as nth-child is 1-based indexing
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove(); // remove 3 rows
return false
});
See demo
Please note that since jQuery 1.7, .delegate() is superseded by .on() so the updated function is:
$('#controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 1
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove();
return false
});
I had a similar experience: I was using Google Chrome and it would refresh the page everytime I called a function. You will have to return false. My problem was when I called a function from an element using "onclick". When I called the function from onclick I had to include the "return false;":
onclick="return false; functionName()"
Try this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
return false;
});
});
Or this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
});
return false;
});
Sorry my Javascript is not very good :(
You can do it in this way..
var RowCount = 0;
$(document).ready(function() {
$("#btnAdd").click(function() {
RowCount = RowCount + 1;
var newRow1 = "<tr id='tr" + RowCount + "'><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv' onclick='RemoveRow(" + RowCount + ")'>Remove</button>";
});
});
function RemoveRow(RowID) {
$('#RemoveRow' + RowID).remove();
}
It looks like you are hooking up the remove click handler on $(document).ready.
On document.ready, the remove buttons do not yet exist (since they are generated dynamically when clicking 'Add', after the document.ready code has run). That's why $("#btn_rmv").click(function()... is not working.
So, after dynamically inserting a remove button in the $("#btnAdd").click event, you explicitly have to add a click handler to it.
EDIT:
If you generate your remove buttons with a unique id (eg. btn_rmv_1, btn_rmv_2, etc), you can add the following to your Add-handler (after appending the new button to the DOM):
$('#btn_rmv_1').click(removeButtonFunction);
I have an ajax function that loads my inbox messages and each of the messages has a user_type and read field.
I'm looping over the messages and generating the html for them.
function initializeMailbox() {
// get all mailbox data
user.GetInboxMessages(function (response) {
if (response) {
inboxMessages['inbox'] = response;
$("#inbox-table").fadeIn();
loadInboxTable();
inboxDataTable = $("#inboxTable").dataTable();
$("#inbox-count").html(inbox_msg_count);
displayMessage(first_msg_id);
}
});
}
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
var user_type = "";
if (inboxMessages['inbox'][i].user_type = 1)
user_type = "DONOR";
else if (inboxMessages['inbox'][i].user_type = 0)
user_type = "CANDIDATE";
else if (inboxMessages['inbox'][i].user_type = 2)
user_type = "GROUP";
$("#inbox-table-body").append(
"<tr class='data-row' style='height: 75px;'> " +
"<td>" +
"<input type='hidden' id='user_type' value='" + inboxMessages['inbox'][i].user_type + "'/>" +
"<input type='hidden' id='read' value='" + inboxMessages['inbox'][i].read + "'/>" +
"<input type='checkbox' id='" + inboxMessages['inbox'][i].message_id + "'></input></td>" +
"<td>" +
"<p class='left'>" +
"<img class='td-avatar' style='margin-top: 0px !important;' src='/uploads/profile-pictures/" + inboxMessages['inbox'][i].image + "' alt='avatar'/>" +
"<br/>" +
"<span class='user-type'>" + user_type + "</span>" +
"</p></td><td>" +
"<h2 onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].firstname + " " + inboxMessages['inbox'][i].lastname + "</h2><br/>" +
"<h3 class='message-subject' onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].subject + "</h3><br/><br/>" +
"<h3 style='font-size: 0.7em; margin-top: -25px; float:left;'><span>" + inboxMessages['inbox'][i].datesent.toString().split(" ")[0] + "</span></h3>" +
"</td>" +
"<td><button class='delete-item' onclick='deleteMessage(" + inboxMessages['inbox'][i].message_id + ");' src='/images/delete-item.gif' alt='Delete Message' title='Delete Message' style='cursor: pointer; float:left; margin-left: 5px; margin-top:-3px;'></button></td>" +
"</tr>"
);
// check if the message has been read
if (inboxMessages['inbox'][i].read == 0) {
// not read
$("#message-subject").addClass('read-message');
} else {
// read
$("#message-subject").removeClass('read-message');
}
inbox_msg_count++;
}
}
Now if I alert out the values of user_type and read, I get the correct values, based on the message it's iterating over. But when it outputs, it's only using the value of the first message.
I need to be able to dynamically style the messages with jquery, based on these values. Can someone please tell me why this isn't working...
Well, for one thing, you are using an ID selector:
$("#message-subject").addClass('read-message');
When you actually have a class:
<h3 class='message-subject'...
Use:
$(".message-subject").addClass('read-message');
Secondly, you are making an assignment (=) instead of doing a comparison (==) on user_type.
Might I suggest a different approach instead of a big if..then..else?
Use an array to index your user_types:
var user_type_labels = [ 'CANDIDATE', 'DONOR', 'GROUP' ];
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
// One line instead of an if/then/else
var user_type = user_type_labels[ inboxMessages['inbox'][i].user_type ];
...
Third, you are adding multiple items with the same ID to your DOM. This is not legal and has undefined consequences.
<input type='hidden' id='user_type' value='...
<input type='hidden' id='read' value='...
You need to use classes for this.
<input type='hidden' class='user_type' value='...
<input type='hidden' class='read' value='...
In your code I think you meant to do the following
if (inboxMessages['inbox'][i].user_type === 1)
Notice the equal signs. What you currently have will always be true and user_type will always be assigned to DONOR