Finding the next input (of a parent?) with jQuery - javascript

I've got a checkbox inside a table, and when you click on it, it'll change the background colour accordingly like so...
$("#table tr td :checkbox").bind("click change", function() {
$this = $(this); // cache the jquery object
if($this.is(':checked')) { $this.closest('tr').css('background-color', 'lightyellow'); }
else { $this.closest('tr').css('background-color', '#fff'); }
});
That works just fine, however, I figured I'd like to go one better, so anywhere on the table row you click, it'll check the box and highlight the row.
I tried using this code, but it doesn't work unfortunately:
$("table tr").bind("click", function() {
$(this).parents("tr").find(":checkbox").attr('checked');
});
And here's the HTML code (removed excessive stuff to improve readability...
<td>Name</td>
<td>Description</td>
<td><input type="checkbox"></td>
Any help would be very much appreciated, thank you!

The event your handling is the tr click.
The parent is the table so that will not help. All you need to do is use find() from the this context.
I would use .live to avoid multiple event handlers when one will do.
Assuming you only have one checkbox in the row then use the following.
(note it uses tr's inside tbody to avoid running this on thead rows)
$("table>tbody>tr").live("click", function() {
$(this).find(":checkbox").attr('checked', 'checked');
});
UPDATE
If you want to toggle it try something like
$("table>tbody>tr").live("click", function(ev) {
var $checkbox = $(this).find(":checkbox");
//check to see we have not just clicked the actual checkbox
if ( !$(ev.target).is(':checkbox') ){
$checkbox.is(':checked') ? $checkbox.removeAttr('checked')
: $checkbox.attr('checked', 'checked')
}
});

You want to change this:
$(this).parents("tr").find(":checkbox").attr('checked');
to this:
$(this).parents("tr").find(":checkbox").attr('checked', 'checked');
Otherwise all you're doing is reading the checked attribute, not setting it.

I think you are just forgetting to set the value of the attribute.
$("table tr").bind("click", function() {
$(this).find(":checkbox").attr('checked', 'checked');
});
The jQuery Docs on Attributes might be of some assistance.
Credit to redsquare for noticing that the .parent("tr") is not needed.

Related

How to access paragraph inside table td using jquery

I am having an issue accessing a paragraph inside a table td using jquery.
What I want to do is to hide the paragraph inside table td if the value is X for example.
This is my code. The value is being select but the hiding is not working.
var Privileges = jQuery('.woocommerce-checkout #customer_details
.woocommerce-billing-fields #billing_country');
var select = this.value;
Privileges.change(function () {
if ($(this).val() == 'RO') {
$( "#wc-local-pickup-plus-toggle-default-handling" ).show();
}
else $('#wc-local-pickup-plus-toggle-default-handling').hide();
});
Here is the inspected element image. I have no idea why its not working.
Thank You.
$("table td").children().find('p').hide();
If you added the element dynamically use the following:
Privileges.on('change', function(){
// your code here
});
Its looking like the problem in your code is here:
if ($(this).val() == 'RO')
try changing this to
if ($(this).find(':selected').val() == 'RO')
To summarize, the listener is added to the select box, so in the listener, 'this' refers to the select element. Which doesn't have a value.
$(this).find(':selected') finds any sub element that has the "selected" property, which in this cas we know will be an option, which should have a value.

Jquery - Setting value of <td>

I currently have a table and in 1 column a Delete link, if the user clicks this link it fires an onClick which basically flags that item to be deleted and hide the TR.
It works fine, but I am just wondering if there is a better way .....
$(document).on('click', '.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
var target = $(e.target);
if (!target.is('td')) {return;}
var h = this.innerHTML;
var newH = h.replace("CsUpdated", "CsDeleted");
newH = newH.replace("CsAdded", "CsDeleted");
this.innerHTML = newH;
//We clicked on a TD so get the row TR.
var theRow = $(this).closest('tr');
theRow.hide();
});
I just think there must be a better way than the string manipulation I am doing with the replace? Is there?
I've tried these but with no luck...
$(this).attr('value', 'CsDeleted');
$(target).attr('value', 'CsDeleted');
$(this).val('CsDeleted');
$(target).val('CsDeleted');
Thanks
td has no value use .text() or .html()
td doesnt have a value attribute.
Use
$("td").html() // to fetch html
$("td").html("<span> Hello World </span>") // to set html
$("td").text() // to fetch plain text
$("td").text("Hello World") // to set plain text
You could use any of the following to set the cell contents
.html() or .text() or .prependor .append and more
However .val() only works on inputs that have the value="...." attribute. If you want to prop the Cell with some data use .data("key","value") which can be accessed at any point by calling .data("key");
Try this one,
$(function(){
$('.delete').click(function(){
$(this).closest('tr').remove();
});
});
You may use custom data-- attributes on any html element ( see this MDN article and the reference ). These are accessible through jquery's attr method and have no influence on rendering.
Code PoC:
$(document).on('click', 'td.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
$(this)
.removeAttr('data-CsUpdated')
.removeAttr('data-CsAdded')
.attr('CsDeleted', '1')
;
//We clicked on a TD so get the row TR.
$(this).closest('tr').hide();
});
In case the values given in your code are mutually exclusive, this simplifies to
$(document).on('click', 'td.deleteCell', function (e) {
//Belt and braces - only do this for <td> elements
$(this).attr('Cs', 'Deleted');
// attr 'Cs' contained 'Added' or 'Updated'
// This scheme requires modifications at other places in your original code !
;
//We clicked on a TD so get the row TR.
$(this).closest('tr').hide();
});
Update
As the OP actually wants to modify the value of a child input element, the handler reduces to:
$(document).on('click', 'td.deleteCell', function (e) {
$('input', $(this)).val('CsDeleted');
// more specific selector may be needed depending on possible cell contents
$(this).closest('tr').hide();
});

toggleClass works only on td and not whole tr

I am using a datatable whch has a checkbox on each row..
When the checkbox will be clicked, the total will have a class called "selected"
so here is my code which i have put
$("#domains_list").find("input[name=\'chk[]\']").on("click",
function()
{
$(this).closest("tr").toggleClass("selected");
});
But the problem is, instead of getting the whole as class selected, only particular td is getting highlighted.
Here's a screenshot
so, how can i solve this issue, is there any way?
As Zougen pointed out, your JS is correct - that is why the td next to the input is being colored and not the td containing the input itself. The other tds wont get highlighted probably because your CSS is being overwritten.
One thing though: your selector looks a little bit strange:
.find("input[name=\'chk[]\']") here you dont need to escape the single ' since your string delimiters are " anyways, just write:
$('td input[name*="chk"]').change(function() {
$(this).closest('tr').toggleClass("selected");
});
i have achieved the same purpose by following jQuery code, i hope this will solve your problem as wel.
$(function() {
$('td:first-child input').change(function() {
$(this).closest('tr').toggleClass("selected");
});
});

Jquery, getting 'this' selector from a conditional

I have several elements on my page with the 'checkbox' class. When clicked, a corresponding checkbox input is checked. However, I need to have JQuery check if the checkbox element is active when the page first loads, and check the checkbox input accordingly at that time.
Since there are multiple 'checkbox' classes on my page, I used the 'this' selector previously and it worked fine, however I do not know how to make it do this with my conditional on page load without the .click action that I used before. Here's what I'm trying to make work:
if($('.checkbox').hasClass('active')) {
$('[name="'+$(this).attr('rel')+'"]').prop('checked', true);
}
Obviously the 'this' selector doesn't know what I'm referring to. Is there a better way of doing this? Since it's checking through a bunch of elements and not just one I'm stumped. Thanks!
You can only use this within the context of a jQuery function, so in this scope it's not going to refer to any .checkbox.
You can use .each instead:
$('.checkbox.active').each(function() {
// In this context, this refers to the DOM element represented by .checkbox.active
$('[name="'+this.rel+'"]').prop('checked', true);
});
The each function may suit your needs:
$('.checkbox').each(function() {
var $this = $(this);
if ($this.hasClass('active')) {
$('[name="'+$this.attr('rel')+'"]').prop('checked', true);
}
});
If the checkboxes must be unchecked when the active class is absent, then:
$('.checkbox').each(function() {
var $this = $(this);
$('[name="'+$this.attr('rel')+'"]').prop('checked', $this.hasClass('active'));
});

Dynamic checkbox onchange & javascript

This might be an easy one for you, but I'm stuck, so I hope you can help me.
I'm creating checkboxes through a loop and want to specify a text somewhere in the website if a checkbox is clicked.
I'v seen solutions where a make a script for each checkbox, but that could turn out to be alot sometimes (something like this: chckbx.onchange = function(){} )
I'd rather have one function that is called from different checkboxes, but my javascript skills is basicly non-existing :)
This is what i got so far (which ofcourse dosn't work)
http://jsfiddle.net/Sz3BK/130/
You have jQuery tagged in your question, so I'm going to provide a jQuery answer:
You'd use jQuery's on() method to delegate the event to a non-dynamic ancestor of your checkbox:
$('elem').on('change', 'input[type="checkbox"]', function() {
...
});
Where elem is a non-dynamic ancestor of your checkbox.
In your JSFiddle your checkbox isn't dynamic, but assuming it was, the closest non-dynamic ancestor of it would be the document's body. Therefore, we can use:
$('body').on('change', 'input[type="checkbox"]', function() {
testing('hello', '1');
});
JSFiddle demo.
You may want to extend this by passing in "hello" and "1" as data-* attributes:
<input type="checkbox" name="test" data-newvalue="hello" data-spanid="1" />
<input type="checkbox" name="test" data-newvalue="second" data-spanid="2" />
Here I've created two checkboxes with our two data-* attributes. In our jQuery method we can pull these values and pass them into our testing() function using jQuery's data() method:
$('body').on('change', 'input[type="checkbox"]', function() {
testing($(this).data('newvalue'), $(this).data('spanid'));
});
JSFiddle demo.
We can then modify our testing() function to also use jQuery:
function testing(newValue, spanID) {
$('#'+spanID).text(newValue);
}
This pulls our spanID (e.g. "1") and places it within an ID selector $('#1'), then modifies the text using jQuery's text() method. If you wanted to modify the HTML instead, jQuery also has a html() method for this purpose.
Final JSFiddle demo.
because you are adding che checkboxes dynamicly,
to enable the change event for those added later, use code below
$(document).on('change', 'input[type="checkbox"]', function() {
...
});
Change your jsfiddle code http://jsfiddle.net/Sz3BK/136/ like this...
Add <head></head> in HTML code at top..
and change on load to "No wrap - in head"
This code works fine for me:
$('input[name=test]').change(function(){
if($(this).is(':checked'))
{
alert("chk");
// Checkbox is checked.
}
else
{
alert("unchk");
// Checkbox is not checked.
}
});
Check the fiddle. Hope it helps.

Categories