How to delete a hidden input added by jQuery - javascript

I'm trying to create a list of products added from a select in a form using jQuery.
After the addition of those products, I would like to send them with the rest of the form.
The question is when I delete a product, I would also like to remove the hidden input created before.
Could you someone please give me a hand.
Thanks!!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-receta" id="form-receta">
<label for="nombre_receta">Nombre :</label><input id="nombre_receta" name="name_receta" type="text">
<label for="nombre_ingr">Ingredientes:</label><br />
<select style="width:7.7em;display: inline-block;" id="nombre_ingr" name="nombre_ingr">
<option></option>
<option value="1*Prueba">Prueba</option>
<option value="2*Test">Test</option>
</select>
<input id="cantidad_ingr" name="cantidad_ingr" placeholder="cantidad" type="text">
<input id="um_ingr" name="um_ingr" placeholder="U.M" type="text">
<button type="button" class="add-row">ADD</button>
<h3>Ingredientes</h3>
<table>
<tr >
<th>#</th>
<th></th>
<th>Cantidad</th>
<th>U.M</th>
<th>Eliminar</th>
</tr>
<tbody id="tabla-ingr"></tbody>
</table>
<script>
$(document).ready(function(){
var x = 0;
$(".add-row").click(function(){
var id_nombre = $("#nombre_ingr").val();
var res = id_nombre.split("*");
var nombre = res[1];
var id = res[0];
var cantidad = $("#cantidad_ingr").val();
var um = $("#um_ingr").val();
x = x + 1;
var markup = "<tr><td>" + x + "</td><td>" + nombre + "</td><td class=\"text-center\">" + cantidad +
"</td><td class=\"text-center\">" + um + "</td><td class=\"text-center\"><button type=\"button\" class=\"btn btn-xs btn-danger removebutton\"><span class=\"glyphicon glyphicon-remove\"></span>DEL</button></tr>";
$("tbody#tabla-ingr").append(markup);
$('#form-receta').prepend('<input type="hidden" name="_id_ingr[]" value="'+ id +'" />');
$('#form-receta').prepend('<input type="hidden" name="_cantidad_ingr[]" value="'+ cantidad +'" />');
$('#form-receta').prepend('<input type="hidden" name="_um_ingr[]" value="'+ um +'" />');
});
$(document).on('click', 'button.removebutton', function () {
$(this).closest('tr').remove();
return false;
});
});
</script>
Thanks!

You can set an id to those input hidden elements. Then, when you delete the row, you can look for the id of that specific row and delete only the input hidden related to that row.
I hope it makes sense!
$(document).ready(function(){
var x = 0;
$(".add-row").click(function(){
var id_nombre = $("#nombre_ingr").val();
var res = id_nombre.split("*");
var nombre = res[1];
var id = res[0];
var cantidad = $("#cantidad_ingr").val();
var um = $("#um_ingr").val();
x = x + 1;
var markup = "<tr><td>" + x + "</td><td>" + nombre + "</td><td class=\"text-center\">" + cantidad +
"</td><td class=\"text-center\">" + um + "</td><td class=\"text-center\"><button type=\"button\" class=\"btn btn-xs btn-danger removebutton\"><span class=\"glyphicon glyphicon-remove\"></span>DEL</button></tr>";
$("tbody#tabla-ingr").append(markup);
$('#form-receta').prepend('<input type="hidden" name="_id_ingr[]" id="_id_ingr_'+x+'" value="'+ id +'" />');
$('#form-receta').prepend('<input type="hidden" name="_cantidad_ingr[]" id="_cantidad_ingr_'+x+'" value="'+ cantidad +'" />');
$('#form-receta').prepend('<input type="hidden" name="_um_ingr[]" id="_um_ingr_'+x+'" value="'+ um +'" />');
});
$(document).on('click', 'button.removebutton', function () {
var ingrediente_row = $(this).closest('tr');
var ingrediente_id = $(ingrediente_row).children('td')[0].innerHTML;
$('#_id_ingr_' + ingrediente_id).remove();
$('#_cantidad_ingr_' + ingrediente_id).remove();
$('#_um_ingr_' + ingrediente_id).remove();
$(ingrediente_row).remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-receta" id="form-receta">
<label for="nombre_receta">Nombre :</label><input id="nombre_receta" name="name_receta" type="text">
<label for="nombre_ingr">Ingredientes:</label><br />
<select style="width:7.7em;display: inline-block;" id="nombre_ingr" name="nombre_ingr">
<option></option>
<option value="1*Prueba">Prueba</option>
<option value="2*Test">Test</option>
</select>
<input id="cantidad_ingr" name="cantidad_ingr" placeholder="cantidad" type="text">
<input id="um_ingr" name="um_ingr" placeholder="U.M" type="text">
<button type="button" class="add-row">ADD</button>
</form>
<h3>Ingredientes</h3>
<table>
<tr >
<th>#</th>
<th></th>
<th>Cantidad</th>
<th>U.M</th>
<th>Eliminar</th>
</tr>
<tbody id="tabla-ingr"></tbody>
</table>

Simply add a specific class for each hidden field and and pass this no to delete button :
$(document).ready(function(){
var x=0;
$(".add-row").click(function(){
var id_nombre = $("#nombre_ingr").val();
var res = id_nombre.split("*");
var nombre = res[1];
var id = res[0];
var cantidad = $("#cantidad_ingr").val();
var um = $("#um_ingr").val();
x = x + 1;
var markup = "<tr><td>" + x + "</td><td>" + nombre + "</td><td class=\"text-center\">" + cantidad +
"</td><td class=\"text-center\">" + um + "</td><td class=\"text-center\"><button type=\"button\" class=\"btn btn-xs btn-danger removebutton\" data-id='"+x+"'><span class=\"glyphicon glyphicon-remove\"></span>DEL</button></tr>";
$("tbody#tabla-ingr").append(markup);
$('#form-receta').prepend('<input type="hidden" name="_id_ingr[]" class="_hidden_'+x+'" value="'+ id +'" />');
$('#form-receta').prepend('<input type="hidden" name="_cantidad_ingr[]" class="_hidden_'+x+'" value="'+ cantidad +'" />');
$('#form-receta').prepend('<input type="hidden" name="_um_ingr[]" class="_hidden_'+x+'" value="'+ um +'" />');
});
$(document).on('click', 'button.removebutton', function () {
$('._hidden_'+$(this).data('id')).remove();
$(this).closest('tr').remove();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form-receta" id="form-receta">
<label for="nombre_receta">Nombre :</label><input id="nombre_receta" name="name_receta" type="text">
<label for="nombre_ingr">Ingredientes:</label><br />
<select style="width:7.7em;display: inline-block;" id="nombre_ingr" name="nombre_ingr">
<option></option>
<option value="1*Prueba">Prueba</option>
<option value="2*Test">Test</option>
</select>
<input id="cantidad_ingr" name="cantidad_ingr" placeholder="cantidad" type="text">
<input id="um_ingr" name="um_ingr" placeholder="U.M" type="text">
<button type="button" class="add-row">ADD</button>
</form>
<h3>Ingredientes</h3>
<table>
<tr>
<th>#</th>
<th></th>
<th>Cantidad</th>
<th>U.M</th>
<th>Eliminar</th>
</tr>
<tbody id="tabla-ingr"></tbody>
</table>

you can just use Jquery selected type=hidden to remove too, while you click remove botton.
$(document).on('click', 'button.removebutton', function () {
$(this).closest('tr').remove();
$('[type=hidden]').remove();
return false;
});

You can use input[type="hidden"] to remove input elements alone.
Code snippets:
$(document).on('click', 'button.removebutton', function () {
$(this).closest('tr').remove();
$('#form-receta input[type="hidden"]').remove();
return false;
});
Fiddle Demo

If the hidden inputs were added using append(), the order of these inputs woud be the same as shown in the table.
So there is 3 hidden fields created on each ADD click.
On DEL click, we know on wich row the click occured.
So we can deduct the index of the 3 hidden fields to remove.
In your HTML, I added <div id="hiddenInputList"></div> in the form.
Then in the code, to append the hidden fields:
// Append the hidden fields to a div, in the same order as the table.
$('#hiddenInputList').append('<input type="hidden" name="_id_ingr[]" value="'+ id +'" />');
$('#hiddenInputList').append('<input type="hidden" name="_cantidad_ingr[]" value="'+ cantidad +'" />');
$('#hiddenInputList').append('<input type="hidden" name="_um_ingr[]" value="'+ um +'" />');
And then, to remove them:
$(document).on('click', 'button.removebutton', function () {
var thisTR = $(this).closest("tr");
var thisTR_Index = thisTR.index();
console.log("thisTR_Index: "+thisTR_Index);
// Delete the 3 hidden fields (Must do it in the revers order)
$('#hiddenInputList').find("[type='hidden']").eq((thisTR_Index*3)+2).remove();
$('#hiddenInputList').find("[type='hidden']").eq((thisTR_Index*3)+1).remove();
$('#hiddenInputList').find("[type='hidden']").eq(thisTR_Index*3).remove();
// Remove the table row.
thisTR.remove();
return false;
});
In this CodePen, to be make it a visual example... Instead of hidden fields, I used classes.
Added fields are green. And on DEL click, we can see that re right ones are targeted because they turn red.

Related

Dynamically row validation not working - jquery?

I trying to validate dynamically added rows but some faults its not working.
I could'nt find my problem.
Anyone tell me or correct me why its not working n all..
I need to validate dynamically add rows and columns.
Here is my full code..
Full code Fiddle <3
Here is my sample code..
$(document).ready(function() {
$("#ok_button").on("click", function() {
$(".act").val($("#cash_text:first").val());
});
$("#add_Row").on("click", function() {
var counter = 0;
var idVal = $('#tab_logic tr:last').find('td:first').html();
// alert(idVal);
if (idVal === undefined) {
counter = 0;
} else {
var matches = idVal.match(/\d+/g);
// alert(matches);
if (matches != null) {
counter = Number(matches) + counter + 1;
}
}
var newRow = $("<tr>");
var cols = "";
if ($('.price').length > 0) {
var first_ele = document.querySelector('.price').value;
} else {
var first_ele = '';
}
cols += '<td><select class="form-control sel_sel status required" id="accountName' + counter + '" name="accountName" for="accountName" required><option value="">Choose an account</option><option value="1">code 1</option></select></td>';
cols += '<td><input value="' + first_ele + '" type="text" class="form-control required price narr" name="narr" placeholder="Enter your text here" id="acc_narrat' + counter + '" data-toggle="modal" data-target="#narratModal"/></td>';
cols += '<td><input type="number" class="form-control sumTot deb allignAmt" id="cashdeb' + counter + '" min="0" data-action="sumDebit" name="debit" placeholder="Debit amount" onkeypress="restrictMinus(event);" required/></td>';
cols += '<td style="width: 11%;"><button type="button" class="adRow ibtnDel" style="width:30%;position: relative;right: 25%;">x</button></a></td>'
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
if ($("#tab_logic tbody tr").length == 1)
$("#cash_text:first").val('');
evaluateTotal();
});
});
// dynamic row validations
$(document).ready(function() {
$('#contactForm').on('submit', function(event) {
console.log($('.narr'))
$('.status').each(function() {
$(this).rules("add", {
required: true
})
});
$('.narr').each(function() {
$(this).rules("add", {
required: true
})
});
$('.deb').each(function() {
$(this).rules("add", {
required: true
})
});
event.preventDefault();
if ($('#contactForm').validate().form()) {
alert("validates");
} else {
alert("does not validate");
}
});
$('#contactForm').validate();
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- validation cdn -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/css/bootstrapValidator.min.css">
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.2/js/bootstrapValidator.min.js"></script>
<form id="contactForm">
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
<table class="table table-bordered table-hover order-list" id="tab_logic" style="width:100% !important">
<thead>
<tr style="background-color: #680779; color: #fff;">
<th class="text-center">
select code*
</th>
<th class="text-center">
description*
</th>
<th class="text-center">
amount*
</th>
<th class="text-center">
action*
</th>
</tr>
</thead>
</table>
<!-- submit button -->
<div class="form-group col-4 vocSub" style="margin-bottom: 0px !important;">
<div class="col-md-12 cashform_submit" id="">
<input type="submit" class="btn add-btn submit-btn load cashmainBtn" id="cashSub" value="Submit" />
</div>
</div>
</form>
I need to validate dynamically add rows and columns.
Thank you
Important points first about the changes:
There was a problem in the implementation of incrementing the counter so I changed it to a working one first. The problem was you get a NaN value for the counter in the succeeding rows so you will not get a unique name for the succeeding rows. I just created a variable outside that will increment every time the add button is clicked.
I am just showing how to make it work. For me, there's a problem with the framework of how it handles the showing of error messages. What I mean is, the name of the input field should be unique so that the error messages are displayed. This will pose a problem for array type fields like your problem on the backend side. I guess you will have to improvise on the backend.
Here is the summarized code snippet:
let counter = 0;
$(document).ready(function() {
$("#add_Row").on("click", function() {
counter++;
...
cols += '<td><select class="form-control sel_sel status required" id="accountName' + counter + '" name="accountName'+counter+'" for="accountName" required><option value="">Choose an account</option><option value="1">code 1</option></select></td>';
cols += '<td><input value="' + first_ele + '" type="text" class="form-control required price narr" name="narr'+counter+'" placeholder="Enter your text here" id="acc_narrat' + counter + '" data-toggle="modal" data-target="#narratModal"/></td>';
cols += '<td><input type="number" class="form-control sumTot deb allignAmt" id="cashdeb' + counter + '" min="0" data-action="sumDebit" name="debit'+counter+'" placeholder="Debit amount" onkeypress="restrictMinus(event);" required/></td>';
...
});
...
});
...
Please take note of the concatenated counter in the name attributes of the dynamic fields.

Using input value with onkeyup to innerHTML a div

i have been watching some questions here about the same topic but i cant make my code works with the solutions,
I have a dynamic tr table, what i want to do is when i write on the last input of each row a div "result" overwrite like the values, that because i want to make later a connection that shows me users name on my db, like a data live search
JS
function createTable() {
var a;
var r;
a = document.getElementById('tb1').value;
var length = document.getElementById('table').rows.length;
if (a == "") {
alert("Please enter some numeric value");
} else {
var change = document.getElementById("trow1").style.visibility = 'visible';
//var change = document.getElementById("trow2").style.visibility = 'visible';
var changet = document.getElementById("table").style.visibility = 'visible';
var rows = "";
for (var i = 0; i < a; i++) {
r=i+length;
let tr = document.createElement("tr");
tr.innerHTML = "<td>"+r+"</td><td><input type='text' id='" + "parameter".concat(r) + "'></td><td id='tdlmin'><input type='text' id='" + "lmin".concat(r) + "'></td><td id='tdlmax'><input type='text' id='" + "lmax".concat(r) + "'></td><td><input type='text' id='" + "level".concat(r) + "'></td><td><select id='" + "relcal".concat(r) + "' style='width:100%;'><option value='NA'>NA</option><option value='SI'>SI</option></select></td><td><input type='text' id='" + "comment".concat(r) + "' cols=100></td><td><input type='text' id='" + "procown".concat(r) + "' onkeyUp='document.getElementById('result').innerHTML = this.value;'></div></td>";
document.getElementById("table").appendChild(tr);
}
}
}
HTML
<div class="container-fluid">
<div class="row align-items-start">
<div class="col-9">
Numero de Parametros: <input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Crear</button>
<table id="table" class="order-table table" name="table1" required style="visibility:hidden;">
<tr id="trow1" style="visibility:hidden; text-align: center;"><td>#</td><td>Parametro</td><td colspan="2"><table><tr><td colspan="2">Limite</td></tr><tr><td>Min.</td><td>Max.</td></tr></table></td><td><table style="width: 100%;"><tr><td>Nivel</td></tr><tr><td>1 - 4</td></tr></table></td><td>Relevante Calidad</td><td>Comentario</td><td>DueƱo del Proceso</td></tr>
</table>
<button type="button" onclick='subir()'>Subir Parametros</button>
</div>
<div class="col-3">
<div id="result" name="result"></div>
</div>
</div>
</div>
Edit:
This is what i have tried yet:
$('"'+procownid+'"').on("keyup",function(){
var userlike = document.getElementById(procownid).value;
alert(userlike);
});
$("#table tr").on('keyup', procownid, function({
var userlike = document.getElementById(procownid).value;
alert(userlike);
result.innerHTML="<p>"+userlike+"</p>"
});
alert(userlike);
document.getElementById('result').innerHTML="<p>userlike:"+uselike+"</p>";
$.post('getUser',{accion:"ListarUserTPMD",userlike:userlike}, function(data){
result.innerHTML=data;
});
my question is, i can get that when i write on the input it trigger the onkeyup and show me for example the input.value, why i cant make it write on the div?

Value of input text is empty after appending using jQuery

I am dynamically generating a form using AJAX and on the click of a button I add more input fields. But when I enter values in the input field and inspect in developer console,I don't see any value in the input text box.
Code for generating the form
$.ajax({
method: 'GET',
url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
success: function(data) {
if (Object.keys(data).length == 0) {
$.alert({
title: 'Saved',
content: 'Account Number Saved!',
});
var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
$('.EmpTable').append(row);
} else {
$.each(data, function(index, value) {
var rows = ('<div id="form_div"><form method="post"><table class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name"> <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name"> </td><td> <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td> </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form> </div><hr />');
$('.EmpTable').append(rows);
});
}
}
});
Code for appending the row containing the new text box to the form
function add_row(index) {
$rowno = $(".employee_table tr").length;
$rowno = $rowno + 1;
$(".employee_table" + index + " tr:last").after("<tr id= 'row" + $rowno + "' > <td><input type='text' class='form-control Leavename' name='Leavename[]' placeholder='Enter Leave Name'> </td><td> <input type='number' name='LeaveAmount[]' class='form-control LeaveAmount' placeholder='Enter Leave Amount'></td><td> <input type='button' value='x' onclick=delete_row('row" + $rowno + "') ><br></td></tr>");
}
Immediate help will be well appreciated.
EDIT: My loop logic that gave no value when looping through the text boxes of each form generated.
$('#saveAdj').click(function() {
$('form').each(function() {
var thisForm = this;
alert($('.EmpId', thisForm).val());
alert($('.Leavename', thisForm).val());
alert($('.LeaveAmount', thisForm).val());
});
})

How to reset the error number when deleted from list

I'm creating a set of textboxes and some drop downs using jQuery. The add function is working with out any issues.
My problem is with the delete function function works nicely as long as the user deletes one after the other but if the user delete from some where else the number sequence get messed up. Which breaks the 1,2,3,4 ... etc and sets the number which was deleted last.
As an example if the user deletes number 4 out of 7 errors the functions sets the last number as 4 when the user clicks the add button the next number generated will be 5 not the correct last number. I want to rest the rest of the numbers when something get removed from the middle.
I'm storing the last number in a hidden filed called stValue which is getting reset when deleting.
My problem is here I can't get my head around to think of way to reset this when deleting from some where else and then reset the entire error number row numbers when something get removed from the middle. Can you guys help me with this below is my code.
jsFiddle will help to understand better
JQuery:
//Add and remove function for the error text boxes
$(document).ready(function () {
$(document).on('click','.addRow',function () {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/);//Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_'+btnId).prop("disabled", true);//Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function () {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
alert(errNoList);
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_'+errNoList).prop('disabled',false);// Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
});
});
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1)+2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="'+genNum+'" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_'+genNum+'" data-bid="addRow_'+genNum+'" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_'+genNum+'" data-bid="delRow_'+genNum+'" value="Delete"/><br />'
}
HTML:
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%"/>
<input type="hidden" value="1" id="stValue"/>
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add"/>
</div>
</div>
</div>
**UPDATE:**Completely changed the code now it's much more simpler adding the solved answer here so it might help some one in the future.
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var btnId = $("#stValue").val(); //Read the value of stValue
btnId = btnId - 1; //Deduct 1 from the value to get the last ID
//Enables the 1st add button if the value equals 1
if (btnId === 1) {
$('#addRow_' + btnId).prop('disabled', false);
}
$(this).parent().remove(); //Remove the text row from the list.
resetErrorNo(); //Calls the reset function
});
});
//Reset the entire error count number index
function resetErrorNo() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
$("#stValue").val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>
Try with whenever, you delete any row, update all input with new number.
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
Full Code
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_' + errNoList).prop('disabled', false); // Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
rearrange();
});
});
function rearrange() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>

Setting a dropdown selected value when generating a html table using jquery

I am generating a html table with a dropdown and a textbox from an array. I am storing array value property value in textbox and based on the value comin in the key property I want to to set the selected value of the dropdown in each row.
How can I set the dropdown value.
My code is like this. Everything is done I want only to set dropdown selected value.
var filtrnode=[arrayvalue];
$.each(filterNodeData.FilterData, function (i, item) {
debugger;
var newData = filterNodeData.FilterData[i];
trHTML += '<tr><td>' + '<select class="form-control"><option value="and">And</option><option value="or">Or</option></select>' + '</td>' +
'<td>' + '<input class="form-control" size=35 type="text" id="filterValue" value= ' + filterNodeData.FilterData[i].value + '>' + '</td>' +
'<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>' +
'<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>' + '</tr>';
});
$('#filterTable').append(trHTML);
Thanks
You can set it by getting the option selected for that index like,
$.each(filterNodeData.FilterData, function (i, item) {
var newData = filterNodeData.FilterData[i],
value=newData.value,
key = newData.key;
trHTML += '<tr><td>' + '<select class="form-control">'+
'<option value="and" '+(key=='and'?'selected':'')+'>And</option>'+
'<option value="or" '+(key=='or'?'selected':'')+'>Or</option>'+
'</select></td>' +
'<td>' + '<input class="form-control" size=35 type="text" id="filterValue" value= ' + value + '>' + '</td>' +
'<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>' +
'<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>' + '</tr>';
});
$('#filterTable').append(trHTML);
I would do it like this:
$(document).ready(function() {
// store your html as a variable, `` alows you to use lines in string
var row = `
<tr>
<td><select class="form-control"><option value="and">And</option><option value="or">Or</option></select></td>
<td><input class="form-control" size=35 type="text" id="filterValue"></td>
<td><input type="button" id="delFilter" class="delHeader btn btn-md red" value="Delete" onclick="deleteFilter(this)" ></td>
<td><input type="button" id="AddFilter" class="btn btn-md btn-primary" value="Add" onclick="insertFilter()" ></td>
</tr>
`
var filtrnode = [{arrayvalue}];
$.each(filtrnode, function(i, item) {
// make a jQuery object from your html variable
var newRow = $(row);
// and now you are free to use jQuery selectors and functions on it
newRow.find("select option[value="+ item.key +"]").prop("selected", true);
newRow.find("input[type='text']").val(item.value);
$('#filterTable').append(newRow);
});
});
Storing your HTML code as a variable using `` allows you tu use line breaks and create a code which is easier to read. After you create a jQuery object from your stored HTML you can access all of jQuery functions which is cool. This makes your code less prone to mistakes and typos. Here is a jsFiddle.

Categories