Get selected row value using javascript - javascript

I have dynamically add the table on html button click. Add the teamname,teamid,radio button.
HTML attributes:
<input type="button" value="Generate a table." onclick="generate_table()">
Javascript function :
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
4 rows with 3 columns will generate on the button click , Now i need to get the details on the radio button click.
If i select the radio button from the first row i need to show the teamid in alert box? how can I achieve this in javascript?

try this code below should alert teamid cell's innerText
<input type="button" value="Generate a table." onclick="generate_table()">
function generate_table()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
//here we set value of radio button based on element index and we set a classname for teamid cell
radio.setAttribute("value", i);
cell1.setAttribute("class", "selected_teamid");
//here we add click event
radio.setAttribute("onclick", "getteamid("+i+")");
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
function getteamid(i){
alert(document.getElementsByClassName("selected_teamid")[i].innerText);
}
<input type="button" value="Generate a table." onclick="generate_table()">

just add this line, before appending the radio element:
radio.onclick = function(){alert(this.value};

You just need to add an event handler to the radio button when you create it:
...
radio.addEventListener('click', radioButtonClick, false);
...
function radioButtonClick() {
alert(this.getAttribute('value'));
}
This requires that you set the value of the radio button to your team id, or store it on the radio button (which will be the this inside the event handler) in some other way.

You aren't passing a teamid anywhere, so I assumed the teamid is the index of the looped array.
var generate_table = function()
{
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var teamrecord = "test";
for (var i = 0; i < teamrecord.length; i++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
var cellText = document.createTextNode("teamrecord");
var cellId = document.createTextNode("teamid");
var radio = document.createElement("INPUT");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "radio");
radio.setAttribute('data-team', i); // passing the team id
cell.appendChild(cellText);
cell1.appendChild(cellId);
cell2.appendChild(radio);
row.appendChild(cell);
row.appendChild(cell1);
row.appendChild(cell2);
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
// add an event listener on a dynamic element, and alert the team id
document.addEventListener('click', function(e) {
if(e.target && e.target.hasAttribute('data-team')) {
alert(e.target.getAttribute('data-team'));
}
});

You have several way to achieve that:
The easiest way I think is to add an attribute 'teamid' to the radio button. Then just listen for click event and get this value back.
radio.setAttribute('teamid', teamid);
radio.addEventListener('click', onRadioClick);
function onRadioClick(domEvent){
console.log(domEvent.target.getAttribute('teamid'));
}
For me it is not the best way because you need to put some information in the DOM... In my opinion, it would be better to separate the presentation and the data :
var tableData = [
{teamId: 'someId0', title:'title0', someData:'...' },
{teamId: 'someId1', title:'title1', someData:'...' },
{teamId: 'someId2', title:'title2', someData:'...' }
];
for (var i = 0, n = tableData.length ; i < n ; i++){
var rowData = tableData[i];
// Create the row using rowData
// ...
radio.setAttribute('teamid', rowData.teamId);
radio.addEventListener('click', onRadioClick.bind(rowData));
// ...
}
function onRadioClick(domEvent){
// Here this represent data of the row clicked
console.log(this.teamId);
}
I think it's easier to manage because every data are JS side... You don't store any data in the DOM... However both works ;) Hope it helps

radio.setAttribute("onclick", "anotherFunction(this)")
and after this function create anotherFunction():
function anotherFunction(object){
alert(object.parentNode.parentNode.firstChild.innerHTML);
}

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>

For 2 dynamically generated TD

Right now the following code generates two much white spaces between the two TDs.
How to set the first TD left aligned and
the second TD left aligned to the first TD?
// nTR being the newly TR
nTR.setAttribute('style','td {padding: 10px}') has no effect. How to go about it?
// creating row and creating all cells
// creates a table row
var newrow = document.createElement("tr");
newrow.setAttribute('style','td {padding: 10px}');
// cell 1
var cell = document.createElement("td");
cell.colSpan = "2";
// cell.setAttribute('style','padding: 10px');
var cellText = document.createElement('input');
cellText.type = 'text';
cellText.id = 'fLabel';
cellText.name = 'fLabel';
cellText.size = "20";
cell.appendChild(cellText);
newrow.appendChild(cell);
// cell 2
var cell = document.createElement("td");
cell.colSpan = "3";
var cellText = document.createElement('input');
cellText.type = 'text';
cellText.id = 'fValue';
cellText.name = 'fValue';
cellText.size = "80";
cell.appendChild(cellText);
newrow.appendChild(cell);
// code to append the new TR to table
// ...
Thanks.

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);
}

html dynamically generating form but not giving the value of date in url when posting it

function addrow() {
document.getElementById("myTableData").style.display="block";
/*displaying div on click of button abc*/
var el = document.createElement('input');
el.type = 'text';
el.name = 'kname';
/*creating name field*/
var el_r = document.createElement('input');
el_r.type = 'radio';
el_r.name = 'gender';
el_r.value ='FEMALE';
el_r.id = "rad1";
el_r.defaultChecked = true;
/* creating radio button for gender field */
var el_r2 = document.createElement('input');
el_r2.type = 'radio';
el_r2.name = 'gender';
el_r2.value ='MALE';
el_r2.id = "rad2";
/* creating radio button for gender field */
var obj1 = document.createTextNode("Female");
var obj2 = document.createTextNode("Male");
var objLabel = document.createElement("label");
objLabel.htmlFor = el_r.id;
objLabel.appendChild(el_r);
objLabel.appendChild(obj1);
var objLabel2 = document.createElement("label");
objLabel2.htmlFor = el_r2.id;
objLabel2.appendChild(el_r2);
objLabel2.appendChild(obj2);
/* creating drop down for date field */
var el_s = document.createElement('select');
el_s.onchange = function(){
var r = el_s.options[el_s.selectedIndex].value;
alert("selected date"+r); //cheking the selected date value;
}
for(var i=0;i<32;i++)
{
var j = i;
j = document.createElement('option');
j.text=i;
j.name="day";
j.value=j;
el_s.appendChild(j);
}
var month = new Array("January","Februray","March","April","May","June","July","August","September","October","November","December");
var el_sm = document.createElement('select');
for(var i=0;i<month.length;i++)
{
var j = i;
j = document.createElement('option');
j.text=month[i];
j.name="month";
j.value=month[i];
el_sm.appendChild(j);
}
var el_sy = document.createElement('select');
for(var i=2013;i>1950;i--)
{
var j = i;
j = document.createElement('option');
j.text=i;
j.name="year";
j.value=j;
el_sy.appendChild(j);
}
var table = document.getElementById("myTableData");
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var td = document.createElement('TD');
td.width='175';
td.appendChild(el);
tr.appendChild(td);
var td = document.createElement('TD');
td.width='245';
td.appendChild(objLabel);
td.appendChild(objLabel2);
tr.appendChild(td);
var td = document.createElement('TD');
td.width='245';
td.appendChild(el_s);
td.appendChild(el_sm);
td.appendChild(el_sy);
tr.appendChild(td);
myTableData.appendChild(table);
}
</script>
<input type="submit" value="submit"/>
i am dynamically generating form in HTML with the help of javascript on button click named abc. my code is working fine , when i am inserting values ,but when i am posting this form with the help of button the values name and gender is showing in address bar but the DATE ( element name"el_s") selected values is not showing in addressbar.
there are 2 buttons in first displays the div in which form is shown and next one is submit button of form
You must set el_s.name='date' in order for the data to be automatically posted.

Button click in each row in a dynamically created table to retrieve a column value of the corresponding row

//Button click in each row in a dynamically created table to retrieve a column value of the corresponding row
var rowCount = result.rows.length;// to count numrows coming from database
for(var j=1; j<=rowCount; j++)
{
var row = result.rows.item(j-1); // creating rowindex in the table
exercise =row.Exercise; // value from database
time= row.Time; // value from database
userid = row.UserId // value from database
var table = document.getElementById("check"); // table id
var row1 = table.insertRow(j); // Insert Row To Table
var cell1 = row1.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.value = exercise;
cell1.appendChild(element1);
var cell2 = row1.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.value = time;
cell2.appendChild(element2);
var cell3= row1.insertCell(2);
var element3 = document.createElement("input");
element3.type = "button";
element3.value = "edit";
var cell4= row1.insertCell(3);
var element4= document.createElement("input");
element4.value = userid;
cell4.appendChild(element4);
cell4.style.dispalay="none";
element3.addEventListener('click', function () {
alert('event fired!');
// get the userid value of the clicked button as an alert
});
}
First of all assign each of the elements a unique id. For example:
var cell4= row1.insertCell(3);
var element4= document.createElement("input");
element4.type = "text";
element4.value = userId; // from DB
element4.id = "element4-" + j;
cell4.appendChild(element4);
Assign your edit button id = j.
var cell3= row1.insertCell(2);
var element3 = document.createElement("input");
element3.type = "button";
element3.value = "edit";
element3.id = j;
cell3.appendChild(element3);
Then assign onclick handler to your edit button inside the for loop like this:
element3.onclick=doSomething;
Create a function doSomething()
function doSomething() {
for(var j=1; j<=rowCount; j++)
{
var value = document.getElementById("element" + j + "-" + this.id).value;
alert(value);
}
}
Hope this helps.
Try to give some row id and class to the columns then you can use
jQuery(".your_class").click(function(){
var column_value = jQuery(this).html();
});
did you mean something like this ?

Categories