Can I create multiple onclick events dynamically? - javascript

For some reason I am unable to re-enable a button and go through all of the columns I have in a table with the same button. Can I create multiple onclick events for the button? The HTML itself is really just a button within a table.
function focaccia(x){
var table = document.getElementById("orderTable");
var row = table.insertRow(0);
var rem = document.createElement("button");
var name = document.createTextNode("Remove");
rem.appendChild(name);
rem.onclick = function(){
x.disabled = false;
document.getElementById("orderTable").deleteRow(this);
var table = document.getElementById("orderTable");
var amount = 0;
var tot;
for(var x = 0; x < table.rows.length; x++){
amount = amount + parseInt(table.rows[x].cells[1].children[0].value);
}
tot = amount * 9;
document.getTotal.total.value = tot;
}
var num = document.createElement("input");
num.size = 2;
num.onchange = function(){
var table = document.getElementById("orderTable");
var amount = 0;
var tot;
for(var x = 0; x < table.rows.length; x++){
amount = amount + parseInt(table.rows[x].cells[1].children[0].value);
}
tot = amount * 9;
document.getTotal.total.value = tot;
}
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "Focaccia";
cell2.appendChild(num);
cell3.appendChild(rem);
x.disabled = true;
num.value = 1;
total = total + 9;
document.getTotal.total.value = total;
}

Yes, use addEventListener.
Instead of target.onclick=clickHandlerFunction;, use target.addEventListener('click', clickHandlerFunction);'
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Note: The syntax for adding events using old Internet Explorer is different (target.attachEvent('onclick',handler)). If you need compatibility with old browsers, you can use both syntaxes, use jQuery's click or on functions or gator.js.

Related

How can I get the text of a JavaScript-generated input element?

I have a table that creates a row of input elements each time the "+" button is clicked underneath it. All elements are given the className "table-data". Once the "Done" button is clicked I want to loop through all these elements and get the text inside of them:
<table id="myTable"></table>
<button onclick="addRow();">+</button>
<button onclick="getData();">Done</button>
function addRow() {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text"></input>';
cell1.className = 'table-data';
cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text"></input>';
cell2.className = 'table-data';
}
function getData() {
inputCells = document.getElementsByClassName("table-data");
for (var i = 0; i < inputCells.length(); i++) {
console.log(inputCells[i].innerHTML);
}
}
However, when I run this code it just logs: 'input type="text"'
I tried using this instead:
console.log(inputCells[i].value);
But this method just logs "undefined". How can I get the value of these input elements?
Note: I don't mind if jQuery is used to answer this question.
I've prepared a solution for you using jQuery as your question is tagged with it. My solution find all inputs in table and then iterates over them using jQuery#each method.
const $table = $('#myTable');
$('#addBtn').on('click', function() {
let tr = $('<tr>');
let td1 = $('<td>');
let td2 = $('<td>');
let input = $('<input>', {
type: 'text',
class: 'table-data'
});
td1.append(input.clone());
td2.append(input.clone());
tr.append(td1);
tr.append(td2);
$table.append(tr);
});
$('#doneBtn').on('click', function() {
$table.find('input').each(function() {
console.log($(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable"></table>
<button id='addBtn'>+</button>
<button id='doneBtn'>Done</button>
Details commented in demo
// Reference form
const form = document.forms[0];
/*
//A Pass a number (max 10)
//B Reference table
//C Number of cells in a row
//D if number of cells in a row is less than input number...
//E Run addCols() function
//F Number of cells in a row is equal to number of the input
//G Add row
//H On each iteration...
//I Add a cell
//J Create an input assign type and name
//K Add input to cell.
*/
function addRow(count) {//A
const table = document.querySelector("table");//B
let width = table.rows[0].cells.length;//C
if (width < count) {//D
addCols(table, width, count);//E
width = count;//F
}
const row = table.insertRow();//G
for (let r = 0; r < width; r++) {//H
const cell = row.insertCell();//I
const text = document.createElement('input');//J
text.name = 'data';
text.type = 'text';
cell.appendChild(text);//K
}
return false;
}
// Similar to addRow() but will only adds cells
function addCols(table, width, count) {
let rowCount = table.rows.length;
for (let r = 0; r < rowCount; r++) {
let row = table.rows[r];
for (let c = 0; c < (count - width); c++) {
let cell = row.insertCell();
let text = document.createElement('input');
text.type = 'text';
text.name = 'data';
cell.appendChild(text);
}
}
return false;
}
/*
//A Pass Event Object
//B Prevent the form from sending data to a browser
//C Collect all form controls and convert collection into array
//D Use flatMap() to filter in the inputs with text and extract it
*/
function getData(event) {//A
event.preventDefault();//B
const ui = [...this.elements];//C
let txt = ui.flatMap(field => field.matches('[name=data]') && field.value !== '' ? [field.value] : []);//D
console.log(txt);
return txt;
}
//Register the button to click event
form.elements.add.onclick = function(event) {
const qty = Number(event.target.previousElementSibling.value);
addRow(qty);
};
//Register the form to submit event
form.onsubmit = getData;
input {display:inline-block;font:inherit;width:10vw}
<form>
<input id='qty' type='number' min='0' max='10' value='2'>
<button id='add' type='button'>+</button>
<button type='submit'>Done</button>
<table><tr></tr></table>
</form>

how to add the serial number column and options for a drop down list through javaScript

i have a add button in my jsp. while clicking on the add button, it will add a complete row which will include the checkbox, serial no, textbox and a drop down list with options.
i can able to add checkbox and text box but i am not able to add the serial no column(which is increasing the serial no by 1) and the drop down list options to the select through javaScript.
As the eleements are adding the ids dynamically i am not able to get the element by its id to check.
var i=1;
function addRow(tableID)
{
var tbl = document.getElementById(tableID);
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
//adding the checkbox
var el1 = document.createElement('input');
el1.type = 'checkbox';
el1.name = 'chkbox_' + i;
el1.id = 'chkbox_' + i;
el1.align = 'center';
//el1.size = 15;
el1.maxlength = 20;
firstCell.appendChild(el1);
var secondCell = row.insertCell(1);
//adding the serial no
var el2 = document.createElement('input');
el2.type = 'style';
el2.name = 'style_' + i;
el2.id = 'style_' + i;
//el1.size = 15;
el2.maxlength = 20;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
//adding the textbox
var el3 = document.createElement('input');
el3.type = 'text';
el3.name = 'txtbox_' + i;
el3.id = 'txtbox_' + i;
el3.size = 15;
el3.maxlength = 20;
thirdCell.appendChild(el3);
var forthCell = row.insertCell(3);
//adding the option
var el4 = document.createElement('select');
el4.type = 'select-one';
el4.name = 'select_' + i;
el4.id = 'select_' + i;
el4.value = "1";
//el4.size = 15;
el4.maxlength = 20;
var select = document.getElementById("select_2");
select.options[select.options.length] = new Option('Value1', 'Value2','Value3');
forthCell.appendChild(el4);
el4.appendChild(option);
// alert(i);
i++;
frm.h.value=i;
// alert(i);
}
</script>
please help me to get the solution. i tried with possibilities but never get a solution what i need.Thanks in advance.
You've missed setting the value of Serial Number.
var el2 = document.createElement('input');
el2.type = 'style';
el2.name = 'style_' + i;
el2.id = 'style_' + i;
el2.value = i;
Also, You have to set options to select something like below
var el4 = document.createElement('select');
var opt = document.createElement('option');
opt.value = "Value1";
opt.innerHTML = "Value1";
el4.appendChild(opt);
window.onload = function()
{
addRow("test");
}
var i=1;
function addRow(tableID)
{
var tbl = document.getElementById(tableID);
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
//adding the checkbox
var el1 = document.createElement('input');
el1.type = 'checkbox';
el1.name = 'chkbox_' + i;
el1.id = 'chkbox_' + i;
el1.align = 'center';
//el1.size = 15;
el1.maxlength = 20;
firstCell.appendChild(el1);
var secondCell = row.insertCell(1);
//adding the serial no
var el2 = document.createElement('input');
el2.type = 'style';
el2.name = 'style_' + i;
el2.id = 'style_' + i;
//el1.size = 15;
el2.value = i;
el2.maxlength = 20;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
//adding the textbox
var el3 = document.createElement('input');
el3.type = 'text';
el3.name = 'txtbox_' + i;
el3.id = 'txtbox_' + i;
el3.size = 15;
el3.maxlength = 20;
thirdCell.appendChild(el3);
var forthCell = row.insertCell(3);
//adding the option
var el4 = document.createElement('select');
el4.type = 'select-one';
el4.name = 'select_' + i;
el4.id = 'select_' + i;
el4.value = "1";
//el4.size = 15;
el4.maxlength = 20;
var opt = document.createElement('option');
opt.value = "Value1";
opt.innerHTML = "Value1";
el4.appendChild(opt);
//var select = document.getElementById("select_2");
//select.options[select.options.length] = new Option('Value1', 'Value2','Value3');
forthCell.appendChild(el4);
//el4.appendChild(option);
// alert(i);
i++;
//frm.h.value=i;
// alert(i);
}
</script>
<input type="button" value="Add Row" onclick='addRow("test")' />
<table id="test"></table>

Button and radio button inside excel CSV after file upload using javascript

A excel CSV (comma seperated value) file is uploaded initially. This CSV file is represented as a table format in an html page. Here, I need to add a radio button, button etc,along with the table formatted representation. Is this possible without usage of database?.
Thanks in advance.
function Upload() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var radio = document.createElement("radio");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
dvCSV.appendChild(radio);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
I had created an element 'radio' inside function also appended as a child, but it doesn't displays it. My requirement is that, when each row of CSV file is placed, I need to place a radio and button there.(radio for selecting and button for editing the row element and save file).
This line
var radio = document.createElement("radio");
means <radio></radio>. However, there is no radio tag. It's <input type="radio">:
var radio = document.createElement("input");
radio.type = 'radio';
To "group" all radio buttons together, you also need to give them the same name:
radio.name = 'radio';
And if you say you need a button too, then create one:
var button = document.createElement('button');
button.textContent = 'Click me';
But most importantly, if you need them for every row, then put them there, and not somewhere else:
reader.onload = function(e)
{
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for(var i = 0; i < rows.length; i++)
{
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for(var j = 0; j < cells.length; j++)
{
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
// Here:
var radio = document.createElement("input");
radio.type = 'radio';
radio.name = 'radio';
var button = document.createElement('button');
button.textContent = 'Click me';
var cell = row.insertCell(-1);
cell.appendChild(radio);
cell.appendChild(button);
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}

Delete row from table dynamically created in javaScript

I want to delete a row from a table created by JavaScript. i tried the code from different post on this page but doesn't solve it.
function value_pass()
{
var Delete = document.createElement("input");
Delete.type="button";
Delete.name = "del"
Delete.value = "Delete";
Delete.onclick = function(o)
{
var r = o.parentElement.parentElement;
document.getElementById("table").deleteRow(r.rowIndex);
}
var order_no = document.getElementById("Order_no");
var quantity = document.getElementById("quantity");
var type = document.getElementById("Recipe");
var recipe = type.options[type.selectedIndex].text;
var body1 = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute("id","table");
var tblbody = document.createElement("tbody");
tbl.setAttribute("border","2");
var col = document.createElement("td");
for (var j = 0; j < 1; j++)
{
var rows = document.createElement("tr");
for (var i = 0; i < 4; i++)
{
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var col5 = document.createElement("td");
var col1text = document.createTextNode(order_no.value);
var col2text = document.createTextNode(recipe);
var col3text = document.createTextNode(quantity.value);
var col4text = document.createTextNode();
//also want to put checked values in table row
}
col1.setAttribute("width","150");
col2.setAttribute("width","150");
col3.setAttribute("width","150");
col4.setAttribute("width","150");
col1.appendChild(col1text);
col2.appendChild(col2text);
col3.appendChild(col3text);
col4.appendChild(col4text);
col5.appendChild(Delete);
rows.appendChild(col1);
rows.appendChild(col2);
rows.appendChild(col3);
rows.appendChild(col4);
rows.appendChild(col5);
tblbody.appendChild(rows);
} tbl.appendChild(tblbody);
body1.appendChild(tbl);
}
The function will be called by a button in HTML
its an order form that
and also want to know about the checked values of checkbox to put in the table row.
You can use :
document.getElementById("myTable").deleteRow(0); //Where 0 is your row.
Explained : http://www.w3schools.com/jsref/met_table_deleterow.asp
Edit:
To delete the current row, set this on your button: onclick="deleteRow(this), with the following code in that function:
function deleteRow(t)
{
var row = t.parentNode.parentNode;
document.getElementById("myTable").deleteRow(row.rowIndex);
console.log(row);
}

How to delete a row in Javascript?

I already have add/delete rows dynamically in Javascript, there is no problem in adding rows, only having a problem with deleting rows.
For now, what I have made is when I want to delete a row it always deletes the last one, so I think I want if it only can be deleted the selected row, and I don't know how to modify the script to what I wanted be.
Here is the script:
var i=0;
function addRow()
{
i++;
m.r.value = i;
var tbl = document.getElementById('table');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
var cellRightSel1 = row.insertCell(1);
var sel = document.createElement('select');
sel.name = 'name' + iteration;
sel.setAttribute("onchange", "choosec(this);");
var item = new Option("","");
sel.options[sel.length] = item;
<?
while($data = mysql_fetch_array($result)){
?>
var item = new Option("<?=$data["Name"];?>","<?=$data["ID"];?>");
sel.options[sel.length] = item;
<? } ?>
cellRightSel1.appendChild(sel);
var cellRightSel2 = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'class' + iteration;
sel.setAttribute("onchange", "choosepoint(this);");
var item = new Option ("","");
sel.options[sel.length] = item;
<?
while($data = mysql_fetch_array($result_sub)){
?>
var item = new Option("<?=$data["Class"];?>","<?=$data["ID"];?>");
sel.options[sel.length] = item;
<? } ?>
cellRightSel2.appendChild(sel);
var cellRight = row.insertCell(3);
var div = document.createElement('div');
div.id = 'point' + iteration;
cellRight.appendChild(div);
}
function removeRow(){
var tbl = document.getElementById('table');
var lastRow = tbl.rows.length;
var rem = lastRow - 1;
if (lastRow > 2) tbl.deleteRow(rem);
}
Help is appreciated, thanks.
My solved problems:
function removeRow(t){
var i = t.parentNode.parentNode.rowIndex;
var tbl = document.getElementById('table');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
tbl.deleteRow(i);
}
try it like this
<tr onclick="removeRow(this);">...</tr>
then in javascript method
function removeRow(row){
var tbl = row.parentNode;
var index = row.parentNode.rowIndex;
if (index > 2) tbl.deleteRow(index);
}
I found one good example suitable your requirement. check here
This is the code that needs to be changed:
var rem = lastRow - 1;
Right now, that's always going to be the last row. You can build some logic around that to pass in an index, or hunt for a string, or whatever, but tbl.deleteRow() needs to delete at a particular index.
If you wanted to delete the 3rd row, for example:
var rem = 2; //zero-based index

Categories