can't use .val on element found by .find - javascript

I have a dynamically generated table, with (currently) a set rule that the first column has to be an unique identifier of some sort. The table is generated based on a json file, altought i don't think that's really important here.
Each table row has a anchor tag added with class="delete". when i click that anchor tag, i execute the following code:
e.preventDefault();
var idCell = $(this).closest('tr').find('td')[0];
If i console.log(idCell),i get <td>01</td> in my console.
If i console.log(typeof idCell) i get object.
If i console.log the type of a random element from the DOM, i get object as well.
My issue is: I cannot get the .val() from idCell, while i can access the .val() from any element directly filtered from the DOM.
My primary concern is why this is(n't) happening, and if there is a fix existing for this type of problem, i would be most gratefull if you would share it with me.
EDIT 1:
Here you have an example table.
<table>
<tr>
<th>
id
</th>
<th>
delete
</th>
</tr>
<tr>
<td>
01
</td>
<th>
delete
</th>
</tr>
</table>
please try to get me the ID of the table, when i click on the delete link, preferably using jQuery.

As JJJ and
Daniel A. White mentioned, The solution is:
1) To use .eq(0) instead of [0] to keep the selector a jQuery element.
2) To use .text() instead of .val() since only input fields have values, and table cells don't.

here's the script (works fine by me)
$(".delete").bind("click",function(e) {
e.preventDefault();
var idCell = $(this).closest('tr').find('td');
idCell.html("");
});

Related

How exactly does this JQuery script work? and how can I modify it to select a specific object?

I am absolutly new in JavaScript and jQuery and I have the following problem.
I have the following jQuery script:
$(document).ready(function () {
$("thead.opening").click(function () {
$(this).next().slideToggle('slow', function () {
$(this).prev("thead.opening").toggleClass("active");
$("thead.opening").find(".imgAccordion").attr("src", "img/arrow.gif");
$("thead.active").find(".imgAccordion").attr("src", "img/arrow_down.gif");
});
return false;
});
});
and in my HTML I have something like this:
<table class="standard-table-cls table-header-cls">
<thead class="opening active">
<tr>
<th>
<img class="imgAccordion" src="img/arrow_down.gif"/>
Ricerca Flussi (la funzione e' consentita per flussi inferiori alle 300 fatture)
</th>
</tr>
</thead>
<tbody class="expanded">
<tr>
<td style="width: 100em;">
SHOW SOMETHING
</td>
</tr>
</tbody>
</table>
...........................................................
...........................................................
...........................................................
<table class="standard-table-cls table-header-cls">
<thead class="opening">
<tr>
<th>
<img class="imgAccordion" src="img/arrow.gif"/>
Ricerca Fatture
</th>
</tr>
</thead>
<tbody class="expanded" style="display: none;">
<tr>
<td style="width: 100em;">
SHOW SOMETHING ELSE
</td>
</tr>
</tbody>
<table>
As you can see in my code there is 2 different tables both having the same classes (standard-table-cls table-header-cls).
When I click on the thead of one of these table it seems to me that the previous script is perfromed (it is right or am I saying wrong assertion?).
I think so because this statment:
$("thead.opening").click(function () {.......
means something like: perform the body of the defined function() when the user click on any thead element having class=opening.
Is it my reasoning correct?
No my doubt (and also the related problem) is: how jQuery know what is the specific thead.opening clicked by the user (the one related to the first table or the one related to the second table)?
What exactly represent the $(this) element in the previous script? (it is the selected object or what?)
And finally, how can I modify the previous script to obtain the reference of the inner tbody of the same table of the thead.opening clicked?
Tnx
I'll keep this as short as possible but this is the scope in the current function. In elements, its an element. So for you?
$("thead.opening").click
runs a function. So the $(this) is the thread.opening that was actually clicked.
Post
this statment ... perform the body of the defined function() when the user click on any thead element having class=opening.
yes that is correct.
how JQuery know what is the specific thead.opening clicked by the user
the answer lies in: $(this).next().slideToggle('slow', function ()....
What exactly represent the $(this) element in the previous script?
the object which is clicked.
obtain the reference of the inner tbody of the same table of the thead.opening clicked
use something similar to the following in the click handler:
$(this).closest('.standard-table-cls').children('tbody')
reference: here and here
hope this helps.
When I click on the thead of one of these table it seems to me that
the previous script is perfromed (it is right or am I saying wrong
assertion?).
You are right
Is it my reasoning correct?
This is correct
What exactly represent the $(this) element in the previous script? (it
it the selected object or what?)
$(this) referes to the element invoking the function $("thead.opening").click(function () {});, so $(this) is equal to $("thead.opening"), where thead.opening is the exact element clicked (not the other thead.opening in your document).
And finnally, how can modify the previous script to obtain the
reference of the inner tbody of the same table of the thead.opening
clicked?
$(this).next() (which is used in your exemple) is the selector to target the tbody. $(this).next()means this (clicked thead), find next sibling element (tbody).
$("thead.opening") returns a array of elements that match the selector, in your case the two separate table headers that have the class opening added to them.
the .click() assigns a click event handler to each of the elements returned by the selector. In your case to both the table headers.
$(this) refers to element which invoked the event in the event handler.
The code $(this).next().slideToggle( is already referencing the next sibling of the thead - in your HTMLs case, the tbody.
You will have to change your script and change selectors. Current $("thead.opening") will for example select all <thead class="opening"> tags, so it would have to be similar to this:
$(document).ready(function () {
$("thead.opening").click(function () {
var thisThead = $(this);
var thisTbody = thisThead.next();
thisTbody.slideToggle('slow', function () {
thisThead.toggleClass("active");
thisThead.find(".imgAccordion").attr("src", thisThead.is('.active') ? "http://placehold.it/30/ffffff/000000" : "http://placehold.it/30/000000/ffffff");
});
});
});
Check this Fiddle with 2 tables.

Edit HTML Table Data cell using Jquery

I have an HTML table, and each cell of the table will have two data attributes. What I'm trying to do is set a button to switch the value being shown in the table between those two attributes.
<table class="table1">
<tbody>
<tr>
<td data-original="A" data-new="B"> A </td>
</tr>
</tbody>
</table>
I'm able to set new text and get attributes outside the table, but whenever I try to within the table I keep receiving an error:
'Uncaught -> TypeError: undefined is not a function'.
I've been receiving this error for a number of commands $('td').text(), .val(), .attr('td'), .getAttribute().
Am I missing a plugin or something for getting and setting values from tables?
ANSWER: I figured out the reason, I was an idiot and didn't mention that there would be numerous TD elements with repeating tags. I eventually used Underscore.js's each method to iterate through them and parts of the below answer to swap the values.
Just made a Fiddle:
$("button").on("click", function () {
$("td").text($.trim($("td").text()) == $("td").data("original")
? $("td").data("new") : $("td").data("original"));
});
to switch between the data-original and data-new values by checking the current text in the td and using a ternary operator.
By using trim() for the initial text issues in case of whitespace are taken care of (as I just noticed that you have whitespace in your example td).
Just in case the button isn't already in the DOM when the page is initially loaded, you have to adjust the on() to delegate the click event from a static parent element to the button, e.g. like this: $(document).on("click", "button", function () { ...
Instead of $(document) every other static parent element can be used.
And as you mentioned that the table will have multiple tds with data-attributes, I've just adjusted the Fiddle to take care of that:
$("button").on("click", function () {
$("td").each(function () {
$(this).text($.trim($(this).text()) == $(this).data("original") ?
$(this).data("new") : $(this).data("original"));
});
});
I don't know how .text() didn't work for you.
To set text inside td elements, you use .text(). To get the data inside data-current or data-new, jQuery has a handy function .data(tag), for example $(sel).data('current').
Here's a fiddle displaying usage of this on your problem.

jQuery - cannot get col number of a td

I try to get a column number of a td by selecting the td by its class name. But it always returns -1. What is wrong?
js fiddle
HTML
<table >
<tbody>
<tr>
<td >apple</td><td class="current">banana</td><td>cherry</td>
</tr>
</tbody>
JS
console.log($("td.current:first").parent().parent().children().index($(this)));
You can use the variant of .index() that does not take any arguments, to get the index based on its sibling elements
console.log($("td.current:first").index());
Demo: Fiddle
Simply do:
console.log($("td").index($("td.current:first")));
As you have it, $(this) is pointing to the window object, and not the scope you think it is, which has not been defined in the context of the call.
Also note that index() works thusly: collection.index(member).
you don't neet to get parent then parent, Simply do this
$("td.current:first").index();

jQuery How to Target A String in a TD Class

I'm trying to subtract a two characters from a string that is being dynamically generated from a database that is being placed into a shopping cart table td. So instead of having a product show as $28.00, I want the product to show up as $28. Since these values are coming from a database, I can't simply define the string in a variable, like I've seen in a lot of tutorials.
Here's my JS Fiddle
http://jsfiddle.net/EbckS/6/
Here's my eronous code
$(document).ready(function(){
$("table td.SCNProductPrice").text(function(i, text) {
return text.slice(0, -2);
});
});
This is a follow up to a different question I posted here:
jQuery Removing last two characters in a class
I'm placing this into a different question because I didn't realize targeting a class within a table td would require different syntax. Thanks for your help!
Assuming your html is valid i.e it has table and td your slice has wrong index. First one will take care of any number of decimal points if at all comes up.
try
$("table td.SCNProductPrice").text(function(i, text) {
return '$' + parseInt(text.replace('$',''));
});
or
$("table td.SCNProductPrice").text(function(i, text) {
return text.slice(0, -3);
});
You should add td inside a tr which is inside a table.
<table>
<tr>
<td class="SCNProductPrice" valign="top">$28.00</td>
</tr>
</table>
Demo
Markup:
<table>
<tr>
<td class="SCNProductPrice" valign="top">$28.00</td>
</tr>
</table>
JS:
$(document).ready(function(){
$("td.SCNProductPrice").text(function(i,text) {
return text.split('.')[0];
});
});
don't forget, you need valid markup during your fiddle. lastly, i'm not sure why you'd want "$28." shouldn't it just be "$28" ? The JS above does the latter.

jQuery class count on a certain table column number

I've been at this for a while and want to know the best way of achieving my goal if anyone has any ideas!
Example:
<table>
<tbody>
<tr>
<td>Hello</td>
<td>Hello (I want to check this column)</td>
</tr>
<tr>
<td>Hello 2</td>
<td class="active">Hello 2 (this column)</td>
</tr>
</tbody>
</table>
jQuery I've got so far (I'm traversing from a clicked element):
var length = $(self).closest("tbody").find("tr").find("td.active").length;
Obviously this gets all the active classes of td, when I only want the second column. I've tried:
var length = $(self).closest("tbody").find("tr").find("td:eq(1).active").length;
This does not work.
Any ideas?
If I'm understanding correctly, you want to get the table cells in the second column (not the first as indicated in the question) which have the class active on them. If that's the case, you can use the following:
var length = $(self).closest('tbody').find('tr').find('td:eq(1)').filter('.active').length;
http://jsfiddle.net/mikemccaughan/g6mnn/
I think your selector isn't doing what you expect it to. I would have expected what you're expecting, but check out this paragraph from the eq() documentation (emphasis mine):
Note that since JavaScript arrays use 0-based indexing, these
selectors reflect that fact. This is why $('.myclass:eq(1)') selects
the second element in the document with the class myclass, rather than
the first. In contrast, :nth-child(n) uses 1-based indexing to conform
to the CSS specification.
So you're going to want to use td:eq(1) without the class selector, then filter your results, and then count them:
var length = $(self).closest("tbody").find("td:eq(1)").filter(".active").length;
Hope that helps!

Categories