Add new row with dropdown on button click - javascript

I'm trying to add new rows on button click:
<div class="row" style="margin: 20px 0;">
<div id="AddContainer">
<!--new rows with content to add will be added here-->
</div>
<br />
<input id="btnAdd" type="button" class="btn btn-success" value="+" />
</div>
and JavaScript:
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(''));
$("#AddContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
var ddlId = $('[id*=hfDDLId]').val();
$('[id$=ddl' + parseInt(ddlId) + ']').remove();
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
$('[id*=hfdropdownids]').val(resultids);
//}
});
function GetDynamicTextBox(value) {
var combo = $("<select></select>").attr("id", value).attr("name", value).attr("runat", "server").attr("class", "class").attr("required", "required");
$.each(document.pvm.SettingsList(), function (i, el) {
combo.append("<option value=" + el + ">" + el + "</option>");
});
return '<input type="button" value="-" class="remove btn btn-danger" />&nbsp'
+ combo + '&nbsp'
+ '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp'
}
function ClearAddTab() {
document.getElementById("AddContainer").innerHTML = "";
}
and the settings list is:
_mVM.SettingsList = ko.observableArray(['France', 'Germany', 'Spain']);
The problem is that I want need to add the dropdown with the SettingsList options for each new added row, but it displays [object object].
It is possible to add the dropdown between the red button and the text field, but also to allow the user to delete that row by pressing the red button?

In this case you want the HTML of the selected DOM object rather than the object itself.
When running function GetDynamicTextBox try combo.prop('outerHTML') when returning the string and you should get the dropdown html rather than [object object].
JsFiddle: jsfiddle.net/fgazfLaz
HTML
<div class="row" style="margin: 20px 0;">
<div id="AddContainer">
<!--new rows with content to add will be added here-->
</div>
<br />
<input id="btnAdd" type="button" class="btn btn-success" value="+" />
</div>
Javascript
var settingsListAry = ['France', 'Germany', 'Spain'];
$("#btnAdd").bind("click", function () {
//var test = GetDynamicTextBox('a');
//alert("test");
var div = $("<div />");
div.html(GetDynamicTextBox(''));
$("#AddContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
var ddlId = $('[id*=hfDDLId]').val();
$('[id$=ddl' + parseInt(ddlId) + ']').remove();
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
$('[id*=hfdropdownids]').val(resultids);
//}
});
function GetDynamicTextBox(value) {
var combo = $("<select></select>").attr("id", value).attr("name", value).attr("runat", "server").attr("class", "class").attr("required", "required");
$.each(settingsListAry, function (i, el) {
combo.append("<option value=" + el + ">" + el + "</option>");
});
return '<input type="button" value="-" class="remove btn btn-danger" />&nbsp'
+ combo.prop('outerHTML') + '&nbsp'
+ '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp'
}
function ClearAddTab() {
document.getElementById("AddContainer").innerHTML = "";
}

First add a <div> inside <div id="AddContainer"> this will hold for appending a new input.
<div id="AddContainer">
<!--new rows with content to add will be added here-->
<div></div>
</div>
Add an onclick event on your button then call this function, it will append a new button:
<script>
function addButton()
{
$('#AddContainer')
.find('div')
.remove()
.end()
.append('<input type="button" value="button"
/><div></div>');
}
</script>
Your input button:
<input id="btnAdd" type="button" onclick="addButton();" class="btn btn-success" value="+" />

Related

remove all field from dynamic add field

I'm working on the following jsfiddle code:
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function() {
var valuesarr = new Array();
var phonearr = new Array();
$("input[name=DynamicTextBox]").each(function() {
valuesarr.push($(this).val());
});
$("input[name=phoneNum]").each(function() {
phonearr.push($(this).val());
});
alert(valuesarr);
alert(phonearr);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> <input name = "phoneNum" type="text" /> <input type="button" value="Remove" class="remove" />';
}
example
It works perfectly but:
I add more then one input field, for example 3 new rows (via add button), then I can remove each line with the "remove button". I would like to "remove all" rows... is it possible with a new button called "remove all" or something similar?
thanks for your help
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function() {
var valuesarr = new Array();
var phonearr = new Array();
$("input[name=DynamicTextBox]").each(function() {
valuesarr.push($(this).val());
});
$("input[name=phoneNum]").each(function() {
phonearr.push($(this).val());
});
alert(valuesarr);
alert(phonearr);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
// remove all input field(s).
$("#btnRemoveAll").bind("click", function() {
$("#TextBoxContainer").empty();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> <input name = "phoneNum" type="text" /> <input type="button" value="Remove" class="remove" />';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="btnAdd" type="button" value="Add" />
<input id="btnRemoveAll" type="button" value="remove all" />
<br />
<br />
<div id="TextBoxContainer">
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />

How could i delete the list from todo app which i want to delete?

I have created a todo list app, it runs prefectly, but there's only one issue, like i created two list and I want to remove the second list, when I click on the remove button of second list it removes me the first list not the second list.
Here is my code, could someone please help me, Thanks in advance.
script.js
function getAndUpdate() {
console.log("Updating List...");
tit = document.getElementById('title').value;
if (localStorage.getItem('itemsJson') == null) {
itemJsonArray = [];
itemJsonArray.push([tit]);
localStorage.setItem('itemsJson', JSON.stringify(itemJsonArray))
}
else {
itemJsonArrayStr = localStorage.getItem('itemsJson')
itemJsonArray = JSON.parse(itemJsonArrayStr);
itemJsonArray.push([tit]);
localStorage.setItem('itemsJson', JSON.stringify(itemJsonArray))
}
update();
}
function update() {
if (localStorage.getItem('itemsJson') == null) {
itemJsonArray = [];
localStorage.setItem('itemsJson', JSON.stringify(itemJsonArray))
}
else {
itemJsonArrayStr = localStorage.getItem('itemsJson')
itemJsonArray = JSON.parse(itemJsonArrayStr);
}
// Populate the table
let tableBody = document.getElementById("tableBody");
let str = "";
itemJsonArray.forEach((element, index) => {
str += `
<tr>
<th scope="row">${index + 1}</th>
<td class ="ele">${element[0]}</td>
<td class="table-buttons" id="spaning-buttons">
<button class="btn btn-sm btn-primary open-modal" id = "open" value="click" onclick = "ShowPopUp()">
<i class="fa fa-book" aria-hidden="true"></i></button><span>Open</span></td>
<td class="table-buttons" id="margin-padding"><button class="btn btn-sm btn-primary delete-btn" onclick="removeItem()"><i class="fa fa-trash" aria-hidden="true"></i></button><span>Delete</span></td>
</tr>`;
});
tableBody.innerHTML = str;
}
add = document.getElementById("add");
add.addEventListener("click", getAndUpdate);
update();
function removeItem(itemIndex) {
if (confirm("Do you want to delete?")) {
console.log("Delete", itemIndex);
itemJsonArrayStr = localStorage.getItem('itemsJson')
itemJsonArray = JSON.parse(itemJsonArrayStr);
// Delete itemIndex element from the array
itemJsonArray.splice(itemIndex, 1);
localStorage.setItem('itemsJson', JSON.stringify(itemJsonArray));
// RemoveLsItem();
update();
}
}
All the problem is that you forgot to pass the element index to the
removeItem method
<td class="table-buttons" id="margin-padding"><button class="btn btn-sm btn-primary delete-btn" onclick="removeItem(${index})"><i class="fa fa-trash" aria-hidden="true"></i></button><span>Delete</span></td>
var i = 1;
function ADDdata () {
var text = $('#txtName').val();
$('#list').append('<ol class="Editdata"></br><span>'+ text + ' </span> <input type="submit" id="edit' + i + '" value="Edit"> ' + '<input type="submit" class="done" id="delete' + i + '" value="Delete"></ol>');
$('#edit' + i).click(function(){
$(this).prev().attr('contenteditable','true');
$(this).prev().focus();
});
$('#delete' + i).click(function(){
$(this).parent().remove();
});
i++;
};
$(function() {
$('#add').on('click', ADDdata);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Todo List</h1>
<input type="text" id="txtName" placeholder="Enter Name">
<input type="submit" id="add" value="Add">
<p>
<ul id="list">
</ul>
</p>

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>

Issues with converting label to input field on button click

I have modified the answer in the post dicussed here.
In my application I have two buttons - edit and save. When clicked on edit, the labels get converted into input fields, where the user can edit the content and save.
Everything is working fine, but the problem is that when the user clicks on the edit button twice, the content in the input fields becomes blank, i.e. the <input> value becomes blank.
Please suggest me a fix for this. Where am I going wrong?
<div id="companyName">
<label class="text-cname"><b>#Html.DisplayFor(m => m.Company)</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" />
</div>
<script>
$(document).ready(function () {
$('#edit').click(function () {
// for company name
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
</script>
You can use replaceWith() method to convert label to textarea.
$("#edit").click(function(){
var text = $("label").text();
$("label").replaceWith("<input value='"+text+"' />");
});
$("#save").click(function(){
var text = $("input ").val();
$("input ").replaceWith("<label>"+text+"</label>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="edit">Edit</button>
<button id="save">Save</button>
<br/><br/>
<label>Text</label>
The most simple fix would be to disable the edit button once you've clicked it, and enable it again after saving:
$(document).ready(function () {
$('#edit').click(function () {
$(this).prop('disabled', true);
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
$('#edit').prop('disabled', false);
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
When you click the second time the value of companyName is empty, that's why the <input> value becomes blank. This is a very simple solution, but you lose the focus on edit box which is easy to fix.
$('#edit').click(function () {
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if(companyName != "")
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
Try This one
function EditContent(){
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if (companyName != "") {
$('.text-cname').text('').append(lblCName);
}
lblCName.select();
}
function SaveContent(){
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="companyName">
<label class="text-cname"><b>Company</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" onclick="SaveContent()" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" onclick="EditContent()" />
</div>

Dynamically add and remove TextBoxes and get value of dynamic TextBox using jQuery and display it in a textbox

i have code where you can add or delete textbox using .append() and .remove() in jquery, now i want to implode all the value of the textboxes separated by commas and pass it into another textbox located outside the script. how can i do it? here's the code for dymically adding and removing textbox. (not mine just got it here in stackoverflow)
HTML:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs /jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
</script>
Use .val() to set value of "another textbox" to values
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox").val(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<input id="anotherTextbox" type="text" />

Categories