How to update values in json through user input in jquery? - javascript

I have 3 text boxes and when I enter the values and click add button it get added in new JSON and table and when I click particular field to edit it should update the linked json values with the new updated one.
I have two hidden fields:
$(document).ready(function() {
var departments = [{
"dep_id": 1,
"dep_name": "Account",
"deptnum": 10
},
{
"dep_id": 2,
"dep_name": "Software",
"deptnum": 20
},
{
"dep_id": 3,
"dep_name": "Hardware",
"deptnum": 30
},
{
"dep_id": 4,
"dep_name": "IT",
"deptnum": 40
}
];
var json = [];
$("#btn").click(function() {
if ($("#dept").val() && $("#name").val() && $("#eid").val()) {
var eid = $("#eid").val();
var name = $("#name").val();
var dept_id = $('#dept').val();
var counter = $('#counter').val();
counter++;
// var depart = departments.length;
for (var i in departments) {
var dep_obj = departments[i];
if (dep_obj.dep_id == dept_id) {
var dep = dep_obj;
}
}
var emp = {
"eid": eid,
"name": name,
"dept": dep,
};
var j_emp = JSON.stringify(emp);
console.log(j_emp);
json.push(j_emp);
var obj = JSON.parse(j_emp);
var x = '<tr><td id="eidA' + counter + '">' + obj.eid + '</td>' +
'<td id="nameA' + counter + '">' + obj.name + '</td>' +
'<td id="deptA' + counter + '">' + obj.dept.deptnum + '</td>' +
'<td id="deptnoA' + counter + '">' + obj.dept.dep_name + '</td>' +
'<td><input type="button" class="btn btn-primary" value="Edit" id="bEdit' + counter + '" data-id="' + obj.dept.dep_id + '" data-counter="' + counter + '"></td></tr>';
$(" #tab tr:last").after(x);
$("#counter").val(counter);
$("#eid").val('');
$("#name").val('');
$("#dept").val('');
$("#bEdit" + counter).unbind('click');
$("#bEdit" + counter).bind('click', form);
}
});
function form() {
var editCounter = $(this).data('counter');
var id = $(this).data('id');
var eId = $('#eidA' + editCounter).text();
var name = $('#nameA' + editCounter).text();
$('#eid').val(eId);
$('#name').val(name);
$('#dept').val(id);
$('#chosen_counter').val(editCounter);
$('#btn').hide();
$('#btn1').show();
$("#btn1").unbind('click');
$("#btn1").bind('click', update);
}
function update() {
var second = [];
var counter = $('#chosen_counter').val();
var eid = $('#eid').val();
var name = $('#name').val();
var dept_id = $('#dept').val();
for (var i in departments) {
var dep_obj = departments[i];
if (dep_obj.dep_id == dept_id) {
var dep = dep_obj;
}
}
var a = $('#eidA' + counter).text(eid);
var b = $('#nameA' + counter).text(name);
var c = $('#deptA' + counter).text(dep.deptnum);
var d = $('#deptnoA' + counter).text(dep.dep_name);
$('#bEdit' + counter).data('id', dep.dep_id);
$('#eid').val('');
$('#name').val('');
$('#dept').val(0);
$('#chosen_counter').val(0);
$("#btn1").unbind('click');
$("#btn").show();
$("#btn1").hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="counter" value="0" />
<input type="hidden" id="chosen_counter" value="0" />
<input type="text" class="input" id="eid" />
<input type="text" class="input" id="name" />
<select class="input" id="dept">
<option value="0">Select department</option>
<option value="1">10</option>
<option value="2">20</option>
<option value="3">30</option>
<option value="4">40</option>
</select>
<input type="button" class="btn btn-success" value="Save" id="btn">
<input type="button" class="btn btn-success" value="Update" id="btn1">
<div class="show">
<table id="tab" class="table table-bordered">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Dept_No</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I tried this:
But I think I am doing it wrong...I am new to this so its hard for me to understand.. I am able to fetch these values in new json but I don't know to update the values in old one.
emp.foreach(function check(value, index, array) {
if (value.choosencounter == counter) {
emp[index].eid = eid;
emp[index].name = name;
emp[index].deptA = dep_val;
emp[index].deptnoA = dep_name;
}
});

Here you go, I think you could easy understand the code.
var j_emp = [];
var currentEditID = 0;
var departments = [{
"dep_id": 1,
"dep_name": "Account",
"deptnum": 10
},
{
"dep_id": 2,
"dep_name": "Software",
"deptnum": 20
},
{
"dep_id": 3,
"dep_name": "Hardware",
"deptnum": 30
},
{
"dep_id": 4,
"dep_name": "IT",
"deptnum": 40
}
];
$(document).ready(function() {
$("#btn").click(function() {
if ($("#dept").val() && $("#name").val() && $("#eid").val()) {
var emp = fetchFieldValues();
j_emp.push(emp);
renderTable();
clearFieldValues();
}
});
});
function edit(item) {
let id = $(item).attr('id');
currentEditID = id;
let emp = j_emp.filter(e => {
return e.id == id;
})[0];
$('#eid').val(emp.eid);
$('#name').val(emp.name);
$('#dept').val(emp.dept.dep_id);
$('#btn').hide();
$('#btn1').show();
}
function update(prevVal) {
var emp = fetchFieldValues();
for (var i = 0; i < j_emp.length; i++) {
if (j_emp[i].id == currentEditID) {
j_emp[i] = emp;
j_emp[i].id = currentEditID;
}
}
renderTable();
clearFieldValues();
$("#btn").show();
$("#btn1").hide();
}
function renderTable() {
$("#tab tbody").empty();
let html = '';
j_emp.forEach(obj => {
html += '<tr><td>' + obj.eid + '</td>' +
'<td>' + obj.name + '</td>' +
'<td>' + obj.dept.deptnum + '</td>' +
'<td>' + obj.dept.dep_name + '</td>' +
'<td><input type="button" class="btn btn-primary edit-button" id="' + obj.id + '" value="Edit" onclick="edit(this)"></td></tr>';
});
$("#tab tbody").append(html);
}
function fetchFieldValues() {
return {
"eid": $("#eid").val(),
"name": $("#name").val(),
"dept": departments.filter(e => {
return e.dep_id == $('#dept').val();
})[0],
'id': new Date().getTime()
};
}
function clearFieldValues() {
$("#eid").val('');
$("#name").val('');
$("#dept").val('');
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<input type="hidden" id="counter" value="0" />
<input type="hidden" id="chosen_counter" value="0" />
<input type="text" class="input" id="eid" />
<input type="text" class="input" id="name" />
<select class="input" id="dept">
<option value="0">Select department</option>
<option value="1">10</option>
<option value="2">20</option>
<option value="3">30</option>
<option value="4">40</option>
</select>
<input type="button" class="btn btn-success" value="Save" id="btn">
<input type="button" class="btn btn-success" value="Update" id="btn1" onclick="update()">
<div class="show">
<table id="tab" class="table table-bordered">
<thead>
<tr>
<th>Emp_ID</th>
<th>Name</th>
<th>Dept_No</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

Related

Group all the similar id as one in jquery

I create an dyamic form with Jquery, there will be the multiple select box and textbox, how can I group the data into one based on the user name. For example, there will be the multiple select box = lim, total = 20, how can I group this 2 into array as 1.
When click the save button the final data will be like below
array(
'lim' => 40,
'tan' => 10,
);
Code here: https://jsfiddle.net/7gbvfjdc/
You mean something like this ?
You save button event listener should have following code
$('.savebtn').on('click', function() {
var mapObj = {};
$('.listable .cb').each(function(index, item) {
var selectVal = $(this).find('select').val();
if (mapObj[selectVal]) {
mapObj[selectVal] += Number($(this).find('#amt1_' + index).val());
} else {
mapObj[selectVal] = Number($(this).find('#amt1_' + index).val());
}
});
console.log(mapObj);
});
var i = 0;
$('.addRow').on('click', function() {
addRow();
});
function addRow() {
var tr = '<tr class="cb" id="row_' + i + '"><td>';
tr += '<select class="form-control select2" id="name1_' + i + ' first" name="name[]">';
tr += '<option>tan</option><option>lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_' + i + '" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function() {
var mapObj = {};
$('.listable .cb').each(function(index, item) {
var selectVal = $(this).find('select').val();
if (mapObj[selectVal]) {
mapObj[selectVal] += Number($(this).find('#amt1_' + index).val());
} else {
mapObj[selectVal] = Number($(this).find('#amt1_' + index).val());
}
});
console.log(mapObj);
});
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center">+</th>
</tr>
</thead>
<tbody class="text-center">
</tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
You can use reduce on the body trs to extract the data and sum it in the wanted object format. Like this:
const result = $('tbody tr').get().reduce((prev, ne) => {
const $this = $(ne);
const type = $this.find('select').val();
prev[type] += parseInt($this.find('input').val())
return prev;
}, {
lim: 0,
tan: 0
});
var i = 0;
$('.addRow').on('click', function() {
addRow();
/*
$('.select2').select2({
theme: 'bootstrap4',
ajax: {
url: '{{ route("getMember") }}',
dataType: 'json',
},
}); */
});
function addRow() {
i++;
var tr = '<tr id="row_' + i + '"><td>';
tr += '<select class="form-control select2" id="name1_' + i + ' first" name="name[]">';
tr += '<option>tan</option><option>lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_' + i + '" class="form-control"></td>';
/* tr += '<td><select class="form-control select2" id="name2_'+i+'" name="name2[]">';
tr += '<option>tan</option><option>lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt2_'+i+'" class="form-control"></td>'; */
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function() {
$(this).parent().parent().remove();
});
$('button').on('click', () => {
const result = $('tbody tr').get().reduce((prev, ne) => {
const $this = $(ne);
const type = $this.find('select').val();
prev[type] += parseInt($this.find('input').val())
return prev;
}, {
lim: 0,
tan: 0
});
console.log(result)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th>Second name</th>
<th>Second amount</th>
<th style="text-align:center">+</th>
</tr>
</thead>
<tbody class="text-center">
</tbody>
</table>
<button>
save
</button>
https://jsfiddle.net/moshfeu/20kczto7/14/

How to send a table html as a serialize array to database?

I want to send my javascript and dynamic table to my database as a text variable.
I explained whatever I did:
I used jquery to get the values
Then I stored HTML table values in a java script array
I converted javascript array to JSON format
I sent JSON array to a php script by JQuery AJAX
But, I don’t know how to send it to database?
Here is my code:
function readTblValues() {
var TableData = '';
$('#tbTableValues').val(''); // clear textbox
$('#tblDowntimes tr').each(function(row, tr) {
TableData = TableData +
$(tr).find('td:eq(1)').text() + ' ' // downtime
+
$(tr).find('td:eq(2)').text() + ' ' // equipment
+
$(tr).find('td:eq(3)').text() + ' ' // starttime
+
$(tr).find('td:eq(4)').text() + ' ' // finishtime
+
$(tr).find('td:eq(5)').text() + ' ' // descriptio
+
'\n';
});
$('#tbTableValues').html(TableData);
}
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').html('<br>JS Array: <br>' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#tblDowntimes tr').each(function(row, tr) {
TableData[row] = {
"DOWNTIME": $(tr).find('td:eq(1)').text(),
"equipment": $(tr).find('td:eq(2)').text(),
"startdowntime": $(tr).find('td:eq(3)').text(),
"finishdowntime": $(tr).find('td:eq(4)').text(),
"description": $(tr).find('td:eq(5)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').html('<br>JSON array: <br>' + TableData.replace(/},/g, "},<br>"));
}
function sendTblDataToServer() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbSendTblDataToServer').val('JSON array to send to server: <br<br>' + TableData.replace(/},/g, "},<br>"));
$.ajax({
type: "POST",
url: "test.php",
data: "pTableData=" + TableData, // post TableData to server script
success: function(msg) {
// return value stored in msg variable
$('#tbServerResponse').html('Server Response:<br><br><pre>' + msg + '</pre>');
}
});
}
function print_r(arr, level) {
var dumped_text = "";
if (!level)
level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++)
level_padding += " ";
if (typeof(arr) === 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof(value) === 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
}
return dumped_text;
}
<html>
<head>
</head>
<body>
<form name="data-entry" method="post" action="data-entry.php">
<input id="product-name" name="product-name" />
<input id="product-quantity" name="product-quantity" />
<input name="Downtime" id="Downtime" />
<input name="equipment" id="equipment" />
<input type='time' name='startdowntime' id='startdowntime' />
<input type='time' name='finishdowntime' id='finishdowntime' />
<input type='text' name='description' id='description' />
<input type="button" value="add rows" id="btnAdd" onclick="addDowntime(this)" />
<input type="button" value="remove rows" onclick="deleteSelected()" />
<table id="tblDowntimes" class="downtime">
<tr>
<th><input type="checkbox" id="chkAll" onclick="chkAll_click(this)" /></th>
<th>downtime</th>
<th>equipment</th>
<th>start-time</th>
<th>finih-time</th>
<th>description</th>
</tr>
</table>
<input type="button" value="1. Read Table Values" name="read" onClick="readTblValues()" />
<input type="button" value="2. Store values in JS Array" name="store" onClick="storeAndShowTableValues()" />
<input type="button" value="3. Convert JS Array to json" name="convert" onClick="convertArrayToJSON()" />
<input type="button" value="4. Send json array to Server" name="send" onClick="sendTblDataToServer()" />
<div id="tbTableValues"></div>
<div id="tbTableValuesArray"></div>
<div id="tbConvertToJSON"></div>
<div id="tbServerResponse"></div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
and Here is my php code:
function processJSONArray() {
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData);
var_dump($tableData);
}
echo processJSONArray();
With aforementioned code, I manage to get the array in client side, but when I use this code that error is appeared (Undefined variable: tableData)
if(isset($_POST[‘submit’])){
echo $tableData;
}

populate json data in tables

javascript code
$(function(){
$(".user").on("click",function(e){
e.preventDefault();
var email = $(this).data("email");
$.ajax({
data:{email:email},
type: "POST",
url: 'getUser_detail.php',
success: function(data) {
var data = JSON.parse(data);
for (var i = 0; i < data['basic'].length; i++) {
$('#inputs').append('<label>Email:</label><input type="text" readonly class="form-control-plaintext" value="' + data['basic'][i].email + '" name="email[]" size="15">');
$('#inputs').append('<label>Password:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Pass +'" name="pass[]" size="5">');
$('#inputs').append('<label>Status:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].status +'" name="pass[]" size="5">');
$('#inputs').append('<label>Acc. Address:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Accno +'" name="pass[]" size="44">');
$('#inputs').append('<label>Balance:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].bal +'" name="pass[]" size="10">');
}
for( var j = 0; j<data['detail'].length; j++) {
var List = ["<tr><td>" + data['detail'][i].type + "</td><td>"+data['detail'][i].DB+"</td><td>"+data['detail'][i].LD+"</td><td>"+data['detail'][i].Prof+"</td><td>"+data['detail'][i].Server_stat+"</td></tr>"];
}
$("#bodywallet").append(List);
},
});
});
})
html code
<table class="table" id="wallet">
<thead class=" text-primary">
<tr>
<th class="text-left">Type</th>
<th class="text-left">Date_Bought</th>
<th class="text-left">Expires</th>
<th class="text-left">Profit</th>
<th class="text-left">Status</th>
</tr>
</thead>
<tbody class="text-left" id="bodywallet" >
</tbody>
</table>
this is what my data should be display on table
but it is displaying the first record only
i have checked json is bringing all the required data. what i have done wrong what is the mistake.any help will be appreciated. thanks
php code
while($row2 = mysqli_fetch_array($alEmailrslt))
{
$json_array['detail'][] = $row2;
}
echo json_encode($json_array);
You are putting everything in an array I and appending it every round.
You should use something like this instead:
success: function (data) {
var data = JSON.parse(data);
var list = []; // only one array
for (var j = 0; j < data['detail'].length; j++) {
// push to this array instead of overwriting the variable
list.push("<tr><td>" + data['detail'][j].type + "</td><td>" + data['detail'][j].DB + "</td><td>" + data['detail'][j].LD + "</td><td>" + data['detail'][j].Prof + "</td><td>" + data['detail'][j].Server_stat + "</td></tr>");
}
// update html once
// the join "glues" all parts of the array into one string
$("#bodywallet").append(list.join());
}
I think your list is not getting updated every time and the simplest approach would be, please find below code snippet:
$(document).ready(function() {
this.json = {
"Students": [{
"id": "1",
"hometown": "London",
"gender": "Male",
"GPA": "8",
"name": "Lee",
},
{
"id": "2",
"hometown": "NY",
"gender": "Male",
"GPA": "9",
"name": "Shaldon",
}, {
"id": "3",
"hometown": "Paris",
"gender": "Female",
"GPA": "7",
"name": "Julie",
}
]
};
this.renderTable = function(Students) {
var tbody = document.getElementById('tbody');
tbody.innerHTML = "";
for (var i = 0; i < Students.length; i++) {
var tr = "<tr>";
tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
tr += "<hr>";
tbody.innerHTML += tr;
}
}
this.renderTable(this.json.Students);
console.log(this.json.Students);
//code for filtering//
this.Filter = function() {
var search = document.getElementById('search');
var category = document.getElementById('category');
var filteredObj = this.json.Students;
filteredObj = $.map(this.json.Students, function(val, key) {
if (search.value === val[category.value]) return val;
});
filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>
<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
<option value = "id">ID</option>
<option value = "hometown">HomeTown</option>
<option value = "gender">Gender</option>
<option value = "GPA">GPA</option>
<option value = "name">NAME</option>
</select>
<button onclick="Filter()">Filter</button>
<table>
<tbody id="tbody"></tbody>
</table>

How can I set up a button handler to remove a parent table row?

I have this HTML & jQuery project, and everything currently works perfectly for what I want them to do. What I need right now is to add a Delete/Remove Button that is linked to this line:
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
As you can see the buttons are visible only if you click the add button and create a new TR with values.
I tried creating a jQuery function:
function removeThis(a) {
$('tr-' + 'a').remove();
}
But of course, it's not doing what I need it to do.
Can anyone help me resolving this?
Thanks in advance.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
$('tr-' + 'a').remove();
}
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >
I don't want any of the other functions to be deleted.
BTW the Delete button is already added with ID removeThis.
Thank you very much in advance.
You can achieve this without jQuery at all, and I highly recommend that.
function removeThis(e){
const parentTd = e.parentNode;
const parentTr = parentTd.parentNode;
const parentTable = parentTr.parentNode;
return parentTable.removeChild(parentTr);
}
And on your button you do
<button onClick='removeThis(this)'>Delete me</button>
This way you create a testable and reusable function that you can use to remove all DOM Elements.
Oh, and by the way, this way you work from inside-out rather than querying the whole document for the element intended to remove.
Your example function below builds a string 'tr-' + 'a' which will always just look for "tr-a":
function removeThis(a) {
$('tr-' + 'a').remove();
}
Just remove the quotes from around 'a':
function removeThis(a) {
$('tr-' + a).remove();
}
Remove the quotes around the letter 'a' so you can use the variable there:
function removeThis(a) {
$('.tr-' + a).remove();
}
You should also consider using a different way to number the table rows. The row numbers will start to get reused if you delete a row and then add a new one:
Row 0, Row 1, Row 2, Row 3, Row 4
Add row. There are 5 rows, so the new row is row 5.
Row 0, Row 1, Row 2, Row 3, Row 4, Row 5
Remove row 1.
Row 0, Row 2, Row 3, Row 4, Row 5
Add row. There are 5 (!!!) rows, so the new row is (also!!!) row 5.
Row 0, Row 2, Row 3, Row 4, Row 5, Row 5
Instead of getting a new value for tr every time you add a row, instead consider a global variable that you increment every time you add a row:
var rowCounter = 0;
function addNewTr() {
//snip
rowCounter++;
$('table tbody').append('' +
'<tr class="tr-' + rowCounter + '">' +
//snip
}
I think you just need to remove the quotes from 'a':
function removeThis(a) {
$('.tr-' + a).remove();
}
EDIT: This snippet is totally working! I did need to add a dot before 'tr' since it is a class.
$(document).ready(function () {
$('.buttons').on('click', 'button.hide', function () {
console.log('hide');
$('form').hide();
});
$('.buttons').on('click', 'button.add', function () {
console.log('add');
var edit = $('#edit');
editRow = $('#editRow');
edit.show();
if (!($('#addNew').length)) {
edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
}
if (editRow) {
editRow.remove();
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
});
$('#show').click(function () {
//$('form').show();
//$('#btd1').val('Vlad');
//$('#btd2').val('Andrei');
//$('#btd3').val('vTask');
// $('#btd4').val('Ceva');
//$('#btd5').val('Alceva');
});
});
function edit(a) {
var edit = $('#edit');
addNew = $('#addNew');
editRow = $('#editRow');
edit.show();
if (addNew) {
addNew.remove();
}
if (editRow.length) {
editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
} else {
edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
}
$.each($('.tr-' + a).find('td'), function (key, val) {
$('form#edit input[type=text]').eq(key).val($(val).text());
});
}
function save(a) {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please complete all the colums' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
$('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
}
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
$('#editRow').remove();
}
}
function addNewTr() {
var tr = $('tr');
valid = true;
message = '';
$('form#edit input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table tbody').append('' +
'<tr class="tr-' + tr.length + '">' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons">' +
'<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
'<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
'</td >' +
'</tr>' +
'');
for (var x = 1; x < $('input').length; x++) {
$('#btd' + x).val('');
}
}
}
function removeThis(a) {
alert('.tr-'+a);
$('.tr-' + a).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html >
<head >
<link href="../css/vtask.css" rel="stylesheet">
<title >vTask</title >
<h1 id="hh1">[<a id="vt1">vTask</a>]</h1>
</head >
<body>
<table class="greenTable">
<tr><td colspan="6"><form id="edit" action="" method="post" hidden >
<label for="btd1" ></label >
<input type="text" name="Name" id="btd1" value="" placeholder="Name">
<label for="btd2" ></label >
<input type="text" name="Secondary Name" id="btd2" value="" placeholder="Secondary Name">
<label for="btd3" ></label >
<input type="text" name="Email" id="btd3" value="" placeholder="Email">
<label for="btd4" ></label >
<input type="text" name="Telephone" id="btd4" value="" placeholder="Telephone">
<label for="btd5" ></label >
<input type="text" name="Password" id="btd5" value="" placeholder="Password">
</form ></td></tr>
<tr>
<td width="10%">Name</td>
<td width="10%">Secondary Name</td>
<td width="10%">Email</td>
<td width="10%">Telephone</td>
<td width="10%">Password</td>
<td class="buttons" width="20%"><button class="add" >Add</button >
<button class="hide" >Hide</button ></td>
</tr>
</table >
<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body >
</html >

Problems with creating dynamically <select/>

<script type="text/javascript">
var a = new Array();
function obj(type, value) {
this.type = type;
this.value = value;
this.toStr = toStr
}
function toStr() {
if (this.type == "select") {
var temp = "";
var arr = this.value.split("/");
for (i = 0; i < arr.length; i++) {
temp += "<option>" + arr[i] + "</option>"
}
return "<select>" + temp + "</select><br>";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "'><br>";
}
function addObj(type) {
var sel = parent.frames["left"].document.form1.q.value;
for (i = 0; i < sel; i++)
a[a.length] = new obj(type,
parent.frames["left"].document.form1.caption_text.value,
a.length);
paint();
parent.frames["left"].document.form1.caption_text.value = "";
}
function paint() {
parent.frames["right"].document.open()
for (i = 0; i < a.length; i++)
parent.frames["right"].document.writeln(a[i].toStr())
parent.frames["right"].document.close()
}
</script>
<form name=form1>
<table>
<tr>
<td><input type="button" style="width: 150px" value="Add Button" onClick="addObj('button')"><br />
<input type="button" style="width: 150px" value="Add TexBox" onClick="addObj('text')" /><br />
<input type="button" style="width: 150px" value="Add Select" onClick="addObj('select')" /></td>
<td>Text : <br /> Number of adding elements:<br /></td>
<td><input type="text" name="caption_text" style="width: 150px"> <br /> <select
NAME=q size=1 style="width: 150px">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
</table>
</FORM>
Code is corrupting when creating select elements.
What's wrong with this code?
Thanks in advance.
Your i variables are missing a var declaration. All loops use the same counter, which means that nested loops will break horribly. My suggestion:
var a = [];
function FormElement(type, value) {
this.type = type;
this.value = value;
}
FormElement.prototype.toString = function toStr(){
if (this.type == "select") {
var arr = this.value.split("/");
for (var i = 0; i < arr.length; i++) {
arr[i] = "<option>" + arr[i] + "</option>"
}
return "<select>" + arr.join("") + "</select><br />";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "' /><br />";
};
function addObj(type) {
var form = parent.frames["left"].document.form1;
var sel = form.q.value;
for (var i = 0; i < sel; i++)
a.push(new FormElement(type, form.caption_text.value);
paint();
form.caption_text.value = "";
}
function paint() {
var doc = parent.frames["right"].document;
doc.open();
doc.write(a.join("\n"));
doc.close();
}

Categories

Resources