error to run function code in javascript has undefined [duplicate] - javascript

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 4 years ago.
A table made containing the edit information field
a problem to run code undifined code in function
please help me to fix this error
"info" id table in html
function submit ()
{
var table = document.getElementById("info");
var td1 = document.createElement("td")
var td2 = document.createElement("td");
var row = document.createElement("tr");
td1.innerHTML = document.getElementById("p-name").value;
td2.innerHTML = document.getElementById("p-id").value;
row.appendChild(td1);
row.appendChild(td2);
table.children[0].appendChild(row);
create button in script
var bedit = document.createElement("BUTTON");
var bename = document.createTextNode("Edit");
bedit.appendChild(bename);
bedit.onclick = function () { edit_row(event) }
td6.appendChild(bedit);}
function code on click button in submit function
function edit_row()
{
bedit.style.display = "none";
bsave.style.display = "block";
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
var string = td1.textContent;
td1.innerHTML = "";
td1.appendChild(input);
input.value = string;
}

Ok, try this. I added some comments.
function submit () {
var table = document.getElementById("info");
var td1 = document.createElement("td")
var td2 = document.createElement("td");
td1.innerHTML = document.getElementById("p-name").value;
td2.innerHTML = document.getElementById("p-id").value;
// create a table row
var row = document.createElement("tr");
row.appendChild(td1);
row.appendChild(td2);
// instead of your append
// table.children[0].appendChild(row);
// use this append
table.appendChild(row);
var bedit = document.createElement("BUTTON");
var bename = document.createTextNode("Edit");
bedit.appendChild(bename);
bedit.onclick = edit_row.bind(null, bedit, td1);
// createtd6 before because it is not known by your previous code
// I use this td2 instead of td6
td2.appendChild(bedit);
}
function edit_row(bedit, td1) {
bedit.style.display = "none";
// create bsave button before because it is not known by your previous code
// bsave.style.display = "block";
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
var string = td1.textContent;
td1.innerHTML = "";
td1.appendChild(input);
input.value = string;
}
submit();
<table id="info"></table>
<hr/>
<input id="p-name" type="text" value="name_value" />
<input id="p-id" type="text" value="id_value" />

Related

How to get values of a full <tr> tag in javascript after on change?

I have created a table inside javascript, with 3 input tags
item_name,
item_value and
quantity.
On change quantity input tag, i want to get the values of all 3 input tags in that particular row to calculate the quantity. How to get the full data of <tr> ?
This is my table,
var tr = document.createElement("tr");
var td = document.createElement("td");
let key = entry[0];
let value = entry[1];
const item_name = document.createElement("input");
item_name.setAttribute("id", "item_name[]");
item_name.setAttribute("name", "item_name[]");
item_name.setAttribute("readonly", "readonly");
item_name.value = key;
td.appendChild(item_name);
tr.appendChild(td);
//$('#receipt_details').append(item_name);
const item_value = document.createElement("input");
item_value.setAttribute("id", "item_value[]");
item_value.setAttribute("name", "item_value[]");
item_value.setAttribute("readonly", "readonly");
item_value.value = value.amount;
//$('#receipt_details').append(item_value);
td.appendChild(item_value);
tr.appendChild(td);
const quantity = document.createElement("input");
quantity.setAttribute("id", "quantity[]");
quantity.setAttribute("name", "quantity[]");
quantity.value = 1;
//$('#receipt_details').append(quantity);
td.appendChild(quantity);
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
$('#receipt_details').append(table);
const total_column = document.createElement("input");
total_column.setAttribute("id", "total_cost[]");
total_column.setAttribute("name", "total_cost[]");
total_column.value = Number(value.amount) * 1;
td.appendChild(total_column);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="receipt_details"></div>
You can try using input event like the following way:
var tr = document.createElement("tr");
var td = document.createElement("td");
let key = 'some key';
let value = {amount:'100'};
const item_name = document.createElement("input");
item_name.setAttribute("id", "item_name[]");
item_name.setAttribute("name", "item_name[]");
item_name.setAttribute("readonly", "readonly");
item_name.value = key;
td.appendChild(item_name);
tr.appendChild(td);
//$('#receipt_details').append(item_name);
const item_value = document.createElement("input");
item_value.setAttribute("id", "item_value[]");
item_value.setAttribute("name", "item_value[]");
item_value.setAttribute("readonly", "readonly");
item_value.value = value.amount;
//$('#receipt_details').append(item_value);
td.appendChild(item_value);
const quantity = document.createElement("input");
quantity.setAttribute("id", "quantity[]");
quantity.setAttribute("name", "quantity[]");
quantity.value = 1;
const total_column = document.createElement("input");
total_column.setAttribute("id", "total_cost[]");
total_column.setAttribute("name", "total_cost[]");
total_column.value = Number(value.amount) * 1;
td.appendChild(total_column);
tr.appendChild(td);
td.appendChild(quantity);
tr.appendChild(td);
const tbody = document.createElement("tbody");
tbody.appendChild(tr);
const table = document.createElement("table");
table.appendChild(tbody);
$('#receipt_details').append(table);
$('table input').on('input', function(){
var parent = $(this).closest('tr');
var value = parent.find('[name="item_value[]"]').val();
var amount = parent.find('[name="quantity[]"]').val();
var total_cost = value * amount;
parent.find('[name="total_cost[]"]').val(total_cost);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="receipt_details"></div>
var value = $('tr').text();
if you can give id or class to the tr then it will be like e.g ( ) then it will be like
var value = $('#tablerow').text();
you can get it like this fiddle
quantity.onchange = function(e) {
var row = {};
$(e.target).closest('tr').find("input:text").each(function() {
row[$(this).attr("name")] = $(this).val();
});
console.log(row);
}

One checkbox at a time JavaScript

Let me start by saying, I have seen very similar questions and yes; I have read through and tried to implement the suggested solutions. I am trying to have it so that only one checkbox in a row can be selected at a time. The most common answer I have seen is this one;
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
This solution did work for me, but that was before I was creating my table dynamically. Here is my code currently. It is pulling the table data from a MySQL table via a JSON $.post.
function load() {
$.post(
"Returnsmedb.php",
function(response) {
var block = []
index = 0;
for (var item in response) {
var objectItem = response[item];
var firstname = objectItem.fname;
var lastname = objectItem.lname;
var username = objectItem.uname;
var email = objectItem.email;
var password = objectItem.password;
var deny = document.createElement("input");
deny.type = "checkbox";
deny.className = "chk";
deny.name = "deny";
deny.id = "deny";
var approve = document.createElement("input");
approve.type = "checkbox";
approve.className = "chk";
approve.name = "approve";
var moreinfo = document.createElement("input");
moreinfo.type = "checkbox";
moreinfo.className = "chk";
moreinfo.name = "moreinfo";
block.push(firstname);
block.push(lastname);
block.push(username);
block.push(email);
block.push(password);
block.push(deny);
block.push(approve);
block.push(moreinfo);
dataset.push(block);
block = [];
}
var data = [" First Name", " Last Name ", " User Name ", " Email ", "Password", " Deny", "Approve", "More Information"]
tablearea = document.getElementById('usersTable');
table = document.createElement('table');
thead = document.createElement('thead');
tr = document.createElement('tr');
for (var i = 0; i < data.length; i++) {
var headerTxt = document.createTextNode(data[i]);
th = document.createElement('th');
th.appendChild(headerTxt);
tr.appendChild(th);
thead.appendChild(tr);
}
table.appendChild(thead);
for (var i = 0; i < dataset.length; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td')); //Added for checkbox
tr.appendChild(document.createElement('td')); //Added for checkbox
tr.appendChild(document.createElement('td')); //Added for checkbox
tr.cells[0].appendChild(document.createTextNode(dataset[i][0]));
tr.cells[1].appendChild(document.createTextNode(dataset[i][1]));
tr.cells[2].appendChild(document.createTextNode(dataset[i][2]));
tr.cells[3].appendChild(document.createTextNode(dataset[i][3]));
tr.cells[4].appendChild(document.createTextNode(dataset[i][4]));
tr.cells[5].appendChild((dataset[i][5])); //
tr.cells[6].appendChild((dataset[i][6])); //
tr.cells[7].appendChild((dataset[i][7])); //
table.appendChild(tr);
}
tablearea.appendChild(table);
}, 'json'
);
}
I have tried pasting the common solution in various areas but I still cannot get it to work. Any help would be greatly appreciated.
Thanks!
Please try this code
$('input.chk').on('change', function() {
if($('this:checked'))
{
var tr =$(this).parents('tr');
tr.find("input.chk").not(this).each(function(){
$(this).prop('checked', false);
});
}
});

Get selected row value using 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);
}

removing textfield in javascript?

I have this problem using javascript whenever I create row and try to remove one, the last row can only removed. here's my javascript
<script>
function createinput(){
var field_area = document.getElementById('fields');
var num = document.forms["zxc"]["set"].value;
for(var count=1;count<=num;count++){
var tr = document.createElement("tr");
var td = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var td4 = document.createElement("td");
var label = document.createElement("label");
var label2 = document.createElement("label");
var label3 = document.createElement("label");
var label4 = document.createElement("label");
var input = document.createElement("input");
var input2 = document.createElement("input");
var input3 = document.createElement("input");
var input4 = document.createElement("input");
input.id = 'qty[]';
input.name = 'qty[]';
input.type = "text";
input.className = "form-control";
input2.id = 'unit[]';
input2.name = 'unit[]';
input2.type = "text";
input2.className = "form-control";
input3.id = 'articles[]';
input3.name = 'articles[]';
input3.type = "text";
input3.className = "form-control";
input4.id = 'serial_number[]';
input4.name = 'serial_number[]';
input4.type = "text";
input4.className = "form-control";
tr.appendChild(td);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
td.appendChild(label);
td2.appendChild(label2);
td3.appendChild(label3);
td4.appendChild(label4);
label.appendChild(input);
label2.appendChild(input2);
label3.appendChild(input3);
label4.appendChild(input4);
field_area.appendChild(tr);
var removalLink = document.createElement('a');
removalLink.className = "remove";
removalLink.onclick = function(){
field_area.removeChild(tr);
}
removalLink.appendChild(document.createTextNode('Remove Field'));
tr.appendChild(removalLink);
}
}
</script>
And here's my HTML.
<form name="zxc" method="post">
<label><input type="text" id="set" name="set"></label><input type="button" onClick="createinput()" value="create" ></form>
<table width="800" id="fields">
<tr>
<th>Quantity</th>
<th>Unit</th>
<th>Article</th>
<th>Serial</th>
</tr>
</table>
I used a for loop to control how many rows can be created.. I can't solve the problem in removing each rows. I need help please!
UPD Working demo http://jsfiddle.net/tarabyte/5TWsv/2/.
You are creating functions in a loop. They will point the same variable. You need
var makeHandler = function(row) {
return function () {
field_area.removeChild(row);
}
};
...
for(...) {
...
removalLink.onclick = makeHandler(tr);
Then num is of type string. You need to convert it to a number
var num = parseInt(document.forms["zxc"]["set"].value);
And ensure num is actually a number
if(!isNaN(num)) {
And finally IDs have to be unique within document! That's why it is called an "identifier".

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.

Categories