I have some code :
<table>
<tbody>
<tr>
<td id='myTdId'>
<input type='text' value='some value' />
</td>
</tr>
...
</tbody>
<table>
I want to get innerHTML of myTdId td element and get value of text input. Is it possible?
for example :
var tdInnerHTML = document.getElementById('myTdId').innerHTML;
// convert this to element operation and access to value of it ...
console.log(tdInnerHTML.value); // :(
please help me, THANKS...
EDIT :
I do not access to input text!
How about using childNodes to navigate?
It is an array containing nodes of contained elements.
In your case...
var tdInputVal = document.getElementById('myTdId').childNodes[0].value;
console.log(tdInputVal ); // :(
Can you add Id on the input itself?
<table>
<tbody>
<tr>
<td id='myTdId'>
<input type='text' value='some value' id="myInput" />
</td>
</tr>
...
</tbody>
<table>
Then access it via
var input = document.getElementById('myInput').value;
Or access it via tag
var input = document.getElementsByTagName("input")[0].value;
Alternative clear way is to have id or class on your HTML so you can get inner value easily.
For example
HTML:
<input id="text-input" value="">
Javascript
var inputValue = document.getElementById('text-input').value;
console.log(inputValue);
jQuery version
var inputValue = $('#text-input').val();
Hope this helps.
I dont think you need to call innerHTML on that element. You need to get child of the td element with id "myTdId". To do that you can use
var tdElement = document.getElementById('myTdId');
console.log(tdElement.children[0].value);
This should get you the value of the td Element without the need of setting id or class to the td element.
I am assuming you have only one element inside the td;
I did not test the code but it should work.
Use getElementById than use on result object also getElementBy_XXX .
If you use getElementsByClassName or TagName you will get array of child element.
//ELEMENT
var tdElement = document.getElementById('myTdId');
// INNER HTML
var tdInnerHTML = document.getElementById('myTdId').innerHTML;
var childElement = tdElement.getElementsByTagName("input");
//if td is only and always first element than we can use :
//childElement[0]
alert(childElement[0].value)
<table>
<tbody>
<tr>
<td id='myTdId'>
<input type='text' value='some value' />
</td>
</tr>
</tbody>
<table>
<script>
// I dont use this function but you can if you want
function getElementInsideElement(baseElement, wantedElementID) {
var elementToReturn;
for (var i = 0; i < baseElement.childNodes.length; i++) {
elementToReturn = baseElement.childNodes[i];
if (elementToReturn.id == wantedElementID) {
return elementToReturn;
} else {
return getElementInsideElement(elementToReturn, wantedElementID);
}
}
}
</script>
// Use querySelector
var input = document.querySelector('#myTdId input');
var val = input.value;
Related
i have a site where i paste my entire source code into a box and update all the td tags with a background color if there isnt currently a "bgcolor" attribute.
I've been messing with this for some time but i can't get my ogSource to update. I've tried many ways such as assigning new variables, returns etc etc. No luck.
the below code properly scans for the appropriate td and adds the background color, it just doesnt apply it to the ogSource. I've removed all my other code to make this as basic as possible.
Can anyone assist with this?
Thanks in advance.
var ogSource = '<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>'
ogSource.replace(/\<td(.*?)\>/g, function(matches) {
if (!matches.includes('bgcolor')) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
matches = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
}
}
});
console.log(ogSource);
EDIT/UPDATE
After a lot of messing around- this was a solution that was able to capture all the source code pasted and make the modification needed.
ogSource = ogSource.replace(/\<td(.*?)\>/g, function( matches , i ) {
var idx = matches.lastIndexOf(">");
if (idx > -1) {
if (!matches.includes('bgcolor')) {
ogSource = matches.substr(0, idx) + " bgcolor='pink'" + matches.substr(idx);
} else {
ogSource = matches;
}
} return ogSource;
});
console.log(ogSource);
My initial answer was off the mark but quite a bit, however, I think regex in general may not be the best solution due to the amount of edge cases present and the DOMParser might be a better solution for this.
Essentially, you pass the html string into the DOMParser method parseFromString and store that in a variable, then select all td elements and check if they have a bgColor attribute, if they don't, give them one, then output the new DOM string.
Here's an example:
const domParser = new DOMParser();
const DOM = domParser.parseFromString(`<table id="test1"> <tr> <td> <table id="test2"> <tr> <td> </td> </tr> </table></td> </tr> </table>`, "text/html");
// Find all tds
const tds = DOM.querySelectorAll("td");
for(let i = 0; i < tds.length; i++) {
let currentTD = tds[i];
if(!currentTD.hasAttribute("bgColor")) {
currentTD.setAttribute("bgColor", "someValue");
}
}
console.log(DOM.body.innerHTML); // If you only want to return the table content
console.log(DOM.querySelector("html").innerHTML); // If you want all of the html code that was added
My goal is to go through a table and append a new <tr> with the same data as it's previous sibling but with some altered content text.
A section of my html is as follows:
<tr>
<td><label>Share - Spanish</label></td>
<td><input type="text" id="blog_share_es" name="blog_share_es" size="30" /></td>
</tr>
Within my current function in Javascript the $(this) is the <label> tag. I have successfully taken the word "Spanish" and replaced it with "Italian" with the following:
var italian = $(this).text().replace("Spanish", "Italian");
and then append it to the table as follows:
var parentDiv = $(this).parent().parent();
$('<tr><td><label>'+italian+'</label></td><td><input type="text" id="logout_de" name="logout_de" size="30"/></td></tr>').insertAfter(parentDiv);
How do I now select the <input> and replace all instances of "_es" within the id and name with "_it" so that I get the following output in html (getting the formatting of the html is not necessary but would be optimal!):
<tr>
<td><label>Share - Italian</label></td>
<td><input type="text" id="blog_share_it" name="blog_share_it" size="30" /></td>
</tr>
Turned into a plug-in
DEMO
(function ($) {
$.fn.newRow = function (language, suffix) {
$lastSibling = this.find("tr").last().clone();
$label = $lastSibling.find("label");
$labelText = $label.text();
$label.text($labelText.replace($labelText.substring($labelText.indexOf("- ") + 2), language));
$input = $lastSibling.find("input");
$id = $input.attr("id");
$name = $input.attr("name");
$input.attr("id", $id.replace($id.substring($id.lastIndexOf("_") + 1), suffix))
.attr("name", $name.replace($name.substring($name.lastIndexOf("_") + 1), suffix));
this.find("tbody").append($lastSibling);
return this;
};
})(jQuery);
$("#yourTable").newRow("Italian", "it");
something like this... not sure if it 100% works, but gives you right direction
$('input[type=text]').each(function(input) {
if (input.attr('id').match(/_it/))
input.attr('id', input.attr('id').replace(/_it/, '_es');
if (input.attr('name').match(/_it/))
input.attr('name', input.attr('name').replace(/_it/, '_es');
})
To select the input starting from $(this) you have to use the function find(), and then you can change the attributes using the function attr()
var inp = $(this).parent().parent().find("input[type=text]");
inp.attr("id", inp.attr("id").replace("_es","_it"));
inp.attr("name", inp.attr("name").replace("_es","_it"));
I have html that looks like this,
<table id="TableAddresses">
<tbody>
<tr>
<td>
string 1
</td>
<td>
<input type="hidden" id='ADDR_843886'
<div id='FLAG_843886'>Pending...</div>
</td>
</tr>
<tr>
<td>
string 2
</td>
<td>
<input type="hidden" id='ADDR_843886'
<div id='FLAG_843886'>Pending...</div>
</td>
</tr>
How do I get all the strings inside of TableAddresses > tbody >tr > td[0]?
EDIT:
I was mistaken in tagging jquery. This is actually a asp.net project.
An easy way would be to use querySelectorAll
var td = querySelectorAll("#TableAddresses tbody td")[0];
Otherwise you can do
var table = document.getElementById("TableAddresses");
var tbody = table.getElementsByTagName("tbody")[0];
var tr = tbody.getElementsByTagName("tr")[0];
var td = tr.getElementsByTagName("td")[0];
// etc
You can try this:
document.getElementById('TableAddresses').firstChild.firstChild.firstChild.innerHTML
or with less legacy support:
document.querySelector('#TableAddresses td').innerHTML
You can use the map method:
var strings = $('#TableAddresses td:first-child').map(function() {
return $.trim( this.textContent || this.innerText );
}).get(); // ["string 1", "string 2"]
Alternatively you can read the HTMLTableElement's rows property:
var rows = document.getElementById('TableAddresses').rows,
strings = [];
for (var i = 0; i < rows.length; i++) {
if ( rows[i].cells[0] ) {
strings.push( rows[i].cells[0].innerHTML );
}
}
http://jsfiddle.net/kvyUh/
Using jQuery:
var myString = $('#tableAddress td:first').text()
Cheers!
There's an MDN article on this topic. In a nutshell, you need to traverse your table with standard means, mostly getElementsByTagName, see this jsBin (look in the console).
var table = document.getElementById("TableAddresses");
var rows = table.getElementsByTagName("tr");
Array.prototype.forEach.call(rows, function(ele, idx) {
console.log(ele.getElementsByTagName("td")[0].textContent.trim());
});
This snippet traverses each row of your table and outputs the textContent of the first <td> element. Please note that this will most likely not work out of the box on older IE versions iirc, but nothing that can't be shimmed. ;-)
I've done some code in html and in JavaScript ... My query is when I click on <td>, whatever the value associated with it, has to be displayed in the corresponding text box ...
In front of <td> I've taken the textbox ... for an example I've taken 3 <td> and 3 textboxes
<script type="text/javascript">
function click3(x) {
x = document.getElementById("name").innerHTML
var a = document.getElementById("txt");
a.value = x;
}
function click1(y) {
y = document.getElementById("addr").innerHTML
var b = document.getElementById("txt1");
b.value = y;
}
function click2(z) {
z = document.getElementById("email").innerHTML
var c = document.getElementById("txt2");
c.value = z;
}
</script>
this is my JavaScript code , I know this is not an adequate way to deal such problem, since its giving static way to deal with this problem
does anyone have a better solution for this problem ??
In JavaScript/jQuery
If click1, click2 and click3 are supposed to be three event then you have to keep all three function you can shorted the script code for assigning values to text field.
<script type="text/javascript">
function click3(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
}
function click1(y) {
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
}
function click2(z) {
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
</script>
You can make a single function if you have single click event and shorten the code for assignment like this,
function SomeClick(x) {
document.getElementById("txt").value = document.getElementById("name").innerHTML;
document.getElementById("txt1").value = document.getElementById("addr").innerHTML;
document.getElementById("txt2").value = document.getElementById("email").innerHTML;
}
As far as I understood your question, you could try the following, assuming that's how your HTML is structured:
HTML Markup:
<table id="mytable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Email</th>
</tr>
<tr>
<td class="name">Tom</td>
<td class="addr">789</td>
<td class="email">tom#dot.com</td>
</tr>
<tr>
<td class="name">Dick</td>
<td class="addr">456</td>
<td class="email">dick#dot.com</td>
</tr>
<tr>
<td class="name">Harry</td>
<td class="addr">123</td>
<td class="email">harry#dot.com</td>
</tr>
</table>
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<input id="txt3" type="text" />
jQuery:
$(".name").click(function(){
$("#txt1").val($(this).text());
$("#txt2").val($(this).nextAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(1).text());
});
$(".addr").click(function(){
$("#txt2").val($(this).text());
$("#txt1").val($(this).prevAll().eq(0).text());
$("#txt3").val($(this).nextAll().eq(0).text());
});
$(".email").click(function(){
$("#txt3").val($(this).text());
$("#txt2").val($(this).prevAll().eq(0).text());
$("#txt1").val($(this).prevAll().eq(1).text());
});
DEMO: http://jsfiddle.net/Z9weS/
You can combine columns and rows. Per cell consisting id you give it th column title and
number of series it could be the index of the row combination of row and column gives the
address as per table cell by a specific event you can read the value of the id
Then you know to pull the cell value.
$('tr')
.click(function() {
ROW = $(this)
.attr('id');
$('#display_Colume_Raw')
.html(COLUME + ROW);
$('#input' + COLUME + ROW)
.show();
STATUS = $("#input" + COLUME + ROW)
.val();
});
<table>
<tr id ="tr_id_1">
<td >
Blah
</td
<td>
Blah
</td>
</tr>
<tr id ="tr_id_2">
<td>
Blah
</td>
<td>
Blah
</td>
</tr>
</table>
i have got the id of first tr using jquery
var first_tr_id = tr_id_1 // id of first tr
now by using this id how to get the id of next tr
i have tried like this
var nextId = ('#'+first_tr_id ).next("tr").attr("id");
but its giving ("#" + row_id).next is not a function error ..
You code lacks the jQuery $
var nextId = $('#'+first_tr_id ).next("tr").attr("id");
Also an id is a string, so you should set your variable like so :
var first_tr_id = 'tr_id_1'; // id of first tr
you should try in this way..
var nextId = $('#'+first_tr_id ).next("tr").attr("id");
You have a problem in assigning a variable:
var first_tr_id = tr_id_1
it should be inside quote
var first_tr_id = "tr_id_1"
Also, to get all the IDs, you can use the following code:
$("table tr").each(function(index) {
alert($(this).id());
}