Extract text in table cell before input field - javascript

I have some HTML of the form:-
<table>
<tr>
<td>Text for input 1<br/><div>Lots of textual data</div><input id="field1" class="mandatory"/></td>
<td>Text for input 2<br/><input id="field2" class="mandatory"/></td?
<td>Text for input 3<br/><input id="field3"/></td>
</tr>
</table>
(but with many more fields & rows).
I'm iterating through the mandatory class and, where the input field is empty, I want to display the text preceding the <br/> but not anything else.
Using:-
$(this).parent().text();
only works up to a point because it also displays the text in the <div>
Is there a way that I can limit the text to just that before the <br/>?

I think what you are looking for is .contents()
$(this).parent().contents().eq(0).text();
Demo: Fiddle

You may update your HTML markup to keep your message in a span tag with a special css class which you can use to make your jQuery selection more easier.
<table>
<tr>
<td><span class="msg">Text for input 1</span><br/>
<div>Lots of textual data</div><input id="field1" class="mandatory"/>
</td>
</tr>
</table>
and now use the closest method to get the parent td and use the find method to get the span
$(".mandatory").each(function(index,item){
var msg=$(this).closest("td").find("span.msg").html();
//do something with msg now
});
Here is a working sample http://jsbin.com/oDUPujOl/1/

Time for some plain JS, as jQuery doesn't really play well with textnodes:
var text = this.parentNode.firstChild.nodeValue.trim();
FIDDLE

You can clone your target TD and remove the elements which are with unnecessary text. Now you easily fetch the required text from that TD. For reference please read this : .clone()
Try this one,
$("#field1").keyup(function(){
var xClone = $(this).parent().clone();
xClone.find('div').remove();
alert((xClone).text());
});
DEMO

Related

How to identify xpath of an element which do not have any attribute information

I want to identify an element which is a text "My Portal" from td tag. Below is my HTML
<tbody>
<tr>
<td>
<!-- rendered always true, custom column names are also label -->
My Portal
<!-- rendered always false, this feature is not required -->
</td>
</tr>
</tbody>
I have tried below xpaths as shown below, but none of them works:
1. .//td[text()="My Portal"]
2. .//td[contains(text(),"My Portal")]
After some search in the internet I found normalize-space() method which will remove the trailing and unnecessary white spaces. I have tried the method using the below xpath
.//td[normalize-space()="My Portal"]
Am able to identify the element, but in the firebug it is showing as 2 matching nodes. Please find the attachment for the highlighted elements in the firebug
My questions are:
Why two tags are getting highlighted?
Why .//td[contains(text(),"My Portal")] does not work?
How to identify the "My Portal" uniquely?
Can anyone please help?
There are several solutions. An efficient approach is to specify the exact path from the root node to the td you want. Something like
/html/body/table/tbody/tr/td/table/tbody/tr/td[normalize-space()='My Portal']
If you know that there are no more than two nesting tables, you can shorten this to
//td//td[normalize-space()='My Portal']
If you want the td in the innermost table regardless of table structure, try
//td[not(.//table) and normalize-space()='My Portal']
This isn't very efficient though. If you know that the text "My Portal" appears in an immediate text child of td, try
//td[text()[normalize-space()='My Portal']]
To uniquely identify the second td, what you have to do is add an additional filter. So if you look at the difference between the 2 tags highlighted, the parent has a class and the child doesn't. So if you need the second td, the xpath would be //td[normalize-space()='My Portal' and not(#class='rich-table-cell')]
If you need the parent then: //td[normalize-space()='My Portal' and #class='rich-table-cell']
Instead of using text() try .
.//td[contains(.,"My Portal")]
To Answer your questions:
1- Because you are using a global selector, "//", with this selector XPAth will find all the elements into the tree, so if you want select only one td you should specific the path, something like this
/table/tbody/table/td[contains(text(),"My Portal")]
2- The command that you are using it should work, I already tried, check your path again, maybe you are not selecting his parent or you are starting from the wrong path.
function xpath(){
var input = document.getElementById("xpath").value
var cell = document.evaluate( input, document, null, XPathResult.ANY_TYPE, null );
var cellvalue = cell.iterateNext();
console.log(cellvalue);
alert(cellvalue.data);
};
<html>
<head>
</head>
<body>
<input type="text" id="xpath" value='//body/table/tbody/tr/td/table//td[contains(text(),"My Value")]/text()'/> <input type="button" onclick="xpath()" value="Execute"/>
<table>
<tbody>
<tr>
<td>
<table>
<tbody>
<tr>
<td>
My Value
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Jquery select first parent of <td> tag in HTML table

I'm using Jquery V1.11.1 in my application. I have a HTML table which looks like this:
<table id="permissions">
<tr>
<td></td>
<th>Administrators</th>
<th>Moderators</th>
</tr>
<tr>
<th class="aco">controllers/users/display</th>
<td class="permission">Allowed</td>
<td class="permission">Denied</td>
</tr>
</table>
When you click on "Allowed" or "Denied" I want to select the TH tag which contains the ACO.
I thought this would do it, but it doesnt. $(this).parent('th').text();
What is the best way to select the TH tag using Jquery in this situation?
Use
$(this).closest('tr').find('th.aco').text();
DEMO
or
$(this).siblings('th.aco').text();
DEMO
Use .siblings() in jquery
$(this).siblings('th.aco').text();
$('.permission').on('click', function(){
$(this).siblings('.aco').text();
})
or if more than one siblings has this class .aco
$('.permission').on('click', function(){
$(this).siblings('th.aco').text();
})
will select the th that is parallel to the clicked td and display it's text. You can perform a different function on selected th instead of .text().

Get ID of first cell in a specific table

Given,
<table id=ThisTable>
<tbody>
<tr>
<td id="ThisCell">
</td>
</tr>
<tr>
<td id="NotThis">
</td>
</tr>
<tr>
<td id="NorThis">
</td>
</tr>
</tbody>
</table
How can I use JQuery/Javascript to assign the ID of the first table cell in #ThisTable to the variable "Selected"?
The result in this case should look like:
var Selected = "ThisCell";
I need to get the first cell's ID without having any knowledge of what the ID is, probably using the :first selector. In addition, this isn't the only table on the page, so it must be referenced with its ID.
var Selected = $('#ThisTable td:first').attr('id');
This selects the first td element that is a descendant of the element with ID ThisTable, returns its id attribute and assigns it to Selected.
JSFiddle
Just:
$("#ThisTable tbody tr:first td:first").attr("id");
This code gets the first td of your table, then stores its id in a variable Selected.
var Selected = document.querySelector("#ThisTable td").id;
Pure DOM methods, fastest method here, and works on 91.71% of browsers according to Can I use.
$(function () {
console.log($($('#ThisTable').find('td')[0]).attr('id'))
});
http://jsfiddle.net/E9mPw/17/

how to select the first td

My Html is bellow.
<tr class="success">
cfgdfgh
<td>1</td>
<td>home1</td>
<td>home1</td>
<td>home1</td>
<td>
<input class="btn btn-mini btn-danger deleteMenu" type="button" value="Delete" name="delete">fgfg</td>
</tr>
My Jquery code is bellow
$(".deleteMenu").click(function(){
$(this).parent().css("color","red");
});
I tried that using above jquery code but no luck.I want to selete first td ?
DEMO
Try:
$(".deleteMenu").click(function () {
$(this).closest('tr').find('td:first').css("color", "red");
});
jsFiddle example
With your selector, .parent(), you're selecting the cell that contains the button. One way to accomplish what you want it to traverse up the DOM to the row (.closest('tr')) and then back down to the first cell (.find('td:first')).
BTW on a side note, in your example, the text cfgdfgh isn't valid where you have it.
1) Start by writing valid HTML
2) Go up the DOM tree until u get to the row element, for that you should use .closest()
3) Find the first child of that row element
4) Apply whatever style changes you want
Fiddle: http://jsfiddle.net/u4A7V/7/
Code:
$(".deleteMenu").click(function () {
$(this).closest("tr") // go up the tree
.find("td:first-child") // find the first child
.css("color", "red"); // change color
});
It's pretty easily done this way:
$(".parentClass").find("td:eq(0)")... /* :eq(0) = first occurance */
Also your HTML Markup is erroneous.
The easiest approach would be to assign a class to the . I don't know if it's possible to assign an id to a (probably possible).
This will get the first td in the row:
$(".deleteMenu").click(function(){
$('.success td').eq(0).css("color","red");
});
Hopefull this helps:
http://jsbin.com/eruric/1/edit
$(".success").find("td:first").css("background-color", "red");
Your HTML is not valid, you lack a '' tag and you have text outside the <td>s, change it to this:
<table>
<tr class="success">
<td>1</td>
<td>home1</td>
<td>home1</td>
<td>home1</td>
<td>
<input class="btn btn-mini btn-danger deleteMenu" type="button" value="Delete" name="delete">fgfg</td>
</tr>
</table>
and then your js to:
$(".deleteMenu").click(function(){
$(this).parent().siblings(':eq(0)').css("color","red");
});
JSFiddle Demo
Here we are:
$(".deleteMenu").click(function(){
$(this).closest('tr').find('td').first().css("color","red");
});
$(".deleteMenu").parent() will choose the parent of that input, which is the TR. Also, don't include code straight in the TR, use TD or TH and put it inside. So after putting it in its own TD, you're looking for
$(".deleteMenu").click(function(){
$(this).parents("tr").find("td").first().css("color","red");
});
You can use :first-child.
I assume myTable is an Id of table
$("#myTable tr td:first-child").css("color","red");
Js Fiddle
Please change your markup as well.
tr elements can only have td no text. You have write text in tr element.

jquery not picking up html

So I have the following HTML
<div class="tmpl" id="query_tmpl">
<tr>
<td></td>
<td class="primary_email"></td>
</tr>
</div>
and the following JS:
console.log($('#query_tmpl').html());
For some reason this only logs the 'a' tag. (Ex: http://jsfiddle.net/L8RQq/ )
Why does this happen and how do I get around it so that I can properly pick up the tr/td? I'm using jQuery 1.9.2 if that makes any difference.
Update:
Yes, the markup is 'bad html', but the whole point of this question is how to get around that. Using the HTML present and without altering it, how can I grab the contents even though it's 'bad'?
You don't have table tags around your tr. Try this:
<div class="tmpl" id="query_tmpl">
<table>
<tr>
<td></td>
<td class="primary_email"></td>
</tr>
</table>
</div>
This will log the div's contents properly.
the reason it wasn't logging, is because the browser sees some invalid tr and td tags, and removes those, because they can only be in a table, leaving you with only the a.
If you can't change the markup, tell the person / company that wrote that markup to fix it. It's invalid HTML.
Make it like this
<table class="tmpl" id="query_tmpl">
<tr>
<td></td>
<td class="primary_email"></td>
</tr>
</table>
Then it will surely work correctly
If you want to pick up tr's or td's you can use css manipulation functions such as children([selector]) where selector is eventually a class

Categories