Can not keep id serially of textbox using Javascript/Jquery - javascript

I have an issue.I am adding multiple textbox using + button and deleting using - button. Here i am unable to keep each textbox's id serially. I am explaining my code below.
<div class="form-group" id="intro-box">
<input type="text" style="width:85%;float:left;margin-bottom:5px;" class="form-control" id="introlabelname0" name="introlabelname" placeholder="Label Name" value="">
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(1);">
</div>
<script>
var a = 0;
function addMore(i) {
a = a + 1;
i = a;
$("#plus").remove();
$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
}
</script>
Here my problem is the id is increasing like introlabelname0,introlabelname1,introlabelname2.. this but while suppose deleting introlabelname1 textbox and adding again its coming introlabelname0,introlabelname2,introlabelname3 like this. Here i need suppose introlabelname1 deleting from introlabelname0,introlabelname1,introlabelname2.. it should introlabelname0,introlabelname1 and if adding again it should introlabelname0,introlabelname1,introlabelname2. Always all textbox id will remain serially from 0,1,2... and so on. Here is my full code. Please help me.

You can also do like this.
1.I added var i = $(".inputBox").length + 1; this line in addMore function it calculate the current input box count and add serialize number to new input box.
2.Also I include serialize() function it makes serialize your input box and button ids.
function addMore(i) {
var i = $(".inputBox").length + 1;
$("#plus").remove();
$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control inputBox" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
serialize();
}
function serialize(){
var i=1;
$(".inputBox").each(function(){
$(this).attr("id", "introlabelname"+i);
$(this).next().attr("id", "minus"+i);
i++;
});
}

I think you just need to decrement the a variable when you remove a row:
function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
a = a - 1;
}

The easy way is to loop over all the input box, and create the new ID(s) with index value. First of all give the text box class name :
class="form-control inputBox"
Then add this function :
function repopulate() {
$( '.inputBox' ).each( function ( i, e) {
$( this ).attr( 'id','introlabelname' + i );
$( this ).next().attr( 'onClick', function (old,n) {
return 'removeThis(' + i + ')';
});
$( this ).next().attr( 'id', function (old,n) {
return 'minus' + i;
});
})
}
Last, for each function calling, call this function :
repopulate();
Here is updated DEMO
p/s : you should edit the HTML,it not properly structured

Related

Adding div on click only once and allowing customer to delete it and reclick it

I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>

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.

Add new row with dropdown on button click

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="+" />

Creating a quiz using php, To store array data in a field in the database

I'm trying to create a dynamic quiz and store it in database, the inputs is composed of 1 question and 4 answers.
I made the textbox and radio buttons dynamically created using jquery. The 1 textbox is for the question and the other 4 textbox is for the answer, I have also 4 radio buttons for correct answer.
var ctr = 2;
$("#addTextBox").click(function() {
var newTBdiv = $(document.createElement('div'))
.attr("id", 'QuestionTBDiv' +ctr);
newTBdiv.css({"margin-top":"20px" });
newTBdiv.css({"width":"500px"});
newTBdiv.css({"padding":"5px"});
newTBdiv.after().html('<label class="mlabel">Question</label><br/><input type="text" name="quiztxtBox'+ctr+'" size="57" id="quiztxtBox'+ctr+'" placeholder="Question #'+ctr+'"><br/><label class="mlabel">Answer</label><br/><input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A"> <input type="radio" name="correct_answer'+ctr+'" value="A"> <input type="text" name="answer'+ctr+'" size="24" id="answer'+ctr+'" placeholder="Choice B">&nbsp<input type="radio" name="correct_answer'+ctr+'" value="B"><br/><input type="text" name="answer'+ctr+'" size="24" id="answer'+ctr+'" placeholder="Choice C"> <input type="radio" class = "choiceC" name="correct_answer'+ctr+'" value="C"> <input type="text" name="answer'+ctr+'"size="24" id="answer'+ctr+'" placeholder="Choice D"> <input type="radio" name="correct_answer'+ctr+'" value="D"><br><span name="errMchoice" class="errorMsg"></span>')
newTBdiv.appendTo("#exam_container");
ctr++;
});
Now the problem is, I need to store the data of questions and answer to one field only in the database.. I found out that using serialize() function will able to store the array in the field, But Im not quite sure of what I am doing. I was thinking of something like this. This is the array that I was thinking to serialize and store in the database.
$array = array(
array(question1, answer1, answer2, answer3, answer4, correctanswer);
array(question1, answer1, answer2, answer3, answer4, correctanswer);
);
Or is there other method to achieve this?
What you do is update you would use 2 tables to be like this:
table: Quizes
id, title, creator, etc
table: Quiz_Settings
id //(simply for managing rows and edits/updates)
"1", "2", "3" // etc
quiz_id
"55912" // or so on
type
"question", "answer"
ref_number
"1", "2" // This is basically Question 1, Question 2, Answer 1 etc.
value
"What is ...?" or "21" // The question or the answer
You would then get quiz by id = 55912, and check against quiz settings for all with "quiz_id" == 55912, and using the "question" field and "ref_number" field, you generate a table or page which has the questions, and then a field which has to be equal to "answer" "1"
In the event of MULTIPLE answers, you simply loop through each "answer" "1", if it's correct, +1, if it's incorrect, 0.
// EXAMPLE JS:
<script>
var num_fields = <?=($num_fields > 0 ? $num_fields : 0)?>;
var num_multi_fields = <?=($num_multi_fields > 0 ? $num_multi_fields : 0)?>;
var cf = new Array();
var cv = new Array();
<?for($i=1;$i<=$num_fields;$i++) { ?>cf[<?=$i?>] = "<?=${'cf'.$i}?>"; cv[<?=$i?>] = "<?=${'cv'.$i}?>";<? } ?>
var cmf = new Array();
<?for($i=1;$i<=$num_multi_fields;$i++) { ?>
cmf[<?=$i?>] = "<?=${"cmf".$i}?>";
var cmv<?=$i?> = new Array();
<?$k = 0; for($j=1;$j<=${"cmf".$i."vt"};$j++) {?>
cmv<?=$i?>[<?=$k?>] = "<?=${"cmf".$i."v".$j}?>";
<? $k++; } ?>
<?} ?>
$(document).ready(function() {
$("#num_fields").val(num_fields);
for(i=1;i<=num_fields;i++) {
$("#custom_fields").append(
'<div id="custom_'+i+'"><br/><label for="custom_field_'+i+'" class="custom-label">Custom Field '+i+': </label> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_o">Delete</button><br />'
+ '<table width="100%"><tr><td>Field Name:</td><td>Field Value:</td></tr><tr>'
+ '<td><input type="text" class="form-control custom_field" value="'+cf[i]+'" name="custom_field_'+i+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" value="'+cv[i]+'" name="custom_value_'+i+'"/></td></tr></table></div>'
);
};
$(".delete_custom_o").click(function() {
$(this).parent().remove();
var i = 0;
$("#custom_fields>div").each(function() {
i++;
$(this).find('label').text("Custom Field " +i+":");
$(this).find('.custom_field').attr("name", "custom_field_"+i);
$(this).find('.custom_value').attr("name", "custom_value_"+i);
});
num_fields--;
$("#num_fields").val(num_fields);
});
});
$("#add_field").click(function() {
num_fields++;
$("#num_fields").val(num_fields);
$("#custom_fields").append(
'<div id="custom_'+num_fields+'"><br/><label for="custom_field_'+num_fields+'">Custom Field '+num_fields+':</label> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_n">Delete</button><br />'
+ '<table width="100%"><tr><td>Field Name:</td><td>Field Value:</td></tr><tr>'
+ '<td><input type="text" class="form-control custom_field" name="custom_field_'+num_fields+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" name="custom_value_'+num_fields+'"/></td></tr></table></div>'
);
});
$('#custom_fields').on("click", ".delete_custom_n", function(){
$(this).parent().remove();
var i = 0;
$("#custom_fields>div").each(function() {
i++;
$(this).find('label').text("Custom Field " +i+":");
$(this).find('.custom_field').attr("name", "custom_field_"+i);
$(this).find('.custom_value').attr("name", "custom_value_"+i);
});
num_fields--;
$("#num_fields").val(num_fields);
});
$("#add_multi_field").click(function() {
num_multi_fields++;
$("#num_multi_fields").val(num_multi_fields);
$("#custom_multi_fields").append(
'<div id="custom_'+num_multi_fields+'" style="border-bottom: 1px solid #ddd; padding-bottom: 5px;"><br/>'
+ '<label for="custom_field_'+num_multi_fields+'">Custom Field '+num_multi_fields+':</label> '
+ '<button type="button" class="btn btn-xs em-bg-blue add_custom_n" data-id="'+num_multi_fields+'" data-target="#custom_table_'+num_multi_fields+'">Add</button> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_n">Delete</button><br />'
+ '<div style="max-height:100px; overflow-y:auto; padding-left: 10px; padding-right: 10px;"><table width="100%" id="custom_table_'+num_multi_fields+'"><tr><td>Field Name:</td><td>Field Value:</td></tr><tr>'
+ '<td><input type="text" class="form-control custom_field" name="custom_multi_field_'+num_multi_fields+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" name="custom_multi_value_'+num_multi_fields+'[]"/></td></tr>'
+ '<tr><td><center><button type="button" class="btn btn-xs btn-danger delete_field">Remove</button></center></td>'
+ '<td><input type="text" class="form-control custom_value" name="custom_multi_value_'+num_multi_fields+'[]"/></td></tr></table></div></div>'
);
});
$('#custom_multi_fields').on("click", ".add_custom_n", function(){
target = $(this).attr('data-target');
id = $(this).attr('data-id');
$(target).find('tbody')
.append($('<tr>')
.append($('<td>').html('<center><button type="button" class="btn btn-xs btn-danger delete_field">Remove</button></center>'))
.append($('<td>')
.append($('<input>').attr('type', 'text').attr('class', 'form-control custom_value').attr('name', 'custom_multi_value_'+id+'[]'))
)
);
});
$('#custom_multi_fields').on("click", ".delete_field", function(){
$(this).parent().parent().parent().remove();
});
$('#custom_multi_fields').on("click", ".delete_custom_n", function(){
$(this).parent().remove();
var i = 0;
$("#custom_multi_fields>div").each(function() {
i++;
$(this).find('label').attr('for','custom_field_'+i).text("Custom Field " +i+":");
$(this).attr('id','custom_'+i);
$(this).find('button.add_custom_n').attr('data-target', '#custom_table_'+i).attr('data-id', i);
$(this).find('table').attr("id","custom_table_"+i);
$(this).find('.custom_field').attr("name","custom_multi_field_"+i);
$(this).find('.custom_value').attr("name","custom_multi_value_"+i+"[]");
});
num_multi_fields--;
$("#num_multi_fields").val(num_multi_fields);
});
$(document).ready(function() {
$("#num_multi_fields").val(num_multi_fields);
for(i=1;i<=num_multi_fields;i++) {
var curr_array = window['cmv' + i];
string = "";
for(j=1;j<curr_array.length;j++) {
string += '<tr><td><center><button type="button" class="btn btn-xs btn-danger delete_field">Remove</button></center></td>'
+ '<td><input type="text" class="form-control custom_value" value="'+curr_array[j]+'" name="custom_multi_value_'+i+'[]"/></td></tr>'
}
$("#custom_multi_fields").append(
'<div id="custom_'+i+'" style="border-bottom: 1px solid #ddd; padding-bottom: 5px;"><br/>'
+ '<label for="custom_field_'+i+'">Custom Field '+i+':</label> '
+ '<button type="button" class="btn btn-xs em-bg-blue add_custom_n" data-id="'+i+'" data-target="#custom_table_'+i+'">Add</button> '
+ '<button type="button" class="btn btn-xs btn-danger delete_custom_n">Delete</button><br />'
+ '<div style="max-height:100px; overflow-y:auto; padding-left: 10px; padding-right: 10px;"><table width="100%" id="custom_table_'+i+'"><tr><td>Field Name:</td><td>Field Value:</td></tr></tr>'
+ '<td><input type="text" class="form-control custom_field" value="'+cmf[i]+'" name="custom_multi_field_'+i+'"/></td>'
+ '<td><input type="text" class="form-control custom_value" value="'+curr_array[0]+'" name="custom_multi_value_'+i+'[]"/></td></tr>'
+ ""+string+""
+ '</table></div></div>'
);
};
$(".delete_custom_o").click(function() {
$(this).parent().remove();
var i = 0;
$("#custom_multi_fields>div").each(function() {
i++;
$(this).find('label').attr('for','custom_field_'+i).text("Custom Field " +i+":");
$(this).attr('id','custom_'+i);
$(this).find('button.add_custom_n').attr('data-target', '#custom_table_'+i).attr('data-id', i);
$(this).find('table').attr("id","custom_table_"+i);
$(this).find('.custom_field').attr("name","custom_multi_field_"+i);
$(this).find('.custom_value').attr("name","custom_multi_value_"+i+"[]");
});
num_multi_fields--;
$("#num_multi_fields").val(num_multi_fields);
});
$(".delete_field").click(function() {
$(this).parent().parent().parent().remove();
});
});
</script>
The Example HTML: Custom Field = 1 to 1 relationship (1 question 1 answer) - Multi Field = 1 to many relationship (1 question multiple answers)
<div class="row">
<div class="col-lg-6">
<button type="button" class="btn em-bg-blue" id="add_field">Add Custom Field</button><br />
<div id="custom_fields" style="max-height: 500px; overflow-y: auto;"></div>
</div>
<div class="col-lg-6">
<button type="button" class="btn em-bg-blue" id="add_multi_field">Add Multi Field</button><br />
<div id="custom_multi_fields" style="max-height: 500px; overflow-y: auto;"></div>
</div>
</div>
Serialization is an alright method. Have a look at the jQuery library, or try to write a very simple PHP file that will serialize for you.

jQuery Dynamic Add Form Field, Remove Form Field

Hello I am trying to add new form field and delete form field after getting inspired from this tutorial - http://bootsnipp.com/snipps/dynamic-form-fields
My Current Problem is to delete and reset the value of all in chronological order.
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Nice Multiple Form Fields</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8"
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
</div>
<br /><small>Press + to add another form field :)</small>
</div>
</div>
Javascript :-
var next = 1;
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
Parent Element is getting removed, but next counter is not reset properly. in hidden and all new created form :-
Only Add Demo :- http://bootsnipp.com/snipps/dynamic-form-fields
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
Can someone help me please.
Thanks
Try:
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
var newInput = $(newIn);
console.log(addto);
$(addto).after(newInput);
if(next>1)
$("button#b"+next).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
DEMO FIDDLE
In my example, I was building a form that would allow users to add multiple input names if they had more than one dog.
var counter = 0
jQuery(function () {
$(".newDog").click(function(){
counter ++;
if (counter < 4) {
var elem = $("<input/>",{
type: "text",
name: `dogname${counter}`
});
} else {
alert("You can only add 4 Dog Names")
}
var removeLink = $("<span/>").html("X").click(function(){
$(elem).remove();
$(this).remove();
counter --;
});
$(".dogname-inputs").append(elem).append(removeLink);
});
})
Full credit as mentioned to https://stackoverflow.com/users/714969/kevin-bowersox

Categories