JavaScript: text element returning "undefined" - javascript

I'm trying to retrieve the entered text in each textbox, by querying and looping through by ID tag.
But when I print what I have retrieved it outputs "undefined".
Looks like your post is mostly code:
</head>
<body bgcolor="#E6E6FA">
<font color=black size=+3>Modifying Sentiment</font>
<table>
<tr>
<td>Text to Save:</td>
</tr>
<tr>
<td colspan="3">
Add positive adjective:
<img Adjective src="http://findicons.com/files/icons/2776/android_icons/96/ic_question_mark.png" alt="question" title="Adjective: is a word naming an attribute of a noun, such as sweet, red, or technical."
width=20 />
<br>
<textarea cols=40 rows=3 id="textbox" ></textarea>
<textarea id="textbox" style="width:512px;height:256px"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button>
<td>
</tr>
</table>
<script type='text/javascript'>
function saveTextAsFile(){
var textBoxes = document.querySelectorAll('textbox');
var textToWrite;
for(var i in textBoxes){
textToWrite = textBoxes[i].value;
window.alert(textToWrite);
}
var textToWrite = document.getElementById("textbox").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
}
</script>

I have edited your javascript to point to textarea instead of textbox.
I also modified your for loop as I was getting additional outputs in the console. I also changed your alert to a console.log as jsbin was throwing an error of possible endless loop.
Try this:
function saveTextAsFile()
{
var textBoxes = document.querySelectorAll('textarea');
var textToWrite;
for(var i = 0; i < textBoxes.length; ++i){
textToWrite = textBoxes[i].value;
console.log(textToWrite);
}
textToWrite = document.getElementById("textarea").value;
var textFileAsBlob = new Blob([textToWrite],{type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
}

Trying using #textbox as this refers to the ID of the dom elements

Actually each id value in an html document should be unique. In your HTML code, I can see two id parameter with the same value "textbox". Try to change the first to "textbox-1" or whatever make sense to you but don't repeat the same value for id property and it should work.

Related

Why are cell name attributes undefined in my code

I have a problem with the code below. There are 4 visible elements here: 2 table cells, and 2 input text boxes. The last input text box displays the name of any of the first 3 elements clicked (the 2 cells and the first input box). Onclick of any of the first 3 elements will call the now() function with a "this" parameter (now(this)).
The now function then assigns the name of the clicked element to elemName variable, change the clicked element's background to blue, and make the value of the last text box to be assighened the elements name. Why is the cell name always undefined when anyone is clicked? Copy and try out the code. I need answers pls.
<html>
<head>
<script>
function now(elementa){
elemName=elementa.name;
elementa.style.backgroundColor = 'blue';
document.getElementById("clickedElementName").value=elementa.name;
} //end of now() function
</script>
</head>
<body>
<table border="1" >
<td name="cell1" onclick="now(this)">cell 1</td>
<td name="cell2" onclick="now(this)">cell 2</td>
</table><br>
<input value=mdfkjkjei name="input" onclick="now(this)" type=text />
<br><br>
clicked elements name:<input id="clickedElementName" type=text />
</body>
</html>
when the cells are clicked, the last input text box is suppose to display its html name attribute, but it displays undefined. But when i click the first input text box it displays its name (input).
Why is the name of the table cells undefined.
Are table cells not allowed to have a name attribute in html?
td elements have no name attribute, and consequently they have no name reflected property. If you use the name attribute (which is invalid), you can get its value via getAttribute("name"):
function now(elementa) {
var elemName = elementa.getAttribute("name"); // ***
elementa.style.backgroundColor = 'blue';
document.getElementById("clickedElementName").value = elemName; // ***
} //end of now() function
<html>
<head>
<script>
function now(elementa) {
var elemName = elementa.getAttribute("name");
elementa.style.backgroundColor = 'blue';
document.getElementById("clickedElementName").value = elemName;
} //end of now() function
</script>
</head>
<body>
<table border="1">
<td name="cell1" onclick="now(this)">cell 1</td>
<td name="cell2" onclick="now(this)">cell 2</td>
</table><br>
<input value=mdfkjkjei name="input" onclick="now(this)" type=text />
<br><br> clicked elements name:<input id="clickedElementName" type=text />
</body>
</html>
(Also note I declared the elemName variable, so you're not falling prey to The Horror of Implicit Globals [that's a post on my anemic little blog].)
But if you're going to put non-standard attributes on elements, use the data- prefix:
<td data-name="cell1" ..>
function now(elementa) {
var elemName = elementa.getAttribute("data-name"); // ***
elementa.style.backgroundColor = 'blue';
document.getElementById("clickedElementName").value = elemName;
} //end of now() function
<html>
<head>
<script>
function now(elementa) {
var elemName = elementa.getAttribute("data-name"); // ***
elementa.style.backgroundColor = 'blue';
document.getElementById("clickedElementName").value = elemName;
} //end of now() function
</script>
</head>
<body>
<table border="1">
<td data-name="cell1" onclick="now(this)">cell 1</td>
<td data-name="cell2" onclick="now(this)">cell 2</td>
</table><br>
<input value=mdfkjkjei name="input" onclick="now(this)" type=text />
<br><br> clicked elements name:<input id="clickedElementName" type=text />
</body>
</html>
user interaction element only have default name attribute like input,select,button.td not have that.so get the name via getAttribute() function in dom
function now(elementa){
elemName=elementa.name;
elementa.style.backgroundColor = 'blue';
document.getElementById("clickedElementName").value=elementa.getAttribute('name');
}
<table border="1" >
<td name="cell1" onclick="now(this)">cell 1</td>
<td name="cell2" onclick="now(this)">cell 2</td>
</table><br>
<input value=mdfkjkjei name="input" onclick="now(this)" type=text />
<br><br>
clicked elements name:<input id="clickedElementName" type=text />

how to access contents of a text box using name of the input text box element in javascript?

function display() {
var x = document.nid.value;
//document.body.innerHTML=x;
document.write(x);
}
<head>
<meta charset="ISO-8859-1">
<title>Print Reverse of a number</title>
</head>
<body>
<table>
<tr>
<td>
Enter number
</td>
<td>
<input type="number" size="20" name="nid">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="submit" onclick="display()">
</td>
</tr>
</table>
</body>
Your should replace
var x = document.nid.value
By
x = document.getElementsByName("nid")[0].value;
var yourinputs = document.getElementByName("nid")
this will return an array of elements. Since you need the first one, you can choose the 0th element of array
var input_val = yourinputs[0].value;
or simply in one line as
var input_val = document.getElementByName("nid")[0].value;
You can use document.getElementsByName(name) to select all nodes by name. It will return an array, take the node for which you want to retrieve value and use value method.
function logValue() {
console.log(document.getElementsByName("nid")[0].value);
}
<input type="number" size="20" name="nid" onchange="logValue()">
var inputField=document.getElementsByName('nid');
This Will return you array of 0th element, then you can get the value
var inputValue=inputField[0].value;
(Or you can directly make it in a single variable)
var inputFieldValue=document.getElementsByName('nid')[0].value;

Read json and create table javascript

I am am trying to read json data and import it to my table in html.
But some how it is not working.
I have already implemented a function to type in data what works great.
Only the function to load the json data is not working.
But i really don't know why.
I have posted the whole html code and my load data function.
MY Javascript code:
function loadData() {
var text = '{"employees":[' +
'{"firstName":"Ben","lastName":"dsafsad" },' +
'{"firstName":"Peter","lastName":"dsdsaadsj" },' +
'{"firstName":"Jules","lastName":"MIAU" }]}';
obj = JSON.parse(text);
for (var i = 0; i < obj.length; i++) {
var currentObj = obj[i];
var myName = currentObj.employees[0].firstName;
var age = currentObj.employees[0].lastName;
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
}
MY HTML code:
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" id="age">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()">
<input type="button" id="add" value="Load Data" onclick="Javascript:loadData()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
<div id="mydata">
<b>Current data in the system ...</b>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</table>
<br/>
</div>
</body>
</html>
You should be iterating over obj.employees, not obj. You have one object, which is composed of an employees array (with length of 3 in your example).
obj = JSON.parse(text);
console.log(obj);
console.log(obj.length); //this returns undefined
console.log(obj.employees.length); //this is what you want
for (var i = 0; i < obj.employees.length; i++) {
var currentObj = obj.employees[i];
console.log(currentObj);
var myName = currentObj.firstName;
console.log(myName);
var age = currentObj.lastName;
console.log(age);
}
Fiddle demo
You also have a problem here:
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
myName and age are variables you defined, not html elements, and as such, they don't have a value property. You just need to refer to the variables themselves, like so:
row.insertCell(1).innerHTML= myName;
row.insertCell(2).innerHTML= age;
Update Fiddle Demo

How to clone textareas with cloneNode?

I have 2 tables, and with a button I want to clone the content from tb_new to tb_made:
var tab = document.getElementById('tb_new');
var clone=tab.getElementsByTagName('tr')[1].cloneNode(true);
var table = document.getElementById("tb_made");
table.appendChild(clone);
Everything is cloned fine, except one cell with a textarea.
How can I fix that?
Fiddle is here.
Writing in a <textarea> will only update its value, not its content.
To solve the issue you can do something like this:
function add() {
var tab = document.getElementById('tb_new');
var textAreas = tab.getElementsByTagName("textarea");
for (var i = 0; i < textAreas.length; ++i) {
textAreas[i].innerHTML = textAreas[i].value;
}
var clone = tab.getElementsByTagName('tr')[0].cloneNode(true);
var table = document.getElementById('tb_made');
table.appendChild(clone);
}
<table id="tb_new">
<tr>
<td>
<textarea>Test</textarea>
</td>
<td>
<input>
</td>
</tr>
</table>
<input type="button" value="add" onClick="add()">
<table id="tb_made">
<tr>
<td></td>
</tr>
</table>

How can I update a set of text fields on key press and avoid resetting a form on submit?

I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:
This is what I've tried:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output")
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" />
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).
Why is the form resetting, and how could I extend this to not need the button at all?
Here is the fiddle link for it:
Calculator
Use the below code to achieve what I think you want to :
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Please check this FIDDLE.
All you need to adding attributes data-formula to your table cells.
HTML
<table border="1">
<tr>
<td>
<input type="text" id="initial-val" />
</td>
<td>card board</td>
<td>recycled</td>
<td>reusable</td>
</tr>
<tr>
<td>lovely trees</td>
<td data-formula='val*5'></td>
<td data-formula='val+10'></td>
<td data-formula='val/2'></td>
</tr>
<tr>
<td>what is acres</td>
<td data-formula='val*2'></td>
<td data-formula='val*(1+1)'></td>
<td data-formula='val*(10/5)'></td>
</tr>
</table>
JAVASCRIPT
$(function () {
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var $input = $('#initial-val'),
$cells = $('td[data-formula]');
$input.on('keyup', function () {
var val = $input.val();
if (isNumber(val)) {
$.each($cells, function () {
var $thisCell = $(this);
$thisCell.text(
eval($thisCell.attr('data-formula').replace('val', val.toString()))
)
});
} else {
$cells.text('ERROR')
}
});
});
You'll need:
a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
an input field for user input
a submit button with a onclick() event which passes your input into your calculation
(you may want to do some validation on this so they can only enter numbers)
validation examples
your Javascript file that takes the input from your box on submit and performs your calculation
display the information back to user... something like innerHtml to an element you've selected or:
var output = document.getelementbyid("your outputbox")
output.value = "";
output.value = "your calculated value variable";
Here is a tutorial for grabbing user input.
Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:
HTML:
<table>
<tr>
<th></th>
<th>Recycled Cardboard</th>
<th>Re-usable Cardboard</th>
</tr>
<tr>
<th>Trees Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Acres Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Energy (in KW)</th>
<td></td><td></td>
</tr>
<tr>
<th>Water (in Gallons)</th>
<td></td><td></td>
</tr>
<tr>
<th>Landfill (Cubic Yards)</th>
<td></td><td></td>
</tr>
<tr>
<th>Air Pollution (in Lbs)</th>
<td></td><td></td>
</tr>
</table>
Javascript:
function showStats(cardboardTons) {
var elements = $("td");
var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
for(var i=0;i<coeffs.length;i++)
elemnts.eq(i).html(cardboardTons * coeffs);
}
Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.

Categories

Resources