This is my first attempt in Javascript, so may be this is fairly easy question.
I need to access row element of a table, each row contains checkbox and two other column. If checkbox is checked, i need to get the id of checkbox.
I made following attempt but element_table.rows returns undefined, therefore i could not proceed. I debugged using Inspect element tool of eclipse and found element_table contains the rows.
Please suggest where I am making a mistake.
Javascript code:
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table.rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].getElementsByName('checkmark');
if(checkerbox.checked){
selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name");
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
}
html code:
<table name="collection" border="1px">
<tr name="1">
<td><input type="checkbox" name="checkmark"></td>
<td>Tum hi ho</td>
<td>Arjit singh</td>
</tr>
<tr name="2">
<td><input type="checkbox" name="checkmark"></td>
<td>Manjha</td>
<td>Somesh</td>
</tr>
<tr name="3">
<td><input type="checkbox" name="checkmark"></td>
<td>Ranjhana</td>
<td>A.R Rehman</td>
</tr>
</table>
<input type="button" value="Check" onclick="myfunction3()">
here's a working version
function myfunction3(){
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for(var i =0 ; i < element_tableRows.length;i++)
{
var checkerbox = element_tableRows[i].cells[0].firstChild;
if(checkerbox.checked){
//selectedTr[selectedTr.length] = element_tableRows[i].getAttribute("name"); //not sure what you want with this
data = data + element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
http://jsfiddle.net/eZmwy/
jsfiddle for your example, your problem is mainly at when you getElementsByName you need to specify the index, also not that not all getElement methods are available in the table
i would also suggest you learn jQuery, this makes life easier, also not sure why you want to display the data as 1,2,3 the name on the tr... seems pretty strange to me
Actually this line
var element_table = document.getElementsByName('collection');
will return collection of elements. If you are sure that you have exactly one table with the specified name, try this approach:
var element_table = document.getElementsByName('collection')[0];
actually if you are using jQuery (very recommanded )
you can do something like
var idsArray = [];
$("[name=collection] tr td [type=checkbox]:checked").parent().each(function() {
idsArray .push($(this).attr('name'))
});
this answer related only to jQuery use (which is same as javascript only more compiled.)
Related
I'm having a some trouble getting the state of dynamically created checkboxes. I used the code below to add several checkboxes, with dynamic Id's, to the body.
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
html +=
`
<label class="checkbox" [attr.for]="'myCheckboxId' + i">
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
In another part of the code, I would like to get and/or set the state of the checkboxes but havent succeeded so far. I tried using the code below to achieve my goals, but "document.getElementById(...)" keeps returning "null".
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById("'myCheckboxId' + i").checked);
}
As you can see, I'd like to save the checkbox states in an array and use it, to reset the new states to the old ones (for example when a button is pushed).
So how should I be adding the states to this buffer array? What am I doing wrong in the code above? Tried several other things but none of those worked.
It looks like you just have a simple error in your code. What you're trying to do is something to the affect of:
id=myCheckboxName1
id=myCheckboxName2
id=myCheckboxName3
...
However, your code is not correct:
<input class="checkbox__input" type="checkbox" [name]="'myCheckboxName' + i" [id]="'myCheckboxId' + i">
It's interpreting the entire id as a string and not inserting the numeric value so it looks like this: myCheckboxIdi
Perhaps try the following:
var html = ...;
for(var i = 0; i < options.checkTextArray.length; i++)
{
var checkboxId = `myCheckboxId${i}`;
html +=
`
<label class="checkbox" [attr.for]=${checkboxId}>
<input class="checkbox__input" type="checkbox" [name]=${checkboxId} [id]=${checkboxId}>
<div class="checkbox__box"></div>${options.checkTextArray[i]}:
</label>
<br>
`;
}
Notice how the value is now inserted in the string via the template string? This should work, but I didn't run it so it may need some modification. Your new code for accessing would be something like:
var ckbStateBuffer = new Array();
var txtContenBuffer = new Array();
for(var i = 0; i < options.checkTextArray.length; i++) {
ckbStateBuffer.push(document.getElementById(`myCheckboxId${i}`).checked);
}
Something to this affect should fix your code. Let me know if you need more clarification.
Okay so I found a solution. Apparently you can't use getElementById(checkboxId) to get the checkbox states. You have to create an array using getElementsByTagName("input") and afterwards itterate through this array while checking for inputs of the checkbox type.
var inputsArray = document.getElementsByTagName("input");
var ckbStateBuffer = new Array();
for (var i = 0; i < 3; i++)
{
if(inputsArray[i].type == "checkbox")
{
ckbStateBuffer.push(inputsArray[i].checked);
}
}
JSFiddle here: https://jsfiddle.net/Maximo40000/agL9opq6/
A big thanks to Jarred Parr!
I need to retrieve date from the generic input field. The number of how many date (input field) user can create in form is unknown by me, so I count them by rowCount.
I'm not enable to extract the value of field (Syntax error maybe).
N.B when I lunch my code I get: Cannot set property '0' of undefined
html code:
<div>
<table id='dynamic_field_edit'>
<tbody>
<tr>
<td>Date</td>
<td><input type="text" placeholder="Enter date" /></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" placeholder="Enter date" /></td>
</tr>
</tbody>
</table>
</div>
JS code :
var arrayDate = [];
var rowCount = document.getElementById('dynamic_field_edit').rows.length;
console.log(rowCount);
var allInputs = document.querySelectorAll('input');
for (let i = 0; i < allInputs.length; i++) {
arrayDate.push(allInputs[i].value);
}
console.log(arrayDate);
Edit:
After all suggested change it works, but it retrieve all values from input in document.
You just need to initialize your array:
var arrayDate = [];
EDIT:
Seems to work in this sample, can you compare to your code?
https://jsfiddle.net/emeLdecm/1/
(I added a button to fire off your JS, just to demonstrate)
Y you use jQuery syntax in plain javascript?
Select your table via:
table = document.getElementById('dynamic_field_edit');
and that iterate:
for (var i = 0, row; row = table.rows[i]; i++) {
// do your stuff
};
I find a way to achieve what I wanted to do by doing this.
#proggrock solution is also good for retrieving all input values in the document.
var arrayDate = [];
var rowCount = document.getElementById('dynamic_field_edit').rows.length;
console.log(rowCount);
$("#dynamic_field_edit").find('input:text')
.each(function() {
arrayDate.push($(this).val());
});
console.log(arrayDate);
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. ;-)
Ok so im trying to add two (or more) variables and make it appear in a table cell.
I get the variables from lets say the 1st and 2nd cells and i want to display them on the 7th cell, so this is what i have for now.
This is the basic code for the cell that gets the info.
function prompta1()
{
var a1=prompt("Unesi broj","")
var spana1 = document.getElementById ("spana1");
spana1.innerHTML = a1;
function prompta2()
{
var a2=prompt("Unesi broj","")
var spana2 = document.getElementById ("spana2");
spana2.innerHTML = a2;
And this is the code for the cell that needs to show them.
function functiona7()
{
var a7= spana1+spana2;
var spana7 = document.getElementById ("spana7");
spana7.innerHTML = a7;
}
Now , when i try this it only gives.
[object HTMLSpanElement][object HTMLSpanElement]
Please help!
HTML for getting the values
enter code here <tr>
<td><h1>1</h1></td>
<td><input type="button" onclick="prompta1()" value="Izmeni"> <br> <span id='spana1'></span></td>
<td><input type="button" onclick="prompta2()" value="Izmeni"> <br> <span id='spana2'></span></td>
</tr>
<tr>
HTML for showing the value
<td> <input type="button" onclick="functiona7()" value="Izracunaj"> <br> <span id='spana7'></span> </td>
Try something like this:
function prompta1() {
var a1 = prompt("Unesi broj", "");
var spana1 = document.getElementById("spana1");
spana1.innerHTML = a1;
}
function prompta2() {
var a2 = prompt("Unesi broj", "");
var spana2 = document.getElementById("spana2");
spana2.innerHTML = a2;
}
function functiona7() {
var spana1 = document.getElementById("spana1").innerHTML;
var spana2 = document.getElementById("spana2").innerHTML;
var spana7 = document.getElementById("spana7");
if (!(spana1 && spana2 && spana7)) return;
var a7 = spana1 + spana2;
spana7.innerHTML = a7;
}
Fiddle
In your current example the values for spana1/2 are not pulling from the DOM, so first they need to be populated using getElementById, after that a simple combination of the Inner Html is all that is needed (although you may want to add a space in between too).
Hello I have a piece of code that allows me to add an author.
I have a problem, I can't seem to delete the created node in my table
This is the worst frustration in my life. I could not seem to delete it.
I also have notice that every time I inspected the element I could not see the
new created element from the source. But when I view it on firebug I can actually see it there.
Adding an input element and appending it on the table works fine for me.
I am just very new to JavaScript and to this web thingy and deleting a CREATED ELEMENT via .createElement is where I am stuck at.
here is my code
<script>
var ctr = 1;
function showTextBox()
{
// is the table row I wanted to add the element before
var target = document.getElementById('bef');
var tblr = document.createElement('tr');
var tbld1 = document.createElement('td');
var tbld2 = document.createElement('td');
var tblin = document.createElement('input');
tblin.name = 'Author' + ctr;
tblin.id = 'Author' + ctr;
tblin.placeholder = 'add another author';
tbld1.appendChild( document.createTextNode('Author' + ctr ) );
tbld2.appendChild( tblin );
tblr.appendChild( tbld1 );
tblr.appendChild( tbld2 );
target.parentNode.insertBefore( tblr , target );
ctr++;
}
function hideTextBox()
{
var name = 'Author'+ctr;
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
// viewing this code on source make the created elem to not appear
}
</script>
Am I doing something wrong? I really need help. This is for my project at school.
Is there any way I could delete it. I created that node and I want it to be deleted when I click something.
Also I prefer to stay with JS not with JQuery or other JStuff and I am disregarding compatibility for now because this is just a sample in my dummy form. I will deal on that later.
EDIT
In case you need the actual form here it is
<form enctype="multipart/form-data" action="process/" method="POST" />
<h3>Book Upload</h3>
<table border="2" id='tbhold'>
<tr>
<td>Title</td>
<td><input type="text" id="book_title" name="book_title" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" id="book_author" name="book_author" /></td>
</tr>
<tr id="bef">
<td colspan="2">
add author
remove
</td>
</tr>
</table>
</form>
Thank you very much!
Try this function:
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
Then you can do this:
removeElements(document.querySelectorAll('#tbhold tr'));
function hideTextBox(){
var name = "Author" + (ctr - 1);
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById(name);
var tr = cTarget.parentNode.parentNode;
tr.parentNode.removeChild(tr);
ctr = ctr - 1;
}
Here is a demo
every time I inspected the element I could not see the new created element from the source. But when I view it on firebug I can actually see it there.
If you change the DOM, you of course do not change the HTML source markup. Only the DOM inspector will show you the changes.
var name = 'Author'+ctr;
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
Yes, you created it using your showTextBox function. But that did also increment the ctr to 2, so that you now are looking for Author2 which obviously does not exist. So put a ctr--; before it and it should work.