I am trying to create a loop which is reponsible to delete DOM elements (one or severals lines into an HTML table) :
<tr class="entireLine><input type="checkbox"></tr>
<tr class="entireLine><input type="checkbox" checked></tr>
<tr class="entireLine><input type="checkbox" checked></tr>
JS
for (var i=0; i<$(".entireLine").length; i++){
// Get the current line of the table
var currentLine = $(".entireLine")[i];
// Get the checkbox in the DOM element
var checkbox = $(currentLine).find("input[type=checkbox]");
// Check the state of the checkbox. If checked, remove the line.
if ( $(checkbox).is(":checked") ) {
$(currentLine).remove();
}
}
This code works fine only when there is one line selected. From 2 lines selected, the second line is not deleted because the index (i) is not good after the first remove.
Where is my mistake ?
You can just find tr with checked checkboxes
$(".entireLine").has('input[type=checkbox]:checked').remove()
In your loop the problem is the expression $(".entireLine").length is evaluated in each iteration, it will reduce the length if item was removed in the previous iteration but the value of i is not reduced so there will be some leftout items
.has()
:checked
Use a jquery each:
$(".entireLine").each(function( index ) {
if ($(this).find("input[type=checkbox]").is(":checked")) {
$(this).remove();
}
});
And correct your HTML, it's not <tr class="entireLine> but <tr class="entireLine"> (You forget the closing ")
Reverse your thinking - instead of looping through all the rows to find selected items, find the selected items then remove their rows:
$(":checkbox:selected").each(function() {
$(this).closest("tr").remove();
});
I would do something like this, instead of doing the for loop. This will find all the checkboxes, and do a $.each and if they are checked, it will remove them. I put checkboxes in its own var for debugging purposes.
var checkboxes = $('input[type=checkbox]');
checkboxes.each(function(){
var $checkbox = $(this);
if ( $checkbox.is(":checked") ) {
$checkbox.remove();
}
})
Related
How can I check if the current element in a .each loop is the last element in a selection?
I have tried it with the following code:
$('#order').find('.xyz').find('input[id ^="order"]').not('[id $="_zyx"]').each(function (index, element) {
var isLast = ($(element) == $('#order').find('.xyz').find('input[id ^="order"]').not('[id $="_zyx"]').last());
});
With the query I am getting three elements. And I want to select the last element of this selection for further use.
In order to determine which element is the right one I have tested it with the code above but I am getting false for isLast for the last element where it should be true.
Am I missing something?
You don't need to use Jquery for this.
Use the length of your elements and the index of your loop.
var elements = $('#order').find('.xyz').find('input[id ^="order"]').not('[id $="_zyx"]');
elements.each(function (index, element) {
var isLast = (index+1) === elements.length;
});
It would be helpful to see your HTML, but you should just be able to use the last selector:
https://api.jquery.com/last-selector/
I am trying to have the user check the boxes they are interested in getting resources for and then click the button to get a list of those resources that are hyperlinked to those resources. The hyperlinks (ul id="results” in HTML) are hidden until they called upon by the button “Get Resources”.
Plus I would like to add text to it before results saying “You have indicated an interest in:” (line break) then a listing the hyperlinks (line break) “Please click on the links to learn more”. If no check box is selected the div id=“alert” displays, which I got to work.
I think I am very close, I just can’t seem to get the list of resources.
Here is a link to my coding:
JSFiddle Code sample
$(document).ready(function() {
$('#alert').hide();
$('#results > li').hide();
/* Get the checkboxes values based on the parent div id */
$("#resourcesButton").click(function() {
getValue();
});
});
function getValue(){
var chkArray = [];
/* look for all checkboxes that have a parent id called 'checkboxlist' attached to it and check if it was checked */
$("#checkBoxes input:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join(',') + ",";
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if(selected.length > 1){
// Would like it to say something before and after what is displayed
$('#results > li.' + $(this).attr('value')).show();
} else {
$('#alert').show();
}
}
I'd ditch the selected variable and just check the chkArray contents against the list item classes like:
function getValue() {
var chkArray = [];
/* look for all checkboxes that have a parent id called 'checkboxlist' attached to it and check if it was checked */
$("#checkBoxes input:checked").each(function () {
chkArray.push($(this).val());
});
$('#results li').each(function () {
if ($.inArray($(this).attr('class'), chkArray) > -1) $(this).show()
else($(this).hide())
})
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if (!chkArray.length) {
$('#alert').show();
//alert("Please at least one of the checkbox");
}
}
jsFiddle example
I found a straightforward way of achieving what you want. DEMO: https://jsfiddle.net/erkaner/oagc50gy/8/
Here is my approach: I looped through all checkboxes. This way I could get the index of the current item in the original list, i, and use this index to display the corresponding item in the second list. I filter the checked items by using .is(':checked') condition, and then added them item to the array:
function getValue() {
var chkArray = [];
$("#checkBoxes input").each(function (i) {//now we can get the original index anytime
if($(this).is(':checked')){//is the item checked?
chkArray.push($(this).val());//if so add it to the array
var selected;
selected = chkArray.join(", ");
if (selected.length) {
$('#results').find('li').eq(i).show();//show the corresponding link by using `i`
} else {
$('#alert').show();
}
}
});
}
Last thing in your $(document).ready function, add:
$("#checkBoxes input:checkbox").click(function() {
$('li.' + $(this).val().replace(/ /g, '.')).show()
});
JSFiddle
Explanation:
On document ready, add a click handler to the checkboxes that shows the corresponding hidden list item below. The tricky thing here is the spaces in the list names. This makes each word a separate classname, so simply combine the list names with a dot . which results in a sequential classname call in jQuery.
By using <li class="Fitness & Recreation"> as a list item classname, you are giving this item 3 classnames: Fitness, &, and Recreation. In jQuery you select elements with multiple classnames by including each name preceded by a dot .. For example, selecting a list item element with the classnames foo, bar, and baz:
$('li.foo.bar.baz').show()
In the case of <li class="Fitness & Recreation">:
$('li.Fitness.&.Recreation').show()
Since these values are stored in the value attribute of the checkboxes we use jQuery to pull these values: $(this).val(), replace the spaces with dots: .replace(/ /g, '.'), and concatenate the result to the li. portion to access the appropriate list item.
I have a table that I loop with JQuery in order to find rows that match certain conditions:
$('#sometable').find('tr').each(function () {
var row = $(this); //<----
if(row.find('input[type="checkbox"]').is(':checked')) {
//etc
}
}
My question is, is there a way to remove each matched row? I mean is there a way to collect these row variables inside my if(row.find('input[type="checkbox"]').is(':checked')) so that I can remove the specific rows from my table directly?
Note that my rows don't have a unique id
You may want:
$('#proposedtable tr:contains(input:checkbox:checked)').remove();
or
$('#proposedtable input:checkbox:checked').closest('tr').remove();
Try this:
var filteredRows = $('#sometable').find('tr').filter(function(){
return $(this).find('input[type="checkbox"]').is(':checked'));
});
$(filteredRows).remove();
The above function will gather all the rows(tr) and then filter those rows based on the checked state of checkbox. Later the filtered rows will be removed.
To make it as array, use Array.prototype.slice.call()
var arrFilteredRows = Array.prototype.slice.call(filteredRows);
Is this help you ?
http://jsfiddle.net/LGdA3/
<pre><code>
$('input#myButton').on('click', function(){
$('table#someTable td input[type="checkbox"]:checked').each(function(){
$(this).parents('tr').first().remove();
});
});
</code></pre>
I currently am using this JavaScript code snippet to select 3 checkboxes at a time
$(document).ready(function() {
var $cbs = $('input:checkbox[name="select[]"]'),
$links = $('a[name="check"]');
$links.click(function() {
var start = $links.index(this) * 3,
end = start + 3;
$cbs.slice(start,end).prop("checked",true);
});
});
Currently this code only selects the checkboxes, however I was wondering if anyone knew how to modify it so that it toggles the checkbox selection on and off?
Here's an example of my current code: "jsfiddle" - click the 1-3, 4-6 links etc to check the checkboxes.
Make the second argument to the prop("checked", ...) call depend on the "checked" status of the first (or other) checkbox in the slice:
// ...
$cbs.slice(start,end).prop("checked", !$cbs.slice(start).prop("checked"));
Here's an updated jsFiddle.
[Edit] Or to update each checkbox in the slice individually:
// ...
$cbs.slice(start,end).each(function() {
var $this = $(this);
$this.prop("checked", !$this.prop("checked"));
});
http://jsfiddle.net/ShZNF/3/
$cbs.slice(start,end).each(function() {
if ($(this).is(":checked")) {
$(this).removeProp("checked");
} else {
$(this).prop("checked",true);
}
});
http://jsfiddle.net/ShZNF/1/
Edit: Maeric's solution is better. I wasn't aware removeProp had this gotcha:
Note: Do not use this method to remove native properties such as
checked, disabled, or selected. This will remove the property
completely and, once removed, cannot be added again to element. Use
.prop() to set these properties to false instead.
Let's say I have a table column with 10 rows, each with <td id="num"> and a text value.
How can I use JQuery to loop through each row in the column and input the spins into a Javascript array?
I thought the following code would do it, but it is only getting the first element:
var numArray = [];
$("#num").each(function(n){
numArray[n] = $(this).text();
});
Any ideas?
Thanks!
You can't have multiple elements with the same id. This isn't allowed because the id is used to identify individual elements in the DOM. I'd suggest giving them all the same class, which is allowed.
<td class="num">
Then this should work:
var numArray = [];
$(".num").each(function(n){
numArray[n] = $(this).text();
});
Like mcos said, selecting by id for all the tables doesn't work. There can only be one item on a page with a given id.
You can either give your table an id and do the following:
var numArray = [];
// Assuming #my-table-id is your table and you want all the tds
$("#my-table-id td").each(function(n){
numArray[n] = $(this).text();
});
Or if you don't want all the tds, use a class to identify the ones you want
var numArray = [];
// Assuming #my-table-id is your table and you added class="collect"
// to the tds you want to collect
$("#my-table-id td.collect").each(function(n){
numArray[n] = $(this).text();
});
Also stealing from others answers, the map function can also help you make your code even smaller
var numArray = $.map( $("#my-table-id td.collect"), function (td){
return $(td).text();
})
You can achieve the this with using .text(function(i, text){})
var allText = [];
$("table td").text(function(i, t){
allText.push(t);
});
Code example on jsfiddle
If you need to target a particular cell(s) you can just modify the selector.
$("table td#num").text(function(i, text){
allText.push(text);
});
With that being said, an id should be unique per dom and if you can adjust the html using a class would be the right way.
<td class="num">
some text 1
</td>
$("table td.num").text(function(i, text){
allText.push(text);
});
Example
it's advised that use don't reuse the ID but since it'll html.. it'll still work..
the jQuery ID(#) selector will only select the first match...
you can use the td[id^='num'] or td[id*='num'] or td[id$='num'] instead
use the map ..
var numArray = $("td[id^='num']").map(function(){
return $(this).text();
}).get();
This will select all the td's with ID's starting as num
See it here