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);
Related
I am currently creating tables and checkboxes using ajax communication.
After it was created, it was confirmed that the checkbox function was working normally,
Even if I include checked while creating it, the onclick function doesn't fire.
success:function(data){
for (var key in data) {
feature = data[key]
head = feature[0].split(" ")
tail = feature[1].split(" ")
type = feature[2]
name = feature[3]
$('#pharmacophore_table').append("<tr>" +
"<td>" + name + "</td>" +
"<td> <label><input type='checkbox' name='ligand_feature' onclick='show_ligand_feature(this, " + '"' + feature + '"' + ");' ></label>" +
"</tr>");
$("input[name='ligand_feature']").attr( "checked", true);
}
},
error:function(data){
alert(data.status)
}
How can I solve this?
I solved it.
Just add click event
complete: function(){
var chck = document.getElementsByName('ligand_feature')
for (var l=0; l<chck.length; l++){
chck[l].click();
}
I have a table where I want to show the last column only if the column before is hovered. The table data is parsed with JSON.
<script type="text/javascript">
$( document ).ready(function() {
var tag_id = $('#tag_id_hidden').val();
$.getJSON("/tags/get_who_tagged/" + '{{tag.tag_id}}' + "/", function(data) {
var lines = '';
for (var i = 0; i < data.length; i++) {
lines += '<tr id="' + data[i]['entity_id'] + '">';
lines += '<td id="button_id"><button id="prefix_' + data[i]["entity_id"] + '" class="js-programmatic-set-val" value="' + data[i]["entity_id"] + '" name="' + data[i]["title"] + '"><i class="fa fa-plus"></i></button></td>';
lines += '<td>' + data[i]['title'] + '</td>';
lines += '<td id="hover_' + data[i]["entity_id"] + '">' + data[i]['count'] + '</td>';
lines += '<td id="hidden_' + data[i]["entity_id"] + '" style="display:none;">'
for (var j = 0; j < data[i]['usernames'].length; j++) {
lines += data[i]['usernames'][j]['username'] + ', '
}
lines += '</td>';
lines += '</tr>';
//$("#count_user_table").empty();
$('#count_user_table tbody').html(lines);
}
});
});
</script>
<script>
$(document).on("mouseenter", "#hover_9242411", function() {$("#hidden_9242411").show();
});
$(document).on("mouseleave", "#hover_9242411", function() {$("#hidden_9242411").hide();
});
</script>
in the example above the code is working but I have to reference the id as "#hover_9242411" and "#hidden_9242411". the part after hover_/hidden_ is dynamically added to each column with a for loop. How can I dynamically reference the second part (9242411)?
Consider modifying your hover cell to something like this:
'<td id="hover_' + data[i]["entity_id"] + '" class="hover-cell" data-target="#hidden_' + data[i]["entity_id"] + '">'
You could then simply use:
$(document).on("mouseover", ".hover-cell", function() {
var target = $(this).data('target');
$(target).show();
});
Fiddle
If it will always be the previous column showing/hiding the next column, you could write your event handlers like this
$('#mytable').on('mouseenter', 'td.hover-column', function(){
$(this).next().show();
}).on('mouseleave', 'td.hover-column', function(){
$(this).next().hide();
});
For that example to work you would need to add a class to the hover column (the one that you want to hover over in order to show the next column). I also gave an id to the table and assigned the event handler to it so the event doesnt have to bubble all the way to the top.
Here is a fiddle
If later on you find that you arent showing/hiding the NEXT column but some other one, you could also put a specific class on that hidden column and instead of using
$(this).next().show();
you could use something like
$(this).closest('tr').find('td.hidden-column').show();
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 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
I have a HTML snippet as follows, I want to take the 'article-form' div, clone it, and increment the numbers for the attributes for, id, and name.
<div class="article-form">
<label for="id_form-0-section">Section:</label>
<select id="id_form-0-section" name="form-0-section">
<option selected="selected" value="">---------</option>
<option value="1">News</option>
<option value="2">Originals</option>
</select>
<label for="id_form-0-slug">Slug:</label>
<input type="text" maxlength="255" name="form-0-slug" id="id_form-0-slug">
<input type="hidden" id="id_form-0-collection" name="form-0-collection">
<input type="hidden" id="id_form-0-order" name="form-0-order">
<input type="hidden" id="id_form-0-id" name="form-0-id">
</div>
I have the cloning part so far, but I need to take what I have cloned an traverse the elements inside have the attribute for, id, and name.
var $articeForm = $('.article-form').clone();
Let me add, the increment part isn't the problem. I plan on doing the following. I am not sure what is the best way to traverse by attribute.
var newNumber = parseInt($('#id_form-0-id').attr('id').split('-')[1]) + 1;
One more thing, the fact that this started at 0 is meaningless, in some situations it could start with 5 and then the next fields that follow should be 6.
You could grab a little regex and parseInt() for this. E.g.
element.attr('name', element.attr('name').replace(/(.*form\-)(\d+)(\-.*)/, function(f, p1, p2, p3) {
return p1 + (parseInt(p2) + 1) + p3;
}));
There's however only one huge caveat: Changing name attr of cloned input element in jQuery doesn’t work in IE6/7
var counter = 0;
$('myElement').each (function(index)) {
$(this).attr('id'+counter);
counter++;
});
You may want to keep a variable that tells you how many clones you made so far.
var count = 0;
Then every time you make a clone you increment the count.
count++;
$articleForm.children().each(function(){
newId = $(this).attr("id") + count;
$(this).attr("id", newId);
});
Assuming you have an area of your page that will hold these cloned divs:
<div id="articles"></div>
Start with a page-wide counter variable:
<script type="text/javascript">
var articleFormCount = 0;
<script>
Create a function that builds the HTML for you:
<script type="text/javascript">
function buildArticleFormDiv()
{
var html = "<div class=\"article-form\">" +
"<label for=\"id_form-" + articleFormCount + "-section\">Section:</label>" +
"<select id=\"id_form-" + articleFormCount + "-section\" name=\"form-" + articleFormCount + "-section\">" +
"<option selected=\"selected\" value=\"\">---------</option>" +
"<option value=\"1\">News</option>" +
"<option value=\"2\">Originals</option>" +
"</select>" +
"<label for=\"id_form-" + articleFormCount + "-slug\">Slug:</label>" +
"<input type=\"text\" maxlength=\"255\" name=\"form-" + articleFormCount + "-slug\" id=\"id_form-" + articleFormCount + "-slug\">" +
"<input type=\"hidden\" id=\"id_form-" + articleFormCount + "-collection\" name=\"form-" + articleFormCount + "-collection\">" +
"<input type=\"hidden\" id=\"id_form-" + articleFormCount + "-order\" name=\"form-" + articleFormCount + "-order\">" +
"<input type=\"hidden\" id=\"id_form-" + articleFormCount + "-id\" name=\"form-" + articleFormCount + "-id\">" +
"</div>";
articleFormCount++;
$("div#articles").append(html);
}
</script>
Call the function on page load:
<script type="text/javascript">
$(document).ready(function()
{
buildArticleFormDiv();
});
</script>
Then, whatever mechanism you use to add the new div (say, a hyperlink click event), call the buildArticleFormDiv() function.
Here is the solution I have come up with so far. Anything look horribly wrong with it?
function incAttrName(name) {
return name.replace(/(.*form\-)(\d+)(\-.*)/, function(f, form, number, label) {
return form + (parseInt(number) + 1) + label;
});
};
$articleForm.find('[for]').attr('for', function() {
var name = $(this).attr('for');
return incAttrName(name);
});
$articleForm.find('[id]').attr('id', function() {
var name = $(this).attr('id');
return incAttrName(name);
});
$articleForm.find('[name]').attr('name', function() {
var name = $(this).attr('name');
return incAttrName(name);
});