Javascript jQuery textbox creation and output - javascript

Currently, I have a two table rows with two textboxes. I want to buid a button which allows the user to add and subtract an author row depending on how many they want. Once they increase the amount of authors they need for input, the user clicks on the generate button, the input from the textboxes will be outputed at the bottom of the page. I was trying to pull this off with javascript and jQuery. I am a ten day old student with javascript and jQuery and feel as if I have bit off more than I can chew.
An example of what I want can be found at this lnk: http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/. However, I need the input from the textboxes outputed on the same page.
<!DOCTYPE html>
<head>
</head>
<body>
<table>
<tbody>
<tr>
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
<tr>
<td>Second Author (If Any)</td>
<td><input type="text" id="3" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="4" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<br>
<br>
<output id="20"></output>
<br>
<br>
</body>
</html>
<script type=text/javascript>
function myFunction()
{
var firstlast=document.getElementById("1").value;
if (firstlast==null || firstlast=="")
{
firstlast;
}
else if(firstlast!=null || firstlast!="")
{
firstlast=document.getElementById("1").value + ", ";
}
var firstfirst=document.getElementById("2").value;
if (firstfirst==null || firstfirst=="")
{
firstfirst;
}
else if(firstfirst!=null || firstfirst!="")
{
firstfirst=document.getElementById("2").value + ". ";
}
var secondlast=document.getElementById("3").value;
if (secondlast==null || secondlast=="")
{
secondlast;
}
else if(secondlast!=null || secondlast!="")
{
secondlast=document.getElementById("3").value + ", ";
}
document.getElementById("20").innerHTML = firstlast + firstfirst + secondlast;
}
</script>

The jQuery
//wait for the document to be ready
$(document).ready(function()
{
// when generate authors is clicked
$("#generate-authors").click(function()
{
// get the first author row in your table
var author = $(".author-row:first");
// for the amount of authors put into the text box
// insert a copy of the row after the last row
for(i = 0; i < parseInt($("#author-amount").val()); i++)
$(".author-row:last").after(author.clone());
});
// when output data is clicked
$("#output-data").click(function()
{
// go through all the author rows
$(".author-row").filter(function()
{
// add them to the output element
$("#output").append("<p>" + $(this).find("[placeholder=\"Last\"]").val() + ", " + $(this).find("[placeholder=\"First\"]").val() + ".</p>");
});
});
});
The html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
// put the script here
</script>
</head>
<body>
<input id="author-amount" type="text" />
<input id="generate-authors" type="button" value="Generate" />
<br />
<input id="output-data" type="button" value="Output Data" />
<table>
<tbody>
<tr class="author-row">
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<br />
<output id="output"></output>
</body>
</html>

See this Example might be this is that what you want
HTML
<table id="table">
<tbody>
<tr>
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
<tr>
<td>Second Author (If Any)</td>
<td><input type="text" id="3" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="4" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<input type="button" id="generat" value="add">
<input type="button" id="remove" value="remove">
<input type="button" id="display" value="display">
<output id="20"></output>
JS
$(document).ready(function(){
$("#generat").click(function(){
var clone = $("#table tr:first").clone();
$("#table tbody:last").append(clone);
});
$("#remove").click(function(){
$("#table tbody tr:last").remove();
});
$("#display").click(function(){
$("#20").html("");
$("table tr").each(function(){
$(this).find("input").each(function(){
$("#20").append(($(this).val()));
});
});
})
});
LINK

Related

JavaScript calculator script does't work

I am learning javascript. Try to make a simple calculator using DOM. I wrote the below script, But my script gives error.
Uncaught TypeError: Cannot read property 'value' of null calculator.html:8
Here is my Script:
<!DOCTYPE html>
<html>
<head>
<title>My Calculator</title>
</head>
<body>
<script type="text/javascript">
var f_number = document.getElementById("f_number").value;
var f_number = document.getElementById("s_number").value;
function calculate(opa)
{
if(opa=='+')
{
var result = Number(f_number) + Number(s_number);
}
if(opa=='-')
{
var result = f_number - s_number;
}
if(opa=='*')
{
var result = f_number * s_number;
}
if(opa=='/')
{
var result = f_number / s_number;
}
return document.getElementById('res').value = result;
}
</script>
<div class="container">
<table>
<tr>
<td>First Number</td>
<td><input type="number" id="f_number" ></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="number" id="s_number" ></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="+" onclick="calculate()" >
<input type="submit" value="-" onclick="calculate()" >
<input type="submit" value="*" onclick="calculate()" >
<input type="submit" value="/" onclick="calculate()" >
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="res"></td>
</tr>
</table>
</div>
</body>
</html>
Full example of working code:
<!DOCTYPE html>
<html>
<head>
<title>My Calculator</title>
</head>
<body>
<div class="container">
<table>
<tr>
<td>First Number</td>
<td><input type="number" id="f_number" ></td>
</tr>
<tr>
<td>Second Number</td>
<td><input type="number" id="s_number" ></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="+" onclick="calculate('+')" >
<input type="submit" value="-" onclick="calculate('-')" >
<input type="submit" value="*" onclick="calculate('*')" >
<input type="submit" value="/" onclick="calculate('/')" >
</td>
</tr>
<tr>
<td>Result</td>
<td><input type="text" id="res"></td>
</tr>
</table>
</div>
<script type="text/javascript">
function calculate(opa)
{
var f_number = +document.getElementById("f_number").value;
var s_number = +document.getElementById("s_number").value;
if(opa=='+')
{
var result = f_number + s_number;
}
if(opa=='-')
{
var result = f_number - s_number;
}
if(opa=='*')
{
var result = f_number * s_number;
}
if(opa=='/')
{
var result = f_number / s_number;
}
return document.getElementById('res').value = result;
}
</script>
</body>
</html>
JavaScript is excuted in the order it is encountered.
When you do document.getElementById("f_number").value that DOM node does not yet exist. So it returns null, hence the error message.
Either move your code below the referenced DOM node definitions or run your code on document ready or onload.
It means there are no values for those items:
var f_number = document.getElementById("f_number").value;
var f_number = document.getElementById("s_number").value;
You need to run the script once a value is present/button is clicked as opposed to right away.

Printing function in javascript is not printing textbox values

I'm trying to print an HTML table with textboxes take their values from another function. but it shows nothing in the Preview .
This is the full Code :
<html>
<head></head>
<script type="text/javascript">
function bill() { //Bill
var PriceTest = document.getElementById("Val");
var Quantity = document.getElementById("Quan");
var price = document.getElementById("total");
price.value = PriceTest.value * Quantity.value ;
var tq = document.getElementById("TQuantity");
tq.value = Quantity.value;
}
function printData() {
var TablePrint = document.getElementById("TestTable");
newWin = window.open("");
newWin.document.write(TablePrint.outerHTML);
newWin.print(); // Printing the Bill
}
</script>
<body>
<form>
<table border="1">
<input type="number" id="Quan" min="0" max="100" step="1" value="0"/>
<input type="text" value="100000" class="TextStyle" id="Val"/>
<input type="button" class="BuyButton" name="Buy" Value="Calc" onclick="bill()"/></table>
<br/><br/>
<table id="TestTable" border="1">
<input type="text" id="total" class="TextStyle" onfocus="this.blur();">
<input type="text" id="TQuantity" class="TextStyle" onfocus="this.blur();">
</table>
<input type="button" value="Print This" onclick="printData()"/>
</form>
</body>
</html>
You shouldn't be printing input fields.
This is an example with paragraph tags.
(You should also tidy up the code a bit :)
<html>
<head></head>
<script type="text/javascript">
function bill() { //Bill
var PriceTest = document.getElementById("Val");
var Quantity = document.getElementById("Quan");
var price = document.getElementById("total");
price.innerHTML = PriceTest.value * Quantity.value ;
var tq = document.getElementById("TQuantity");
tq.innerHTML = Quantity.value;
}
function printData() {
var TablePrint = document.getElementById("TestTable");
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += TablePrint.outerHTML;
newWin = window.open("");
newWin.document.write(htmlToPrint);
newWin.print(); // Printing the Bill
}
</script>
<body>
<form>
<table border="1">
<input type="number" id="Quan" min="0" max="100" step="1" value="0" />
<input type="text" value="100000" class="TextStyle" id="Val" />
<input type="button" class="BuyButton" name="Buy" Value="Calc" onclick="bill()" />
</table>
<br/>
<br/>
<table id="TestTable" border="1">
<tr>
<td>
<p id="total"></p>
</td>
<td>
<p id="TQuantity"></p>
</td>
</tr>
</table>
<input type="button" value="Print This" onclick="printData()" />
</form>
</body>
</html>
Cheers!
It looks like it is because your table markup is incorrect. tr is the tag for a table row, and td is the tag for the table data (cell) within that row.
<table id="TestTable" border="1">
<tr><td>
<input type="text" id="total" class="TextStyle" onfocus="this.blur();">
<input type="text" id="TQuantity" class="TextStyle" onfocus="this.blur();">
</td></tr>
</table>
Your script is correct, but looks like your html markup isn't valid. You would end up with the textboxes outside of the table with your current implementation (at least in Chrome) other browsers might omit the invalid markup. You will need tr/td.
<table id="TestTable" border="1">
<tr>
<td>
<input type="text" id="total" class="TextStyle" onfocus="this.blur();">
</td>
<td>
<input type="text" id="TQuantity" class="TextStyle" onfocus="this.blur();">
</td>
</tr>
</table>

Dynamically add/remove rows from html table

I am working on a table that can be modified by pressing "Delete" buttons in each row and "Insert row" to add a new one at the end:
So far by now my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
document.getElementById(id).deleteRow(row);
}
function insRow(id) {
var filas = document.getElementById("myTable").rows.length;
var x = document.getElementById(id).insertRow(filas);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = '<input type="text" id="fname">';
z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>
But i cannot attach the function onclick="deleteRow('myTable',0)" on
z.innerHTML ='<button id="btn" name="btn"> Delete</button>'
¿Is there something else i need to declare in order to make that button work when clicked?
Thanks for your answers
First off, IDs must be unique, so why not use classes here instead?
Second, if you're using jQuery, then use jQuery.
Third, you need to use event delegation when dynamically adding elements, so try the following:
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<p>
<input type="button" value="Insert row">
</p>
On each DeleteRow(tableId,Index) function you are passing table id and static index that's why document.getElementById("mytable").deleteRow(Index) first find table node then find no of tr element as children and assigns the index to tr element start from 0 and delete the matching index tr element.
Whenever you delete first row then it will matches the 0 index from 3 elements and deletes the first row. Now there are 2 tr left with index 0 and 1 dynamically assign by table but you trying to match with 1 and 2.
for deleting second row it will delete tr with index 1 (third tr) not the second tr.
for deleting third row actual index is 0 (after deleting 2 rows) and you are passing 1 because of this reason it wont find the matching index.
Here is Simple javascript soltution.
<script>
function delRow(currElement) {
var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(parentRowIndex);
}
</script>
and html,
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>
here is jsfiddle exmple
Click Here
Say you have the following table:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstName" /></td>
<td><input type="text" name="lastName" /></td>
<td> <input type="text" name="email" /></td>
</tr>
</tbody>
<p>
<label>Insert</label>
<input type="number" value="1" id="numberOfRowsToInsert">
<input type="button" value="Insert row" id="insert-line-button">
</p>
</table>
The following jquery code will generate x number of rows entered by the user and append them to the bottom of the table with the ability to delete them if needed:
$('#insert-line-button').on("click", function(){
var noOfRows = $('#numberOfRowsToInsert').val();
for(var i = 0; i < noOfRows; i++){
$('#myTable').append("<tr>" +
"<td><input type='text' name='firstName' /></td>" +
"<td><input type='text' name='lastName' /></td>" +
"<td> <input type='text' name='email' /></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
}
});
And the following jquery code will remove the rows when clicked on the 'Delete' button:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
$(this).parent().parent().remove();
});
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.
<html>
<script>
function CreateTableAndRows(){
var mybody = document.getElementsByTagName("body")[0];
var newTable = document.createElement("table");
var newTableHead = document.createElement("thead");
var headRow = document.createElement("tr");
var headHead1 = document.createElement("th");
var headRowCellValue = document.createTextNode("Device Name");
headHead1.appendChild(headRowCellValue);
var headHead2 = document.createElement("th");
headRowCellValue = document.createTextNode("Start Timing");
headHead2.appendChild(headRowCellValue);
var headHead3 = document.createElement("th");
headRowCellValue = document.createTextNode("End Timing");
headHead3.appendChild(headRowCellValue);
var headHead4 = document.createElement("th");
headRowCellValue = document.createTextNode("Duration");
headHead4.appendChild(headRowCellValue);
headRow.appendChild(headHead1);
headRow.appendChild(headHead2);
headRow.appendChild(headHead3);
headRow.appendChild(headHead4);
newTableHead.appendChild(headRow);
newTable.appendChild(newTableHead);
var newTableBody = document.createElement("tbody");
for(var rowCount=0;rowCount<5;rowCount++)
{
var newTableRow = document.createElement("tr");
for(var cellCount=0; cellCount<4; cellCount++)
{
var newTableRowCell = document.createElement("td");
var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
newTableRowCell.appendChild(cellValue);
newTableRow.appendChild(newTableRowCell);
}
newTableBody.appendChild(newTableRow);
}
newTable.appendChild(newTableBody);
newTable.setAttribute("border","2");
mybody.appendChild(newTable);
}
</script>
</head>
<body>
<input type="submit" onclick="CreateTableAndRows();">
</body>
</html>

Javascript created elements not posting on submission

Ive posted a few times but I'm still not coming right with this problem so below is the all the code, the problem is that the dynamically created elements are not appearing in _POST after submission. but I do see them in the modified source in firefox.
The Javascript inserts elements in between the following div,
<div id="p_scents">
</div>
but as mentioned do not show in in _POST
Below is the full source code so the problem can be replicated.
<html >
<head>
<script src="/js/jquery.min.js"></script>
<script src="/js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').on('click', function() {
$('<p><label for="p_scnts"><input type="text" size="20" name="url' + i +'" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').on('click', function() {
if( i > 1 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<script type="text/javascript">
jQuery(function($){
var jcrop_api;
$('#target').Jcrop({
onChange: showCoords,
onSelect: showCoords,
onRelease: clearCoords
},function(){
jcrop_api = this;
});
$('#coords').on('change','input',function(e){
var x1 = $('#x1').val(),
x2 = $('#x2').val(),
y1 = $('#y1').val(),
y2 = $('#y2').val();
jcrop_api.setSelect([x1,y1,x2,y2]);
});
});
function showCoords(c)
{
$('#x1').val(c.x);
$('#y1').val(c.y);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
$('#w').val(c.w);
$('#h').val(c.h);
};
function clearCoords()
{
$('#coords input').val('');
};
</script>
</head>
<body>
<table border=1 cellpadding="1" cellspacing="0" width=80%>
<form action="/index.php/create" method="post" accept-charset="utf-8"> <tr>
<td>
Select image
</td>
<td>
<input type="file" name="image"/>
</td>
</tr>
<tr><td colspan=2 align=center>
Add Another Input Box
</td>
</tr>
<tr><td>
Give your banner a unique name</td>
<td>
<input type="text" name="name" value="" id="name" autofocus /> </td></tr>
<tr><td>Specify email address or domain to brand</td>
<td>
<input type="text" name="domainName" value="" id="domain" /> </td></tr>
<tr><td>Status</td>
<td>
<select name="status">
<option value="enabled">Enabled</option>
<option value="disabled">Disabled</option>
</select> </td></tr>
<tr><td>Give you banner a default URL</td>
<td>
<input type="text" name="url" value="" id="url" /> </td></tr>
<tr><td valign=top>Alternate Urls
</td>
<td>
<div id="p_scents">
</div>
<input type=submit>
</form> </td>
</tr>
</table>
</body>
</html>
You have multiple nesting errors in your HTML. Your <form> tag is put immediately inside the <table> - that is incorrect! Also the enclosing tag of the form is put inside the last <td>. Your markup should look like this:
<form ...>
<table ...>
<tr ...>
<td ...>
...
</td>
...
</tr>
...
</table>
</form>

HTML/Javascript: How do you change input tag with javascript?

Heres some of what I got, its a calculator, I'mg tryign to call the JS method from the button click events, something wrong though, display won't update.
<script language="javascript" type="text/javascript" src="calculator.js">
var display = document.getElementById('display');
function digit( num ){
if(display == 0){
display.innerHTML = num;
} else {
display.innerHTML = display.innerHTML + "" + num;
}
};
</script>
</head>
<body>
<form name="calculator">
<table width="auto" border="1">
<tr>
<!--<td colspan=4><input id="display" type="text"></td> -->
<td colspan=4><div id="display"></div></td>
</tr>
<tr>
<td>MC</td>
<td>MR</td>
<td>MS</td>
<td><input type="button" value='/' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input type="button" value=7 onclick="javascript:digit(this.value);"></td>
<td><input type="button" value=8 onclick="javascript.digit(this.value);"></td>
<td><input type="button" value=9 onclick="pushButton(this.value);"></td>
<td><input type="button" value='*' onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input type="button" value=4 onclick="pushButton(this.value);"></td>
<td><input type="button" value=5 onclick="pushButton(this.value);"></td>
<td><input type="button" value=6 onclick="pushButton(this.value);"></td>
Move
var display = document.getElementById('display');
into your function.
You are calling document.getElementById('display'); before that element (id=display) exists. You can do a variety of things, but the easiest would just be to move the <script> to just before </body>, or at least after id=display
Place 0 in the div Or change the condition in script (display == null )

Categories

Resources