Why are cell name attributes undefined in my code - javascript

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 />

Related

How to print or get the cell value from HTML TABLE(User Input)

I have a table and in the table, I have tag to get user input. I want to print or get the value from the table cell. I want to input two number such as 12 and 14 and then print sum value at result id. I don't want to use the form tag. Is it possible to do this?
Thanks.
for(i=0;i<x.length-1;i++)
{
result=x[i].cellIndex + x[i+1].cellIndex;
document.getElementById("result").innerHTML=result;
}
<!DOCTYPE HTML>
<html>
<body>
<table>
<tr>
<td> <input id="firstnumber" type="number"> </td>
<td> <input id="secondNumber" type="number"> </td>
</tr>
<p id="result"></p>
</table>
</body>
</html>
Here is a working example
// get the Dom object of the ttwo cells
var cell1 = document.querySelector("#firstnumber"),
cell2 = document.querySelector("#secondNumber");
// when the user writes on each of them the result changes
cell1.oninput = cell2.oninput = function() {
// + before the cell.value only for casting the string to a number
document.getElementById("result").innerHTML = +cell1.value + +cell2.value;
}
<!DOCTYPE HTML>
<html>
<body>
<table>
<tr>
<td> <input id="firstnumber" type="number"> </td>
<td> <input id="secondNumber" type="number"> </td>
</tr>
<p id="result"></p>
</table>
</body>
</html>
you can wrap the td elements in a tBodies tag then you can access each element in the table like this:
let index_1 = document.getElementById("myTable").tBodies[0];
tBodies[0] represents the index of the table. 0 being the first element in the tables tbodies array.

How can I get the difference of fields in html and js?

I tried to do multiplication of two fields, but I want to take the result minus the third field (I want to get the different in column of credit).
$.fn.fonkTopla = function() {
var toplam = 1;
this.each(function() {
var deger = fonkDeger($(this).val());
toplam *= deger;
});
return toplam;
};
function fonkDeger(veri) {
return (veri != '') ? parseInt(veri) : 1;
}
$(document).ready(function() {
$('input[name^="fiyat"]').bind('keyup', function() {
$('#toplam').html($('input[name^="fiyat"]').fonkTopla());
});
});
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="kapsayici">
<ul>
<table border="1">
<tr>
<th>Type</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
<th>Paid</th>
<th>Credit</th>
</tr>
<tr>
<td><input type="text" name="" value="ItemCode" class="mytext" /></td>
<td><input type="text" name="fiyat[]" class="mytext" /></td>
<td><input type="text" name="fiyat[]" class="mytext" /></td>
<td><span id="toplam"></span> RWF</td>
<td><input type="text" name="fiyat[]" class="mytext" /></td>
<td><span id="toplam_difference_here"></span> RWF</td>
</tr>
</table>
</ul>
</div>
</body>
</html>
The result will be in the following column
<td><span id="toplam_difference_here"></span> RWF</td>
Add data attr 'noaction' and class 'paid; within the third input paid field
<!-- add data attr noaction and class paid within paid field-->
<td><input type="text" name="fiyat[]" data-noaction="true" class="paid mytext" /></td>
On based on data attribute, if the input field is paid, do not multiply.
$.fn.fonkTopla = function() {
var toplam = 1;
this.each(function() {
var deger = fonkDeger($(this).val());
//get the data attr value
var no_action= $(this).data('noaction');
var paid_val = $(this).closest('tr').find('.paid').val();
//On based on data attribute, if the input field is paid, do not multiply,
if(!no_action){
toplam *= deger;
//take the result minus paid field
total = toplam - paid_val;
}
});
return total;
};
DEMO
Based on comments modify the code.
In form use class instead of id for multiple row
<!--
1- use class insteadd of id for multiple row, Make it text field.
2- Make it text field, to append the total calculated value
3- And also upadte it to readonly, beacause this field is for display the total calculated amount. -->
<td><input type="text" name="fiyat[]" readonly data-noaction="true" class="toplam mytext" /></td>
For multiple row, get the closest row (tr) field value for calculating and display
jQuery code.
$(document).ready(function(){
$('input[name^="fiyat"]').bind('keyup', function() {
//For multiple row, get the closest row (tr) field value for calculating and display
var closest = $(this).closest('tr');
//change .html to .val to add the value in text field.
closest.find('.toplam').val(closest.find('input[name^="fiyat"]').fonkTopla());
});
});
DEMO

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;

JavaScript: text element returning "undefined"

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.

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