Not work JavaScript function delete - javascript

I have the following JavaScript where I get data from a DataBase for my shopping cart. But when I want to delete cart data it does not work my code.
I do not know if I'm getting well into this part of the code
javascript:deleteRow(this).
I leave the complete code of my two functions: listarPedido() and (at the bottom) deleteRow(r).
function listarPedido(){
var articulos = localStorage.getItem("productos");
var productos = articulos.split(";");
var contador = 0;//cuenta numero de articulos en el carrito
for( var i = 0; i < productos.length - 1; i++ ){
var item = productos[i].split(",");
var pedido = "";
for( var j = 0; j < item.length; j++ ){
pedido = '<tr>'+
'<td class="text-center">'+ '<img style="width: 100px; height: 100px" src="' + item[0] + '"/></td>' +
'<td id="celiminar" style="text-align:left;"><b>'+ item[1].toUpperCase() + '<br><br><br><br></b>' +
'<a style="text-decoration:none">Editar</a> | Delete</td>' +
'<td style="text-align:right; color:red"><b>'+ 'S/.'+ item[2] + '</b></td>' +
'<td class="text-center"><b>'
+ '<input type="number" name="txtcant'+i+'" id="txtcant'+i+'" min="1" max="15" value="'+ item[3] +'" class="form-control">' +
'</b></td>'+
'<td style="text-align:right;"><b>'+ 'S/.'+ (item[2]*item[3]).toFixed(2) + '</b></td>';
}
//<i class="fa fa-trash"></i>
$("#detallePedido").append(pedido);
$("#txtcant"+i).change(function(){
resumen();
//al cambiar el numero actualiza el total
$("#detallePedido tr").find("td").eq(4).html('<b>'+ 'S/.'+ (item[2] * $(this).val()).toFixed(2)+ '</b>');
});
contador++;
}
$("#lblnum").text(contador +" ARTÍCULOS");
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById(".table").deleteRow(i);
}

Your code is simply wrong:
document.getElementById(".table").deleteRow(i);
I doubt you have an element with the ID ".table".
Your function, rewritten to get the proper table:
function deleteRow(link) {
var row = link.parentNode.parentNode;
var idx = row.rowIndex;
var table = row.parentNode;
table.deleteRow(idx);
}

Related

Handle javascript dynamically generated controls in controller

I have a project in asp.net core. I have a view where I can do a paste operation from an excel table in an input and the javascript code reads the information and creates input controls with that info. How can I handle all of the controls and send them to the controller via submit? I want to save all of the info.
Javascript Code:
<script>
$(document).ready(function () {
$("#excel").bind('paste',
function (e) {
$("#excel").hide();
$("#div_cargar").hide();
var cells = '';
var i_group = '<div class="form-group row">';
var f_group = '</div>';
//Variables del input del id frente
var i_div_1 = '<div class="col-sm-1">';
var f_div = '</div>';
var label_id = '<label class="control-label col-sm-1" for="id_frente">Frente:</label>';
//variables del input de frente
var i_div_7 = '<div class="col-sm-2">';
var f_div_7 = '</div>';
var label_frente = '<label class="control-label col-sm-1" for="frente">Frente:</label>';
var copy = e.originalEvent.clipboardData.getData('Text');
var rows = copy.split('\n');
var id_frente_in = '';
var frente_in = '';
var id_frente = "";
var frente = "";
//Variables partidas
var label_partida = '<label class="control-label col-sm-1" for="frente">Partida:</label>';
var id_partida_in = '';
var partida_in = '';
var partida = '';
var id_partida = '';
//Variables conceptos
var i_div_2 = '<div class="col-sm-2 ">';
var f_div_2 = '</div>';
var i_div_3 = '<div class="col-sm-3">';
var f_div_3 = '</div>';
var i_div_4 = '<div class="col-sm-4">';
var f_div_4 = '</div>';
var label_concepto = '<label class="control-label col-sm-1" for="frente">Concepto:</label>';
var id_concepto_in = '';
var concepto_in = '';
var concepto = '';
var id_concepto = '';
var contadorparaapartado = 0;
//Variables parametros
var i_div_5 = '<div class="col-sm-8">';
var f_div_5 = '</div>';
var label_parametro = '<label class="control-label col-sm-1" for="frente">Parametro:</label>';
var id_concepto_in = '';
var parametro_in = '';
var parametro = '';
var id_partida = '';
var previousrow = "";
var hr = "";
$.each(rows,
function (index, value) {
//Se valida que no este vacio el value
if (value) {
var columna = rows[index].split("\t");
console.log(columna);
columna[0] = columna[0].replace(/["]/g, "'");
columna[1] = columna[1].replace(/["]/g, "'");
//Se valida si cambia de columna
if (columna[0].split(".").length - 1 == 3) {//FRENTES--------------------------------------------------------
id_frente_in = columna[0];
frente_in = columna[1];
//Se arregla el input del id del frente
id_input =
'<input type="text" class="form-control" id="id_frente" name="id_frente_ek[]" req="" value="' +
id_frente_in +
'">';
id_frente = label_id + i_div_1 + id_input + f_div;
id_frenteactual = id_frente;
//Se arregla el input del frente
frente_input =
'<input type="text" class="form-control input-sm" id="frente" name="frente[]" req="" value="' +
frente_in +
'">';
frente = i_div_7 + frente_input + f_div_7;
frenteactual = id_frenteactual + frente;
//$('.frentes').append(id + frente);
} else if (columna[0].split(".").length - 1 == 4) {//PARTIDAS-----------------------------------------------
id_partida_in = columna[0];
partida_in = columna[1];
//Se arregla el input del id de la partida
id_input =
'<input type="text" class="form-control" id="id_partida" name="id_partida_ek[]" req="" value="' +
id_partida_in +
'">';
id_partida = label_partida + i_div_2 + id_input + f_div;
id_partidactual = id_partida;
//Se arregla el input del frente
partida_input =
'<input type="text" class="form-control input-sm" id="partida" name="partida[]" req="" value="' +
partida_in +
'">';
partida = i_div_3 + partida_input + f_div_4;
partidaactual = id_partidactual + partida;
//$(".partidas").append(id + partida);s
}
else if (columna[0] != "") {//CONCEPTOS-----------------------------------------------
var siguienterow = rows[index + 1].split("\t");
if (siguienterow[0] == "") {
if (previousrow != "") {
concepto_in = columna[0] + " (Apartado: " + previousrow + ") ";
} else {
concepto_in = columna[0];
}
//Se arregla el input del id de la concepto
id_input =
'<input type="text" class="form-control" id="id_concepto" name="id_concepto_ek[]" req="" value="' +
concepto_in +
'">';
concepto = label_concepto + i_div_2 + id_input + f_div_4;
conceptoactual = concepto;
} else {
previousrow = columna[0];
}
}
else if (columna[0] == "" && columna[1] != "") {//PARAMETROS-----------------------------------------------
var siguienterow = rows[index + 1].split("\t");
if (siguienterow[0].split(".").length - 1 == 3) {
hr = '<hr>';
}
parametro_in = columna[1];
//Se arregla el input del id de la parametro
id_input =
'<input type="text" class="form-control" id="id_parametro" name="id_parametro_ek[]" req="" value="' +
parametro_in +
'">';
parametro = conceptoactual + label_parametro + i_div_5 + id_input + f_div_5;
//$(".parametros").append(id);
}
if (id_frente == "") {
$(".frentes").append(i_group +
id_frente +
frente +
id_partida +
partida +
parametro +
f_group);
} else {
$(".frentes").append(hr + i_group + id_frente + frente + id_partida + partida + parametro + f_group);
}
id_frente = "";
frente = "";
id_partida = "";
partida = "";
concepto = "";
parametro = "";
}
});
});
});
View code:
<div class="card-header h4">
Index
<a asp-action="Guardar" class="btn btn-success btn-sm float-right" type="submit" title="Guardar
datos"><i class="fas fa-save"></i></a>
<a asp-action="Index" class="btn btn-light btn-sm float-right" title="Crear nueva persona"><i
class="fas fa-redo"></i></a>
</div>
<div class="card-body">
<label class="text-gray-800" id="div_cargar">Cargar datos aquí:</label>
<input class="form-control" id="excel" />
<div class="form-group">
<form asp-action="Guardar">
<div class="frentes">
</div>
</form>
</div>
</div>
Everything generated from the javascript goes into div class "frentes".
You can use the IFormCollection class to handle the form submission.
Something like:
[HttpPost] // assuming you will be posting
public ActionResult YourActionMethod(IFormCollection data)
{
// if you want to iterate
foreach (var keyValuePair in data)
{
...
}
// or if you want to get by form control name
var name = data["name"];
...
}

external java script "mtree script" not working when element added by jquery dynamically

Here I attach the images where you can see the list of data which show after page load but in all rows but when i add the row using jquery it is not show the data. please check image 2
image first
image 2
This is the link of mtree demo and this is the codepen link
and below is the code that i use to generate row and display mtree.
$(document).ready(function() {
var ite = <?php echo $projectCount; ?>;
$('.btn-row-add').click(function() {
var leaveDays = checkLeaveDays();
console.log(leaveDays);
var ite2 = 1
style = '';
readOnly = '';
if(jQuery.inArray(ite2, leaveDays) !== -1){
style = "style = 'background:#00FF00;'";
readOnly = "readonly='readonly'";
}
var el2 = '<td><input '+style+' '+readOnly+' id="text_'+ite2+'" class="short-textbox" type="text" name="day_'+ite+'[]" value="" onkeyup="sumNewRows(), colsValues(), colsVertical()"></td>';
for(var i=2; i<<?php echo $noOfDays+1; ?>; i++) {
styleInner = '';
readOnlyInner = '';
if(jQuery.inArray(i, leaveDays) !== -1){
styleInner = "style = 'background:#00FF00;'";
readOnlyInner = "readonly='readonly'";
}
el2 = el2 + '<td><input '+styleInner+' '+readOnlyInner+' id="text_'+i+'" class="short-textbox" type="text" name="day_'+ite+'[]" value="" onkeyup="sumNewRows(), colsValues(), colsVertical()"></td>';
}
console.log($('whc-table tbody').html());
var el = '<tr id="data_'+ite+'">\n' +
'<th scope="row">\n' +
'<select class="dropdownlist" data-text-field="name" name="project_name[]" style="width: 300px;">\n' +
'<option value=""></option>\n' +
'</select>\n' +
'\n' +
'</th>\n' +
'<td id="mm-transit">\n' +
'\n' +
'<div class="fake-input">\n' +
'<input value="" name="task_no[]" class="task_list" id="task_list_" type="text" title="Show category list here leter"><img class="show_task" id="show_task" src="<?=base_url()?>images/down.png">\n' +
'\t<div id="cat-list-" class="cat-list"><?php echo $categories_list ?></div>\n' +
'</div>\n' +
'</td>\n' +
el2 +
'\n' +
'<td style="text-align: center;">\n' +
'<input style="width: 35px;" id="text_total_'+ite+'" readonly=\'readonly\' class="short-textbox" type="text" name="total_'+ite+'" value="">\n' +
'</td>\n' +
'</tr>';
ite++;
$(el).appendTo($('#whc-table tbody'));
projectDropdown();
taskDropdown();
initializeMtree();
});
});
Note - same way i used to show mtree in normal rows means rows those are not generated by javascript that is
Try using
$('.btn-row-add').on('click', function() {
instead of
$('.btn-row-add').click(function() {

Javascript getting total sum from wrong checkbox trigger

Below are two different checkbox and the javascript below seems to be trigger by termsChkbx checkbox instead of chosen. How do I change this portion
var chosen = item.parentElement.querySelector('[type="checkbox"]'); ?
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' id='selectChkbx' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
</div>\n";
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
JS:
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("selectChkbx").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total;
}
createCheckbox();
You can try something like this:
JSFiddle
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
<div id="content"></div>
<p id="total">0</p>
Edit 1
I believe reason why you are not getting value is because of element structure. You have a span tag which holds price and another span tag holds checkbox. For such structure, you will have to navigate to that span and fetch its value. Following is depicted below.
Fetching Span's value
var price = chk[i].parentNode.previousSibling.textContent;
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<span>" + num + "</span>";
html += "<span><input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>Check</span><br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
var price = chk[i].parentNode.previousSibling.textContent;
total += parseFloat(price);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
.chk{
}
<div id="content"></div>
<p id="total">0</p>

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

add padding to ui-block-b

When I add a padding-left to class ui-block-b it has the side effect that my fixed navbar gets this padding as well, which I do not want. I would like only to apply the padding to the ui-block-b in my ui-gid-a. So I tried to add a new class ui-block-b-own but i do not get the padding in ui-block-b:
CSS:
.ui-block-b-own {
padding-left: 10px !important
}
And this is the code:
function showDetails(index){
var suchresultat = search(); // gets either rezepte or result
$("#rezept h1").html(suchresultat[index].name);
var inhalt = "";
var p = suchresultat[index].portionen;
var m = suchresultat[index].menge;
var z = suchresultat[index].zubereitung;
var textM = "";
var textZ = "";
for( var i = 0; i < m.length; i++ )
{
textM += "<br />" + m[i];
}
for( var i = 0; i < z.length; i++ )
{
textZ += "<br />" + z[i];
}
var por;
if (p == 1){
por = "Portion:";
}
else {
por = "Portionen:";
}
inhalt += '<section class="ui-grid-a">';
inhalt += '<!-- Row1 -->';
inhalt += '<div class="ui-block-a"><strong>Zutaten für<br>'+ p + ' '+ por +'</strong></div>';
inhalt += '<div class="ui-block-b"><strong>Zubereitung:</strong></div>';
inhalt += '<!-- Row2 -->';
inhalt += '<div class="ui-block-a">' + textM + '</div>';
inhalt += '<div class="ui-block-b ui-block-b-own"' + textZ + '</div>';
inhalt += '</section>';
$("#rezeptInhalt").html(inhalt); // füllt page id rezept content
$.mobile.changePage($("#rezept"));
}
Any ideas what I do wrong?
This looks like it is generating invalid HTML. The element in question is missing its closing > before you insert content via textZ. CSS will therefore not be correctly applied, since the browser is probably guessing as to what the correct text content of the node should be.
inhalt += '<div class="ui-block-b ui-block-b-own">' + textZ + '</div>';
//----------------------------------------------^^^^

Categories