Keeps returning [object HTMLSpanElement]? (Javascript) - javascript

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).

Related

Parse text from HTML form inside table cell with Cheerio

I have a HTML table that looks like this:
<tr class="row-class" role="row">
<td>Text1</td>
<td>
<form method='get' action='http://example.php'>
<input type='hidden' name='id_num' value='ABCD123'> <!-- < I NEED THIS VALUE -->
<button type='submit' class='btn' title='Check' ></button>
</form>
</td>
</tr>
I want to get the value of the hidden input type named id_num. (In this example the value I want is "ABCD123").
I tried to parse the code with cheerio like this:
var $ = cheerio.load(body);
$('tr').each(function(i, tr){
var children = $(this).children();
var x = children.eq(0);
var id_num = children.eq(1);
var row = {
"x": x.text().trim(), //this is correct, value is Text1
"id_num": id_num.text().trim() //This is empty, value is "", I want the value "ABCD123"
};
});
But I only get the first value correct.
How can I get the value from the hidden input element id_num?
Thanks.
That should be:
$(tr).find('[name="id_num"]').attr('value')
Your eq(1) was getting the whole <tr>, try this instead:
$('tr').each(function(i, tr){
var children = $(this).children('td');
var x = $(children[0]);
var id_num = $(children[1]).find("input[name='id_num']");
var row = {
"x": x.text(),
"id_num": id_num.val()
};
}

Javascript element name change reverting back to original

JavaScript name change of cloned input element "terminal0" isn't saving and/or reverting back to original name after function ends. All other name/id changes work but first element name change reverts back after function completes. Even the first element "terminal0" id change works successfully. I've tested and confirmed name change does work before function exits by placing an alert(cTerm.name) at the end of it. Anyone know reason why name change isn't working for first input element?
<tr id="tr1">
<td id="tr1Td0">
Terminal <input type="checkbox" name="terminal0" id="terminal0" value="0" onClick="cbUpdate()">
<br>
Imager <input type="checkbox" name="imager0" id="imager0" value="0" onClick="cbUpdate()">
</td>
</tr>
</tbody>
</table>
function addTable()
{
var gssTable = document.getElementById("gssTable");
var currTables = gssTable.rows[0].cells.length;
var selNum = document.getElementById("sNum").value;
var tr0 = document.getElementById("tr0");
var tr1 = document.getElementById("tr1");
var br = document.createElement('br');
for(x=currTables; x < selNum; x++)
{
var tr0Td0 = tr0.insertCell(-1);
var setID0 = document.getElementById("setID0");
var cSetID = setID0.cloneNode(true);
cSetID.id = "setID" + x;
cSetID.name = "setID" + x;
tr0Td0.appendChild(cSetID);
var tr1Td0 = tr1.insertCell(-1);
tr1Td0.innerHTML="Terminal";
var terminal0 = document.getElementById("terminal0");
var cTerm = terminal0.cloneNode(true);
cTerm.id = "test" + x;
cTerm.name = "test" + x;
tr1Td0.appendChild(cTerm);
tr1Td0.appendChild(br);
tr1Td0.innerHTML = tr1Td0.innerHTML + "Imager"
var imager0 = document.getElementById("imager0");
var cImager = imager0.cloneNode(true);
cImager.id = "imager" + x;
cImager.name = "imager" + x;
tr1Td0.appendChild(cImager);
}
while (currTables > selNum)
{
tr1.deleteCell(-1);
tr0.deleteCell(-1);
currTables = currTables - 1;
}
Setting the innerHTML makes the browser re-render that element and its contents. Since you are doing it each iteration of the loop, you are probably causing a race condition where innerHTML hasn't been updated to the latest effects of the appendChild calls above it.
So instead of setting innerHTML each time you can just create a Text node, with createTextNode, and append it.
tr1Td0.appendChild(document.createTextNode("Imager"));

Accessing row element of table in Javascript

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.)

How to delete a created element in JavaScript?

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.

storing user input in array

I need to do the following (I'm a beginner in programming so please excuse me for my ignorance): I have to ask the user for three different pieces of information on three different text boxes on a form. Then the user has a button called "enter"and when he clicks on it the texts he entered on the three fields should be stored on three different arrays, at this stage I also want to see the user's input to check data is actually being stored in the array. I have beem trying unsuccessfully to get the application to store or show the data on just one of the arrays. I have 2 files: film.html and functions.js. Here's the code. Any help will be greatly appreciated!
<html>
<head>
<title>Film info</title>
<script src="jQuery.js" type="text/javascript"></script>
<script src="functions.js" type="text/javascript"></script>
</head>
<body>
<div id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="title">Title</label> <input id="title" type="text" >
<br>
<label for="name">Actor</label><input id="name" type="text">
<br>
<label for="tickets">tickets</label><input id="tickets" type="text">
<br>
<br>
<input type="button" value="Save" onclick="insert(this.form.title.value)">
<input type="button" value="Show data" onclick="show()"> <br>
<h2><b>Data:</b></h2>
<hr>
</div>
<div id= "display">
</div>
</body>
</html>
var title=new Array();
var name=new Array();
var tickets=new Array();
function insert(val){
title[title.length]=val;
}
function show() {
var string="<b>All Elements of the Array :</b><br>";
for(i = 0; i < title.length; i++) {
string =string+title[i]+"<br>";
}
if(title.length > 0)
document.getElementById('myDiv').innerHTML = string;
}
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push() method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
You have at least these 3 issues:
you are not getting the element's value properly
The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.
You can save all three values at once by doing:
var title=new Array();
var names=new Array();//renamed to names -added an S-
//to avoid conflicts with the input named "name"
var tickets=new Array();
function insert(){
var titleValue = document.getElementById('title').value;
var actorValue = document.getElementById('name').value;
var ticketsValue = document.getElementById('tickets').value;
title[title.length]=titleValue;
names[names.length]=actorValue;
tickets[tickets.length]=ticketsValue;
}
And then change the show function to:
function show() {
var content="<b>All Elements of the Arrays :</b><br>";
for(var i = 0; i < title.length; i++) {
content +=title[i]+"<br>";
}
for(var i = 0; i < names.length; i++) {
content +=names[i]+"<br>";
}
for(var i = 0; i < tickets.length; i++) {
content +=tickets[i]+"<br>";
}
document.getElementById('display').innerHTML = content; //note that I changed
//to 'display' because that's
//what you have in your markup
}
Here's a jsfiddle for you to play around.

Categories

Resources