jQuery - Selecting the first <a> in the first <td> of a <tr> - javascript

I have the following markup:
<tr>
<td>
<a>foo</a>
</td>
<td>bar</td>
<td>
<a class="delete-btn">delete</a>
</td>
</tr>
I've already hooked up a click event handler using jquery $(".delete-btn") the problem is that inside the click event handler I need the text of the first element (foo).
I'm already getting the value I need with this call:
$(this).closest("tr").children().first().children().first("a")
but I feel it's too verbose. Is there a better way to accomplish this?

I don't like this either, but... it's exactly what you're looking for:
$(this).closest("tr").find("> td:first-child > a");

You can make use of jQuery's :first pseudo-selector.
In this instance, your entire selector would be:
$('tr td:first a:first') (for the first <tr> only)
$('tr').find('td:first a:first') (for every <tr>)
Example:
$(document).ready(function(){
$('.delete-btn').click(function(){
$('tr').find('td:first a:first').hide();
})
});
table, tr, td {
border: 1px solid rgb(191,191,191);
border-collapse: collapse;
}
td {
padding: 12px;
}
.delete-btn {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><a>foo</a></td>
<td>bar</td>
<td><a class="delete-btn">delete</a></td>
</tr>
<tr>
<td><a>foo</a></td>
<td>bar</td>
<td><a>baz</a></td>
</tr>
</table>

Related

How do I display the content of closest <td> on javascript?

I have looked everywhere, but my code does not work at all. I simply want to display the content of the td I'm clicking on.
I have this table:
<tr class='rowData' tooltip='{caracteristicas}'>
<td nowrap class='Body'><a href='{caracteristicas}' target="_blank" style="color:black" onClick='return confirm("VOCÊ SERÁ REDIRECIONADO PARA:\r\r {caracteristicas}")'>{inputDescItem}</a></td>
<td nowrap class='Body' align='right'>{quantidade} {hiddenCodigoItem}</td>
<td nowrap class='Body' align='center'>{grupoEstoque}</td>
<td nowrap class='Body' align='center'>{inputCodigoItem}</td>
<td nowrap class='Body' align='center'>{btnAtualizaItem}</td>
<td nowrap class='Body' align='center'><button type="button" class="btnTest">Assign</button></td>
<td nowrap class='Body' align='center' class="testNameClass" name="output" style="display:none;">{caracteristicas}</td>
</tr>
I want it so that when I click on the CLICK ME tag, it will display (in a pop-up, alert, modal or anything) the content of the below tag (that I'm not displaying).
I have the following javascript:
$("btnTest").on("click", function() {
alert($(this).closest('tr').find('testNameClass').val());
});
I'm not very good at JS so please go easy on me.
Look like you missing
$(".btnTest") instead of $("btnTest")
and just try
$(".btnTest").on("click", function() {
alert($(this).parents('tr').find('.testNameClass').val());
});
To target specific elements using a class you need to use a dot in front of the class name. In your case .btnTest and .testNameClass.
$(".btnTest").on("click", function() {
alert($(this).closest('tr').find('.testNameClass').text());
});
As you are looking for the text inside the td element you should use .text() instead of .val()
In the below example column ent_3 is hidden and you will get its values using the script mentioned above.
$(".btnTest").on("click", function() {
alert($(this).closest('tr').find('.testNameClass').text());
});
.testNameClass {
display: none;
}
table {
border-collapse: collapse;
}
th, td { border: 1px solid #000; padding: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="dataTable">
<thead>
<tr>
<th>pk</th>
<th>ent_1</th>
<th>ent_2</th>
<th>ent_3</th>
</tr>
</thead>
<tbody>
<tr>
<td>PK Row 0</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 0 Ent_3</td>
</tr>
<tr>
<td>PK Row 1</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 1 Ent_3</td>
</tr>
<tr>
<td>PK Row 2</td>
<td>Ent_1</td>
<td><button type="button" class="btnTest">Assign</button></td>
<td class="testNameClass">Row 2 Ent_3</td>
</tr>
</tbody>
</table>
Your method will be handed a reference to the MouseEvent which represents details of the click. Since it is an Event, it has a currentTarget which represents an "element" in the so-called DOM ... an internal data-structure which represents the HTML. This data structure is in the form of a tree, where each node has one parent, two siblings, and some children. You can now write code to "walk up the tree" until you encounter a td node. The first one you come to is the innermost containing td.
I think you are targeting is incorrect use a . before the class name - also I see two classes in one element I set this up for you here have a look
https://jsfiddle.net/hw0ansyj/1/
$(".btnTest").on("click", function() {
alert($('.testNameClass').html());
});

Get dataset item from html <a> element using jquery

I have an element within a table in html:
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
and i need to get the value of the "data-productid" attribute
at the moment i have this code:
$(document).ready(function(){
$('#href0').click(function(event) {
event.preventDefault()
console.log(this.dataset.productid)
return false;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
and nothing is being printed in the console.
I am using handlebars
We managed to establish you are using Handlebars templating
What MIGHT then be the case is your links are inserted dynamically when you compile the handlebars.
If that is the case you need to delegate and then this question is a duplicate of Event binding on dynamically created elements?
$(document).ready(function(){
// document or the nearest STATIC container
$(document).on('click','[data-productid]',function(event) {
event.preventDefault()
console.log(this.dataset.productid)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
<td><a id="href0" href="#" data-productid="1">Product 2</a></td>
You dont need to the a in the td at all (or even the id on the a or the td) - simply apply the click handler to the td and have the data attribute on that so that when it is clicked - the console will log the data attribute.
$(document).ready(function(){
$('td').click(function() {
let id = $(this).attr('data-productid');
console.log('The product id is ' +id)
})
});
table {
border-collapse: collapse
}
td {
border:solid 1px #d4d4d4;
padding: 10px 20px;
border-collapse: collapse
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td data-productid="1">Product 1</td>
<td data-productid="2">Product 2</td>
</tr>
<tr>
<td data-productid="3">Product 3</td>
<td data-productid="4">Product 4</td>
</tr>
</table>
If you absolutely must have the a - then its the same as above - just applied to the different element
$(document).ready(function(){
$('a').click(function(event) {
event.preventDefault();
let id = $(this).attr('data-productid');
console.log('The product id is ' +id)
})
});
table {
border-collapse: collapse
}
td {
border:solid 1px #d4d4d4;
padding: 10px 20px;
border-collapse: collapse
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Product 1</td>
<td>Product 2</td>
</tr>
<tr>
<td>Product 3</td>
<td>Product 4</td>
</tr>
</table>

jQuery selector for sibling of a label in a table

I'm writing a user-script for a third-party website and looking to select value inside a table which has a preceding TD with a label.
Question: I'm looking to get value1 as the result, but it's selecting the containing TD as well, so I get something else too.
Limitations
Can't modify the HTML to be more query-friendly (duh, it's not my site ;)
The table has no ids (I added them for easier discussion), not even the <table> itself has an id.
The count of the rows is dynamic, so no tr:nth-child.
Tried
I found this question: Selecting an element which has another element as direct child and used the direct selector (tr:has(> td:contains), but it still selects more than needed, because the outer TD also transitively contains label1 and has a sibling.
Notice that the background I set is transparent to show that multiple TDs are selected.
$(function() {
$('#result').text($('tr:has(td:contains("label1")) > td:nth-child(2)').text())
$('tr:has(td:contains("label1"))').css("background", "rgba(255,0,0,0.3)");
});
table { border-collapse: collapse; }
table, th, td { border: 1px solid black; }
td { padding: 4px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<tr>
<td id="outer">
<table>
<tr><td id="known-info">label1</td><td id="want-to-select">value1</td></tr>
<tr><td>label2</td><td>value2</td></tr>
</table>
</td>
<td id="outer-sibling">something else</td>
</tr>
</table>
<br/>
This should be "value1": "<span id="result"></span>"
You could use :not(:has(td)) in your selector so it should be
$('td:contains("label1"):not(:has(td))').next().text()
This will select td that contains label1 text, but it will ignore parent td because it has another td inside.
var el = $('td:contains("label1"):not(:has(td))').next()
$('#result').text(el.text())
el.css('background', 'blue')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="outer">
<table>
<tr>
<td id="known-info">label1</td>
<td id="want-to-select">value1</td>
</tr>
<tr>
<td>label2</td>
<td>value2</td>
</tr>
</table>
</td>
<td id="outer-sibling">something else</td>
</tr>
</table>
<br/> This should be "value1": "<span id="result"></span>"

displaying html table with javascript

Please am a newbie in programming, I really need your help in this. Please how can I hide an HTML table then display it with a button using.JavaScript?
Use document.querySelector to get the elements and the hidden attribute to show and hide the table. Use an event listener and listen for the click event on the button:
var table = document.querySelector("table");
table.hidden = true;
document.querySelector("button").addEventListener("click", function(event) {
table.hidden = false;
});
table {
text-align: center;
border-collapse: collapse;
}
td,
th {
padding: 0 5px;
border: 1px solid black;
}
<table>
<tr>
<th>Day</th>
<th>Rain</th>
</tr>
<tr>
<td>1</td>
<td>50 mm</td>
</tr>
<tr>
<td>2</td>
<td>21 mm</td>
</tr>
<tr>
<td>3</td>
<td>5 mm</td>
</tr>
</table>
<button>Show</button>
You can use a library called jQuery to do this extremely easily.
In your <head>, put <script src="code.jquery.com/jquery-latest.js></script>
Give your <table> an id, like this: <table id="myTable">
Add one button like this: <button onclick="$('#myTable').hide();">Hide</button>
And another like this: <button onclick="$('#myTable').show();">Show</button>
This will allow you to toggle the table's visibility.
I started writing this before #metarmask posted - his/her answer is much better, so you should probably take his/her advice.

Check if table tr td is not empty

I want to check if the table tr td still gots the dummy text.
If thats true then a message should appear that they have to enter some text there ( by drag and dropping )
Drag and drop is working thats not the problem i just need to check if the td still got the dummy tekst
else the cannot proceed to the next step
here is my html table layout :
<table width="900px" style="background-color: #dcdcdc;">
<tbody class="sortable">
<tr>
<td>
<table width="90%" style="background-color:#85ca00;; margin:0 auto; border: none; border-collapse: collapse; padding: 0; ">
<tbody>
<tr >
<td align="left" style="padding:10px; " class="dropzone">
s
</td>
<td align="right" style="padding:10px;" class="dropzone">
<p class="dummyTekst">s</p>
</td>
</tr>
</tbody>
</table>
<table width="90%" style="background-color:white; margin:0 auto; background-color:lightgrey;border: none; border-collapse: collapse; padding: 0; ">
<tr style="background-color:white;">
<td width="200px;" style=" vertical-align:top;">
<table style=" border: none; border-collapse: collapse; background-color:lightgrey; margin:10px;" width="100%" align="left" class="dropzone Required ">
<tbody >
<th style="background-color:gray">Menu</th>
<tr ><td ><p style="padding:10px;" class="dummyTekst">Drop content</p></td></tr>
</tbody>
</table>
<table style=" border: none; border-collapse: collapse; background-color:lightgrey; margin:10px;" width="100%" align="left" class="dropzone Required">
<tbody>
<th style="background-color:gray">Menu</th>
<tr><td ><p style="padding:10px;" class="dummyTekst">Drop content</p></td></tr>
</tbody>
</table>
</td>
<td style="vertical-align:top; margin-top:20px;" >
<table style=" border: none; background-color:lightgrey; border-collapse: collapse; margin:10px;" width="90%" align="right" class="dropzone Required">
<tbody>
<th style="background-color:gray">Main Content</th>
<tr ><td ><p style="padding:10px;" class="dummyTekst">Drop content</p></td></tr>
</tbody>
</table>
</td>
</tr>
</table>
<table width="90%" style="background-color:#85ca00; margin:0 auto; border: none; border-collapse: collapse; padding: 0;" class="dropzone">
<tr >
<td align="center" style="padding:10px;" ></td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
the p tag is removed if people drop content there
if they didn't a message should appear there
I tried this :
function checkTemplate(){
$jQ('.Required > tbody > tr > td').each(function(index){
if($jQ(this).children().hasClass('dummyText'));
console.log('Empty');
});
}
As I commented:
dummyTekst != dummyText
You're checking for a class dummyText where you provide dummyTekst as actual classname.
Besides that. You don't have to each all the TD's and loop the children. Just check if the class is present. See fiddle: http://jsfiddle.net/z5oyL9cw/
$(document).ready(function(){
if ($(".dummyTekst").length > 0) {
alert('We still have dropzones');
}
});
I would have written it something like this:
function checkTemplate(){
$jQ('table > tbody > tr > td').each(function(index){
if($jQ(this).children('p.dummyTekst').length == 0){
console.log('Empty');
}
});
}
Take a look into jQuery's .each(): http://api.jquery.com/each/
It iterates over every instance of... whatever you want to target. So, yours might be:
$( "td" ).each(function() {
From there, I'd have to look at your javascript to know the best way to check to see if the user changed anything. One option is using jQuery's .has to see if the p exists. http://api.jquery.com/has/ Or you can simply check the child element itself. Once you post your JS, I can say with more certainty.
Why don't you just add a CSS class to your cells (i.e. has-dummy-text) and use it as a flag?
In your example, say for instance:
<table>
<!-- Rest of code ommitted for clarity ... -->
<tbody>
<th style="background-color:gray">Menu</th>
<tr><td class="has-dummy-text"><p style="padding:10px;" class="dummyTekst">Drop content</p></td></tr>
</tbody>
That way you can manage cell's state by adding or removing the class via jQuery's .addClass() or .removeClass() methods, and then check if cell still has your initial dummy-text state by checking with .hasClass() method. (See jQuery class manipulation methods for more info).
If you want to make sure that your child 'p.dummyTekst' is there and also not empty, you should use the .is() from jquery UI. Just to be sure and avoid flying eggs and stuff :P. Also, to place text in the P, use .append.
$jQ('.required > tbody > tr > td').each(function(index){
if( $jQ(this).children('p.dummyTekst').is(":empty") ) {
$jQ(this).children('p.dummyTekst').append("Your text here");
}
});
Please note that browsers can mess around with this, if you have problems using the .is(":empty") try to use $.trim() from jQuery. If he can't trim ( $.trim() ), the element should be empty.
$jQ('.required > tbody > tr > td').each(function(index){
if ( !$jQ(this).children('p.dummyTekst').trim() ) {
$jQ(this).children('p.dummyTekst').append("Your text here");
}
});
I'd try something on the line of this (I don't know JQuery very well, but I do know some JavaScript, and maybe you can convert it; sorry if it isn't helpful.
function checkTemplate() {
var dummy = document.getElementByClassName(dummyTekst);
if(dummy.innerHTML == "s") {
[Your Continue Function]
}
else {
alert(You must have the dummy text!)
}
}

Categories