How to insert fields using jQuery? - javascript

I'm trying to realise this code in the snippet, for the moment I'm working only on the button Label, so when I click on this button, it adds a small formular that allows to creat this a label in the right side by clicking on OK. However, even if I click on OK nothing happens, normally a label should appear with the name inserted in the textfield "label".
Does anyone know where is the problem? Thank you in advance.
$(function(){
$('button').click(function(){
var typeButton = $(this).text();
if(typeButton=='Label'){
$('hr').remove();
$('#formule').remove();
$('#droite').append('<hr>');
var elementLabel = 'Texte du label';
var elementTexte = '<input type="text" name="label"/>';
var elementButton = '<button>OK</button>';
var elementSpan = elementLabel+' '+elementTexte+' '+elementButton;
var elementDiv = '<div id="formule">'+elementSpan+'</div>'
$(elementDiv).insertAfter('hr');
};
if(typeButton=='OK'){
$('hr').remove();
var elementNom = $('input[name=label]').val();
var elementSpan = '<span>'+elementNom+'</span>';
$('#formule').remove();
$('#gauche').append('elementSpan');
};
});
});
body {
margin: 0;
}
#gauche {
float: left;
width: 70%;
height: 1000px;
background-color: #EFECCA;
}
#droite {
background-color: #CEFFF8;
height: 1000px;
padding : 10px;
padding-left: 71%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="gauche">
</div>
<div id="droite">
Utilisez ces boutons pour créer votre formulaire<br><br>
<button>Label</button>
<button>Zone de texte</button>
<button>Bouton</button>
</div>

you need to delegate dynamically added elements using on event handler attachment with the document.
$(document).on('click', 'button', function () {
var typeButton = $(this).text();
if (typeButton == 'Label') {
$('hr').remove();
$('#formule').remove();
$('#droite').append('<hr>');
var elementLabel = 'Texte du label';
var elementTexte = '<input type="text" name="label"/>';
var elementButton = '<button>OK</button>';
var elementSpan = elementLabel + ' ' + elementTexte + ' ' + elementButton;
var elementDiv = '<div id="formule">' + elementSpan + '</div>'
$(elementDiv).insertAfter('hr');
};
if (typeButton == 'OK') {
$('hr').remove();
var elementNom = $('input[name=label]').val();
var elementSpan = '<span>' + elementNom + '</span>';
$('#formule').remove();
$('#gauche').append(elementSpan);
};
});

It's because the button that gets generated to the DOM (OK) doesn't have an event listener attached to it, so it has nothing to do when being pressed. $('button').click() doesn't get updated any time the DOM changes, so you have to do it yourself.
$(function() {
function listenToButtons() {
$('button').off().on('click', function() {
var typeButton = $(this).text();
if (typeButton == 'Label') {
$('hr').remove();
$('#formule').remove();
$('#droite').append('<hr>');
var elementLabel = 'Texte du label';
var elementTexte = '<input type="text" name="label"/>';
var elementButton = '<button>OK</button>';
var elementSpan = elementLabel + ' ' + elementTexte + ' ' + elementButton;
var elementDiv = '<div id="formule">' + elementSpan + '</div>'
$(elementDiv).insertAfter('hr');
listenToButtons();
};
if (typeButton == 'OK') {
$('hr').remove();
var elementNom = $('input[name=label]').val();
var elementSpan = '<span>' + elementNom + '</span>';
$('#formule').remove();
$('#gauche').append('elementSpan');
};
});
}
listenToButtons();
});

Related

form not clearing properly after submit and also for hidden input

I'm using a parsley validator and somehow it affects my form. After submission, it won't clear all the inputs; especially hidden inputs. And when I tried to set some input value from javascript it won't show up.
I think it's because of my <form method="post" id="transaction_form">. I've tried to re-evaluate my HTML but still, it won't work properly.
$(document).ready(function () {
$("#cust_num").val(55555);
var exam_num = 12345;
var prod_num = 88998;
var prod_name = "Hello";
var prod_price = 150000;
var transactionTable = $("#transaction_table");
var trxprodcount = 0;
var subTotal = 0;
var endTotal = 0;
function clearinput() {
$("#transaction_form")[0].reset();
$("#transaction_form").parsley().reset();
//$('#get_productdata').attr('disabled', 'disabled');
$("#subtotal").html(0);
$("#endtotal").html(0);
}
clearinput();
function recount() {
subTotal = transactionTable.DataTable().column(3).data().sum();
$("#subtotal").html(subTotal);
endTotal = subTotal - (subTotal * $("#trx_disc").val()) / 100;
$("#endtotal").html(endTotal);
}
transactionTable.DataTable({
ordering: false,
responsive: true,
searching: false,
paging: false,
info: false,
fnRender: function (Obj) {
return "Rp" + Obj.Data[3];
},
drawCallback: function () {
recount();
},
});
$("#trx_disc").on("change", function () {
recount();
});
trxprodcount = trxprodcount + 1;
var exam_num = $("#cust_num").val() + "S" + trxprodcount;
var col_exam_num =
exam_num +
'<input type="hidden" name="hidden_exam_num[]" id="exam_num' +
trxprodcount +
'" class="exam_num" value="' +
exam_num +
'" />';
var col_exam_prod =
prod_num +
'<input type="hidden" name="hidden_exam_prod[]" id="exam_prod' +
trxprodcount +
'" value="' +
prod_num +
'" />';
var del_btn =
'<button type="button" name="del_prodtrx" id="' +
trxprodcount +
'" class="btn btn-danger btn-sm del_prodtrx" >Delete</button>';
transactionTable
.DataTable()
.row.add([col_exam_num, col_exam_prod, prod_name, prod_price, del_btn])
.draw()
.node();
$("#transaction_table").on("click", ".del_prodtrx", function () {
var row = $(this).parents("tr");
if ($(row).hasClass("child")) {
transactionTable.DataTable().row($(row).prev("tr")).remove().draw();
} else {
transactionTable.DataTable().row($(this).parents("tr")).remove().draw();
}
});
$("#transaction_form").on("submit", function (event) {
event.preventDefault();
if ($("#transaction_form").parsley().isValid()) {
var count_data = 0;
$(".exam_num").each(function () {
count_data = count_data + 1;
});
if (count_data > 0) {
clearinput();
} else {
$("#message").html(
'<div class="alert alert-danger">Customer/Product Kosong'
);
}
setTimeout(function () {
$("#message").html("");
}, 3000);
}
});
});
Live Example: https://jsfiddle.net/azissofyanp/9p7j1d6u/30/
And I'm very confused about it.

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

Read formatted text from form through javascript

class Storedata {
constructor(name, desc, price, qty) {
this.name = name;
this.desc = desc;
this.price = price;
this.qty = qty;
}
}
var arr = [];
var btnform = document.getElementById('clicktoadd');
var btnlist = document.getElementById('clicktoshow');
var rem = document.getElementById('main');
var cancelform;
var submit;
function addData() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
arr.push(new Storedata(proname.value, prodesc.value, propric.value, proqty.value));
}
function showlist() {
var data = document.createElement('table');
data.setAttribute("id", "data");
data.innerHTML += "<tr><th>Product Name</th><th>Description</th><th>Price</th><th>Quantity</th><th></th></tr>";
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
document.getElementById('listing').appendChild(data);
document.getElementById('showbutton').removeAttribute("hidden", false);
}
function removelist() {
var data = document.getElementById("data");
data.parentNode.removeChild(data);
}
function addformtopage() {
var form = document.createElement('div');
form.setAttribute("id", "remform");
form.innerHTML += "<div id=\"lblname\">Product Name:</div><input id=\"inpname\" type=\"text\"><div id=\"chkname\" hidden=\"true\">Enter a Product Name</div><div id=\"lbldesc\">Description:</div><textarea id=\"inpdesc\" rows=\"10\" cols=\"35\"></textarea><div id=\"chkdesc\" hidden=\"true\">Enter a Product Desciption</div><div id=\"lblprice\">Price in INR:</div><input id=\"inpprice\" type=\"number\"><div id=\"chkprice\" hidden=\"true\">Enter a Product Price</div><div id=\"lblqty\">Quantity:</div><input id=\"inpqty\" type=\"number\"><div id=\"chkqty\" hidden=\"true\">Enter a Product Quantity</div><br><br><button id=\"submitproduct\">Submit</button><button id=\"cancel\">Cancel</button>";
document.getElementById('panel').appendChild(form);
cancelform = document.getElementById('cancel');
submit = document.getElementById('submitproduct');
}
function validateform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
var errname = document.getElementById("chkname");
var errdesc = document.getElementById("chkdesc");
var errpric = document.getElementById("chkprice");
var errqty = document.getElementById("chkqty");
if ((proname.value) && (prodesc.value) && (propric.value) && (proqty.value)) {
errname.setAttribute("hidden", true);
errdesc.setAttribute("hidden", true);
errpric.setAttribute("hidden", true);
errqty.setAttribute("hidden", true);
return true;
}
if (proname.value) {
errname.setAttribute("hidden", true);
}
if (prodesc.value) {
errdesc.setAttribute("hidden", true);
}
if (propric.value) {
errpric.setAttribute("hidden", true);
}
if (proqty.value) {
errqty.setAttribute("hidden", true);
}
if (!proname.value) {
errname.removeAttribute("hidden", false);
}
if (!prodesc.value) {
errdesc.removeAttribute("hidden", false);
}
if (!propric.value) {
errpric.removeAttribute("hidden", false);
}
if (!proqty.value) {
errqty.removeAttribute("hidden", false);
}
return false;
}
function clearform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
proname.value = null;
prodesc.value = null;
propric.value = null;
proqty.value = null;
}
function removeform() {
var elem = document.getElementById("remform");
elem.parentNode.removeChild(elem);
}
function removebuttons() {
rem.setAttribute("hidden", true);
}
function showbuttons() {
rem.removeAttribute("hidden", false);
}
btnform.addEventListener('click', function() {
addformtopage();
removebuttons();
cancelform.addEventListener('click', function() {
showbuttons();
removeform();
});
submit.addEventListener('click', function() {
if (validateform()) {
alert("Values Added");
addData();
clearform();
}
});
});
btnlist.addEventListener('click', function() {
showlist();
removebuttons();
document.getElementById('showbutton').addEventListener('click', function() {
showbuttons();
removelist();
document.getElementById('showbutton').setAttribute("hidden", "true");
});
});
#chkname,
#chkdesc,
#chkprice,
#chkqty {
color: red;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 70%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<!DOCTYPE HTML>
<html>
<head>
<link href="style.css" rel="stylesheet" />
<title>
JS Form
</title>
</head>
<body>
<div id="main">
<p><button id="clicktoadd">Add Product</button> <button id="clicktoshow">Show List</button></p>
</div>
<div id="panel">
</div>
<div id="listing">
</div>
<button id="showbutton" hidden="true">< Back</button>
<script src="script.js"></script>
</body>
</html>
I want to take input in form for description of the item as formatted text. And then output it in the same format as input, but right now I am getting text separated by space where should be there. Please help..
Steps to perform
1. Run this code snippet.
2. Click on 'Add Product' button.
3. Fill the form (For testing give a description of more than one line) and Submit.
4. Click on 'Cancel' button to return.
5. Click on 'Show List' button.
6. Observe Description column.
This is output I am getting separated by spaces
This is form input I am providing
Well, you have two options. Add a <pre> tag:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td><pre>" + arr[i].desc + "</pre></td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
This way it will display the new lines and you keep your string clean.
Or you can replace the new lines with <br> this way:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc.replace(/\n/g, "<br>") + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
Remember that the new lines are not shown by default in HTML, if you want a new line put a <br>
Test it online
Hope it helps! :)
Add this into your code:
var text = arr[i].desc;
text = text.replace(/\n/g, '<br />');
JSfiddle
See JavaScript: How to add line breaks to an HTML textarea? too.

Paragraph numbers changing HTML JAVASCRIPT

I'm working with list which elements can be added with JS by the following code:
function getMovementButtons(size, articleId, articleTitle, articleType){
var lowerArticleType = articleType.toLowerCase();
var html = '<div>'+
'<span style="vertical-align: top">'+ size +
'<span style="vertical-align: top">.</span> '+
'</span>'+
'<span style="vertical-align: top" class="'+lowerArticleType+'-title displaying-'+lowerArticleType+'-id' + articleId +'">' + articleTitle + '</span>' +
'<input class="'+lowerArticleType+'-button-delete" type="button" value="' + '<%= LanguageUtil.get(pageContext, "global.action.delete")%>' + '" onclick="removeArticle(this,\''+articleType+'\')"/>' +
'<div class="'+lowerArticleType+'-div-move"><input class="'+lowerArticleType+'-button-up" type="button" value="" onclick="moveArticleUp(this,\''+articleType+'\')"/>' +
'<input class="'+lowerArticleType+'-button-down" type="button" value="" onclick="moveArticleDown(this,\''+articleType+'\')"/>' +
'</div>'+
'</div>';
return html;
I have a function removeArticleLine.
function removeArticleLine(button) {
var parentDiv = button.parentNode
var articleListDiv = parentDiv.parentNode;
articleListDiv.removeChild(parentDiv);
}
There is a problem, because if I delete an object paragraphs don't change their numbers. I would ask you to give me a hint how can I change these numbers with JS.
I'm adding working functions which can help us. It's moving everything properly:
function moveArticleUp(button, articleType) {
var articleDiv = button.parentNode.parentNode;
var parentDiv = articleDiv.parentNode;
var prevArticleDiv = articleDiv.previousElementSibling;
if (prevArticleDiv && prevArticleDiv.tagName == 'DIV') {
var articleIdValue = getArticleIdValue(articleType);
var ids = articleIdValue.split(',');
var articleId = getArticleIdFromArticleDiv(articleDiv, articleType);
var articleIdIndex = ids.indexOf(articleId);
swapPosition(ids, articleIdIndex, articleIdIndex - 1);
setArticleIdValue(articleType, ids.join());
removedArticleDiv = parentDiv.removeChild(articleDiv);
parentDiv.insertBefore(removedArticleDiv, prevArticleDiv);
console.log(articleIdIndex);
prevArticleDiv.firstElementChild.innerHTML = articleIdIndex + 1 + '<span style="vertical-align: top">.</span> ';
articleDiv.firstElementChild.innerHTML = articleIdIndex + '<span style="vertical-align: top">.</span> ';
}
}
function moveArticleDown(button, articleType) {
var articleDiv = button.parentNode.parentNode;
var parentDiv = articleDiv.parentNode;
var nextArticleDiv = articleDiv.nextElementSibling;
if (nextArticleDiv) {
var articleIdValue = getArticleIdValue(articleType);
console.log(articleIdValue);
var ids = articleIdValue.split(',');
var articleId = getArticleIdFromArticleDiv(articleDiv, articleType);
console.log(articleId);
var articleIdIndex = ids.indexOf(articleId);
console.log(articleIdIndex);
swapPosition(ids, articleIdIndex, articleIdIndex + 1);
setArticleIdValue(articleType, ids.join());
console.log(ids.join());
removedArticleDiv = parentDiv.removeChild(nextArticleDiv);
parentDiv.insertBefore(removedArticleDiv, articleDiv);
console.log(nextArticleDiv.firstElementChild.innerHTML);
console.log(articleDiv.firstElementChild.innerHTML);
nextArticleDiv.firstElementChild.innerHTML = articleIdIndex + 1 + '<span style="vertical-align: top">.</span> ';
articleDiv.firstElementChild.innerHTML = articleIdIndex + 2 + '<span style="vertical-align: top">.</span> ';
}
}
Let me add two screenshots of the displayed table:
http://imgur.com/a/EOfkk
http://imgur.com/a/R9oru
After you remove a line you should loop the array of elements and assign new numbers for them. The code was not tested, but it should works
function removeArticleLine(button) {
var parentDiv = button.parentNode;
// getting the number of deleting div
var divNumber = parseInt(parentDiv.firstChild.textContent);
var articleListDiv = parentDiv.parentNode;
articleListDiv.removeChild(parentDiv);
// we need to loop elements after deleted div, because elements before did not change theit number
for (var i = 0 || divNumber; i < articleListDiv.children.length; i++) {
//changing number
articleListDiv.children[i].firstElementChild.innerHTML = (i + 1) + '<span style="vertical-align: top">.</span> ';
}
}

How to assign deleted textbox id to newly generated textbox when generating dynamic textbox?

I am dynamically generating textboxes and only 5 textbox are allowed.
Now say i have generated 5 textbox with Txtopt1,Txtopt2,Txtopt3 resp..
and i am removing 2nd textbox and then again I am generating 1 new
textbox then i want to assign Txtopt2 to newly generated textbox
instead of Txtopt4.
This is my Code:
var cnt = 1;
var usedIds = [];
var maxNumberOfTextboxAllowed = 5;
function Generatetextbox() {
if (cnt <= maxNumberOfTextboxAllowed) {
var id = findAvailableId();
var OrderingField = $("<div class='OrderingField' id='OrderingField" + id + "'/>");
var LeftFloat = $("<div class='LeftFloat' id='LeftFloat" + id + "'/>");
var RightFloatCommands = $("<div class='RightFloat Commands' id='RightFloat Commands" + id + "'/>");
var upButton = $("<button value='up'>Up</button>");
var downButton = $("<button value='down'>Down</button>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + id + "' name='TxtoptNm" + id + "'/>");
var removeButton = $("<img class='remove' src='../remove.png' />");
LeftFloat.append(fName);
LeftFloat.append(removeButton);
RightFloatCommands.append(upButton);
RightFloatCommands.append(downButton);
OrderingField.append(LeftFloat);
OrderingField.append(RightFloatCommands);
$("#FieldContainer").append(OrderingField);
cnt = cnt + 1;
}
else
alert("Cant create more than 5 route points")
}
function findAvailableId() {
var i = 1;
while (usedIds[i]) i++;
usedIds[i] = true;
return i;
};
function removeId(idToRemove) {
usedIds[idToRemove] = false;
};
$(document).on('click', "img.remove", function() {
$(this).parent().parent().fadeOut(1000, function() {
if (cnt > maxNumberOfTextboxAllowed)
cnt = cnt - 2;
else if (cnt == 1)
cnt = 1;
else
cnt = cnt - 1;
var id = $(this).attr("id").substr(5);
removeId(id);
$(this).remove();
console.log(cnt)
});
});
.LeftFloat
{
float: left
}
.RightFloat
{
float: right
}
.FieldContainer
{
border: 1px solid black;
width: 400px;
height: 300px;
overflow-y: auto;
font-family:tahoma;
}
.OrderingField
{
margin: 3px;
border: 1px dashed #0da3fd;
background-color: #e8efff;
height: 50px;
}
.OrderingField div.Commands
{
width: 60px;
}
button
{
width: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="FieldContainer">
</div>
<button onclick="Generatetextbox()" class="btn btn-primary" type="button">Add</button>
Keep track of the IDs you've assigned, and always take the lowest ones available.
Also, You don't need to use escape characters inside your html, you can use the single quote marks to specify strings.
Something like this should help:
var cnt = 1;
var maxNumberOfTextboxAllowed = 5;
var usedIds = [];
function findAvailableId() {
var i = 1;
while (usedIds[i]) i++;
usedIds[i] = true;
return i;
};
function removeId(idToRemove) {
usedIds[idToRemove] = false;
};
function Generatetextbox() {
if (cnt <= maxNumberOfTextboxAllowed) {
var id = findAvailableId();
var fieldWrapper = $("<div class='fieldwrapper' id='field" + id + "'/>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + id + "' name='TxtoptNm" + id + "' />");
var removeButton = $("<img class='remove' src='../remove.png' />");
fieldWrapper.append(fName);
fieldWrapper.append(removeButton);
fieldWrapper.append('<br />');
fieldWrapper.append('<br />');
$("#abc").append(fieldWrapper);
cnt = cnt + 1;
} else
alert("Cant create more than 5 textbox")
}
$(document).on('click', "img.remove", function() {
$(this).parent().fadeOut(1000, function() {
if (cnt > maxNumberOfTextboxAllowed)
cnt = cnt - 2;
else if (cnt == 1)
cnt = 1;
else
cnt = cnt - 1;
var id = $(this).attr("id").substr(5);
removeId(id);
$(this).remove();
console.log(cnt)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc"></div>
<button onclick="Generatetextbox()" class="btn btn-primary" type="button">Add</button>

Categories

Resources