I have this code for clone/copy a tr element from a modal to a page.
$(function () {
$('#toggleCheckbox').on('click', function () {
var $toggle = $(this).is(':checked');
$("input:checkbox").attr('checked', $toggle);
$('#btnAplicarNorma').prop('disabled', !$toggle);
});
$('#resultadoNormaBody').on('change', 'input[type=checkbox]', function () {
var $my_checkbox = $(this);
var $my_tr = $my_checkbox.closest('tr');
if ($my_checkbox.prop('checked')) {
$my_tr.addClass('copyMe');
}
var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]');
$all_checkboxes.each(function () {
if ($(this).prop('checked')) {
$('#btnAplicarNorma').prop('disabled', false);
return false;
}
$('#btnAplicarNorma').prop('disabled', true);
});
});
$('button#btnAplicarNorma').on('click', function (ev) {
var $tr_to_append = $('#resultadoNormaBody').find('tr.copyMe');
$('#tablaNorma').removeAttr('style');
$('#alertSinNorma').hide();
if ($tr_to_append.length) {
$tr_to_append.find('input[type=checkbox]').prop('checked', false);
$tr_to_append.clone().appendTo('#normaBody').removeClass('copyMe');
$tr_to_append.removeClass('copyMe');
$(this).prop('disabled', true);
}
});
});
But I'm having some issues:
If I mark all checkboxes using the first on the table head then I the code stop working and doesn't clone any tr even if all of them are marked
How do I avoid to clone/copy the same tr twice?
It's possible to modify the checkbox before clone it? If you take a look at the example you'll notice how the clone tr copy exactly as the one on the modal and I want to uncheck the checkbox first, it's possible?
Here is a fiddle to play with, any advice?
The main problem is that your checkboxes inside the table do not really get properly triggered when you programmatically set them selected. To make sure all associated Events get properly triggered you should be triggering a .click() event instead:
$("#resultadoNormaBody").find("input:checkbox").click();
to ensure that you don't end up with duplicate clones the easiest thing is to not clone all the rows in one batch, but iterate thru them, and comparing the html to the ones that have already been added like this:
//fetch all the rows that have already been cloned
var clonedRows = $("#normaBody").find("tr");
//iterate thru all the rows that have been checked
$.each($tr_to_append, function (i, v) {
var added = false;
//fetch their html (for easier compare)
var currentRowHtml = $(v).html();
//now compare against the rows that have already been cloned
$.each(clonedRows, function (i, cRow) {
var clonedRowHtml = $(cRow).html();
if (currentRowHtml == clonedRowHtml) {
added = true;
}
});
//if the row hasn't been added yet- go ahead and clone it now
if (!added) {
$(v).clone().appendTo('#normaBody').removeClass('copyMe');
}
});
Here's a link to your updated fiddle:
http://jsfiddle.net/wq51zL9x/4/
Here is some more info on comparing table rows: Compare two tables rows and remove if match
and here's the more elaborate answer to using .click()
Need checkbox change event to respond to change of checked state done programmatically
Related
I am trying to show the values based on Checkbox check and uncheck
I have got two checkboxes MNC and Worth (Only the Top Ones), i am trying to show or hide the values based on it (pesent under class pack-panel div)
This is my code
$(document).on('change', '.filtermnc', function() {
$(".pack-panel").each(function () {
var visible = $(this).find('.mnccheckbox').prop('checked')
$(this).toggle(visible);
});
});
$(document).on('change', '.filterworth', function() {
$(".pack-panel").each(function () {
var visible = $(this).find('.worthcheckbox').prop('checked')
$(this).toggle(visible);
});
});
When i tried with this code , it is not working and also it is checking all the correspondng checkboxes
Could you please let me know how to achieve this .
http://jsfiddle.net/F8Vk2/121/
I made for one, but it's just a mater of changing the other one likewise:
$(document).on('change', '.filterworth, .filtermnc', function() {
var $this = $(this),
isChecked = $this.is(':checked'),
$packPanel = $('.pack-panel');
isChecked ? $packPanel.show() : $packPanel.hide()
});
You could use this to get the target of the event and verify if it's checked by .is(':checked'). Also, you don't need to iterate over $('.pack-panel') in order to apply your changes. .toggle() will change the visibility by it's previous one, so I think you should hard code to hide or show the panels.
Change your js to
$(document).on('change', '.filtermnc', function() {
var visible = $(this).prop('checked')
if(visible)
$('.mnccheckbox').closest("li").show();
else
$('.mnccheckbox').closest("li").hide();
});
$(document).on('change', '.filterworth', function() {
var visible = $(this).prop('checked')
if(visible)
$('.worthcheckbox').closest("li").show();
else
$('.worthcheckbox').closest("li").hide();
});
http://jsfiddle.net/F8Vk2/123/
You could try ->
$(document).on('change', '.filtermnc', function() {
$('.mnccheckbox').
closest("li").
toggle($(this).prop('checked'));
});
This is basically finding all with .mccheckbox class, and then toggling based on the property of the checkbox you assigned the event too.
Is there a way to force the UI Sortable to change item position in a list when I click some link or a button that pass a value to any of the possible UI events?
Here the Sortable function:
$("#sortable").sortable({
start: function(event, ui) {
// ...
},
update: function(event, ui) {
// ...
},
stop: function(event, ui) {
// ...
}
});
And here is the even of a button which update the value of a text input in spicific row ... It actually fires an Ajax but I'm making it simple here:
$("#sortable tr").on("click", ".row-button", function () {
var sort_id = $this.closest('tr').find('.text-sort-id').val();
...
...
});
UPDATE:
Here is a jsFiddle result of what I did till now. I need to be able when I change the input in second row for example to "5" and click change it visually move to the bottom of the table and so on when change the fourth row input to "1".
I want to be able to change item value when click the change button without resetting all others and from another side, be able to drag any row and change its input value to be less than the one after and more then the input before it and this all happens without changing other values even if we needed to set an equal value.
Please see the comments in the code for an explanation of what I'm doing. I've updated the .sort-btn click event with the following code:
$(".grid-sort-table tbody tr").on("click", ".sort-btn", function() {
var allItems = $('.ui-sortable').children();
//Select all of the input values
var orderedInputValues = $.map(allItems, function(item) {
return $(item).find('input').val();
});
//Order the input values (smallest to largest, by default)
orderedInputValues = orderedInputValues.sort();
//Store the "tr" in a variable so it can be manipulated.
var selectedItem = $(this).closest('tr');
var selectedItemVal = $(selectedItem).find('input').val();
var indexToInsertAt = 0;
for (var i = 0; i < orderedInputValues.length; i++) {
if (orderedInputValues[i] == selectedItemVal) {
indexToInsertAt = i;
break;
}
}
//Find the item at the index the selected item will be inserted at (before or after)
var itemAtIndex = allItems[indexToInsertAt];
//If the selected item's value is greater than the item at the required index, insert it after the item.
if ($(selectedItem).find('input').val() > $(itemAtIndex).find('input').val()) {
selectedItem.insertAfter(itemAtIndex);
}
else { //Otherwise, insert it before the item at the required index.
selectedItem.insertBefore(itemAtIndex);
}
//Additional code below
...
});
Updated Fiddle
I have 2 issues here. Clicking an input on a row should check the row's checkbox. Currently, only the first text input will check the checkbox because of .prev(). Is there a different way to do this? All inputs for that row should check that row's checkbox.
// check checkbox for clicked row
$('table').on('click', 'input[type=text]', function () {
$(this).closest('td').prev().find('input').prop('checked', true);
});
Also, the second block of code isn't working as it should. If you focus on a different row, if the text inputs from the previous (or any) row are blank - remove the checkbox. The checkbox will be a save, and there is no point of saving blank text inputs.
// remove check in inputs are empty for that row
$('input[type=text]').blur(function () {
$('table tr').each(function () {
if ($(this).find('input[type=text]:empty').length()) {
$('td').find('input').prop('checked', false);
}
});
})
http://jsfiddle.net/Ldge5qzn/
Find the closest tr instead and then find the inputs that are checkboxes and set the checked property
$(this).closest('tr').find('input[type=checkbox]').prop('checked', true);
For the second part, the :empty selector tests against the element having child elements not against empty values so that has to also be modified. Loop through each rows text inputs set a flag if any of them are not empty. Set checkbox accordingly
$('table tr').each(function () {
var emptyRow = true;
$(this).find("input[type=text]").each(function(){
if($(this).val().length > 0) {
emptyRow = false;
}
});
if (emptyRow) {
$(this).find('input[type=checkbox]').prop('checked', false);
}
});
JSFiddle Demo
You can do it by checking the closest tr - then finding the checkbox in that tr
$('table').on('click', 'input[type=text]', function () {
$(this).closest('tr').find('input[type=checkbox]').prop('checked', true);
});
Same thing with the second problem - check using the closest tr
Then you can use filter to get all the text inputs with values
Then check the length to see if there are any inputs returned - and set the checked property accordingly using .prop('checked',function()
$('input[type=text]').blur(function () {
var $tr = $(this).closest('tr'); // get closest tr
// get all of input[type=text] with value in that row
var inputsWithValue = $tr.find('input[type=text]').filter(function () {
return $.trim(this.value).length;
});
// set the checked to true if any element has value - else set checked to false
$tr.find('input[type=checkbox]').prop('checked', function () {
return inputsWithValue.length;
}).length;
});
FIDDLE
have a look at this .Hope this helps ...
$('table').on('click', 'input[type=text]', function () {
$(this).closest('td').parent('tr').find('input[type="checkbox"]').prop('checked', true);
});
full code below :-
JSFiddle
I have a JSFiddle: http://jsfiddle.net/dPAAG/
I can loop through the rows which have the checkbox checked...
$('#ordertable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
var row = $(this);
// this is null
var stuff = row.find('.productVal').val();
alert('this is a checked checkbox');
});
But I can't seem to get to the value of the first textbox in the same row. I am trying to access it by using the class name, but it does not seem to work. The variable is always undefined.
Am I missing something simple?
row is a reference to an input which can't have descendant elements. You are missing the closest method for selecting the closest tr parent of the input:
var row = $(this).closest('tr');
You can also use the filtering has method:
$('#ordertable tr').has('input[type="checkbox"]:checked').each(function () {
// `this` here refers the matching `tr` element
});
http://jsfiddle.net/7Tr87/
I have changed your fiddle a bit, The code speaks for itself but if you don't understand any part of it please ask as I'm more than happy to explain it.
I assume you want the value of the first column and not the second column, if you wish to have the second column then you can easily edit the code and change [0] to [1] after the .children() function.
http://jsfiddle.net/dPAAG/2/
$(function () {
$('#go').on('click', function () {
findCheckboxes();
});
});
function findCheckboxes() {
$('#ordertable').find('input[type="checkbox"]:checked').each(function () {
//this is the current checkbox
var row = $(this);
var itemValue = $($(this).parent().siblings()[0]).children().val();
console.log(itemValue);
//var stuff = row.find('.productVal').val();
//alert('this is a checked checkbox');
});
}
I have information that comes out of a database and gets put into a list with a checkbox by each element. This is how it is currently done:
function subjects(){
$.ajax({
url: "lib/search/search.subject.php",
async: "false",
success: function(response){
alert(response);
var responseArray = response.split(',');
for(var x=0;x<responseArray.length;x++){
$("#subjects").append("<br />");
$("#subjects").append(responseArray[x]);
$("#subjects").append("<input type='checkbox' />");
}
}
});
}
it works fine, but I need a way to pick up on if a checkbox is clicked, and if it is clicked then display which one was clicked, or if multiple ones are clicked.
I can't seem to find a way to pick up on the checkboxs at all.
the response variable is "math,science,technology,engineering"
Because you are populating the Checkboxes Dynamically you need to Delegate the event
$("#subjects").on("click", "input[type='checkbox']", function() {
if( $(this).is(":checked") ) {
alert('Checkbox checked')
}
});
To better capture the data it is better if you encase the corresponding data into a span , so that it can be easier to search..
$("#subjects").append('<span>'+responseArray[x] + '</span>');
$("#subjects").on("click", "input[type='checkbox']", function() {
var $this = $(this);
if( $this.is(":checked") ) {
var data = $this.prev('span').html();
alert('Current checkbox is : '+ data )
}
});
It would be best to give your dynamically injected checkboxes a class to target them better, but based on your code try:
$("#subjects").on("click", "input", function() {
if( $(this).is(":checked") ) {
// do something
}
});
Since your input elements are added dynamically, you need to use jQuery's .on() function to bind the click event to them. In your case you need to use .on() to bind to an element that exist in the DOM when the script is loaded. In your case, the element with the ID #subjects.
This note from the docs is mainly for machineghost who downvoted my answer for no apparent reason:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.
$('#subjects input[type=checkbox]').on('click',function(){
alert($(this).prop('checked'));
});
or the change event: in case someone uses a keyboard
$('#subjects input[type=checkbox]').on('change',function(){
alert($(this).prop('checked'));
});
simple fiddle example:http://jsfiddle.net/Dr8k8/
to get the array example use the index of the inputs
alert($(this).prop('checked') +'is'+ $(this).parent().find('input[type=checkbox]').index(this)+ responseArray[$(this).parent().find('input[type=checkbox]').index(this) ]);
simplified example: http://jsfiddle.net/Dr8k8/1/
EDIT: Just for an example, you could put the results in an array of all checked boxes and do somthing with that:
$('#subjects>input[type=checkbox]').on('change', function() {
var checklist = [];
$(this).parent().find('input[type=checkbox]').each(function() {
$(this).css('background-color', "lime");
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist[myindex] = responseArray[myindex];
}
});
$('#currentlyChecked').text(checklist);
});
EDIT2:
I thought about this a bit and you can improve it by using .data() and query that or store it based on an event (my button called out by its id of "whatschecked")
var responseArray = ['math', 'science', 'technology', 'engineering'];// just for an example
var myList = '#subjects>input[type=checkbox]';//to reuse
for (var x = 0; x < responseArray.length; x++) {
// here we insert it all so we do not hit the DOM so many times
var iam = "<br />" + responseArray[x] + "<input type='checkbox' />";
$("#subjects").append(iam);
$(myList).last().data('subject', responseArray[x]);// add the data
}
var checklist = [];// holds most recent list set by change event
$(myList).on('change', function() {
checklist = [];
$(myList).each(function() {
var myindex = $(this).parent().find('input[type=checkbox]').index(this);
if ($(this).prop('checked') == true) {
checklist.push($(this).data('subject'));
alert('This one is checked:' + $(this).data('subject'));
}
});
});
// query the list we stored, but could query the checked list data() as well, see the .each() in the event handler for that example
$("#whatschecked").click(function() {
var numberChecked = checklist.length;
var x = 0;
for (x = 0; x < numberChecked; x++) {
alert("Number " + x + " is " + checklist[x] + " of " + numberChecked);
}
});
live example of last one: http://jsfiddle.net/Dr8k8/5/
The general pattern to do something when a checkbox input is clicked is:
$('input[type=checkbox]').click(function() {
// Do something
})
The general pattern to check whether a checkbox input is checked or not is:
var isItChecked = $('input[type=checkbox]').is(':checked');
In your particular case you'd probably want to do something like:
$('#subjects input[type=checkbox]').click(function() {
to limit the checkboxes involved to the ones inside your #subjects element.