http://jsfiddle.net/3Sd4W/
Reference: The above js fiddle provided by greener.
If the new Entry Button is clicked, there is an layout issue for that new added object.
The text box style is:
file.setAttribute("style", "margin-top: 60px;");
But I want the text box to be in the middle and not at the bottom. I tried myself but it doesn't works for me. Anybody could help me to solve this problem?
Your code is extremely complicated to read, so this may help:
HTML:
<form name="addpoll">
<div id="choices">
</div>
<input id="addchoice" type="button" value="Add New Entry">
</form>
JS:
function addnewDiv(counterAppended) {
counterAppended = parseInt(counterAppended) + 1;
var text = document.createElement("div");
text.innerHTML = '<input type="hidden" class="choicecount" name="choicecount" id="choicecount" value="' + counterAppended + '">\
<input type="file" name="choiceimg' + counterAppended + '" value ="Select" onchange="readURL(this)" style="display:none;">\
<div>\
<div style="width:400px;height:85px;">\
<div id="imgbg" style="float:left;width: 110px;height: 80px;text-align: center;border: 1px solid #CCC;">\
<input type="button" onclick="HandFileButtonClick();" value="Browse" id="firstremove" style="margin-top: 30px;" class="addmultiple">\
</div>\
<div style="float:right;margin-top: 30px;">\
<input type=text name="choicename' + counterAppended + '" id="firstremove2">\
<input type="button" value="Remove" class="remove" id="firstremove3" style="color: red; font-size: 12px; border: 0px; background: none; text-decoration: underline;">\
</div>\
</div>\
<img src="#" name="viewimg' + counterAppended + '" class="addmultiple" id="viewimg' + counterAppended + '" height="70px" width="85px" style="display:none"/>\
<br>\
</div>\
<span id="file"></span>';
text.id = 'choice' + counterAppended;
document.getElementById("choices").appendChild(text);
document.getElementsByClassName("remove")[document.getElementsByClassName("remove").length - 1].addEventListener("click", function() {
this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode);
});
}
function HandFileButtonClick() {
document.addpoll.choiceimg1.click();
}
function HandleFileButtonClick(val) {
var ss = val.name;
document.forms["addpoll"]
var n = ss.split("choiceimgs");
document.forms["addpoll"]["choiceimg" + n[1]].click();
}
document.getElementById("addchoice").addEventListener("click", function() {
var choicecounts = document.getElementsByClassName('choicecount');
addnewDiv(choicecounts[choicecounts.length - 1].value);
});
addnewDiv(0);
JsFiddle: http://jsfiddle.net/99vhF/1/
The first row uses a wrapper div for the input field with a style attribute containing float: right. The generated row (after clicking 'add new entry' button) does not have a div wrapper with the same attribute around the input.
You add elements to incorrect nodes. Review you "add" part. All of variables take "file" element. It looks odd:
var addfile = document.getElementById("file");
var view = document.getElementById("file");
var remove1 = document.getElementById("file");
var br2 = document.getElementById("file");
var textf1 = document.getElementById("file");
var myimgdiv = document.getElementById("file");
Related
Hello I'm trying to rest the ID attribute of a set of text boxes when the delete button is pressed.
What I want to do is that when the delete button is pressed read the existing textboxes and rest there id's because when I delete items the ID's of the existing once keep the old ID values I want to rest this to match the error number value.
Working jsFiddle
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $("#stValue").val(); //Breaks the number from the ID using .match
// 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.
resetErrorNo(); //Calls the reset function
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
if (confirm('Your sure you want to remove this?')) {
var btnId = $("#stValue").val(), //Read the value of stValue
btnId2 = btnId - 1; //Deduct 1 from the value to get the last ID
for (var i = 0; i < btnId; i++) {
$('.addRow').attr('id', 'addRow_' + i);
}
//Enables the 1st add button if the value equals 1
if (btnId2 === 1) {
$('#addRow_' + btnId2).prop('disabled', false);
} else {
$('#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>
UPDATE: I used the answer given by #Rory McCrossan and made some tweaks to get I wanted and ended up with the below code which is what I wanted to do in the first place.
// Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
$clone.find('select').val('');
// $clone.find('input').val('');
$('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
resetErrorNo();
}).on('click', '.delRow', function() {
var $btn = $(this);
if (confirm('Your sure you want to remove this?')) {
$btn.closest('.error-container').remove();
$('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
resetErrorNo();
}
});
});
//Reset the entire error count number index
function resetErrorNo() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
}
/*----- All the styling for the error input area start -----*/
#error-Column-Headings span {
margin-left: 8%;
}
.errorCount {
margin-left: 2%;
}
.errorName {
margin-left: 6%;
}
.error-Column .error-container:nth-child(1) .delRow {
display: none;
}
.error-Column .error-container:nth-child(1) .delRow {
display: none;
}
/*----- All the styling for the error input area end -----*/
<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>Error Name</span>
</div>
<div class="error-Column">
<div class="error-container">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<select class="errorName">
<option selected disabled value="">----- Select Error -----</option>
</select>
<input type="button" class="addRow" value="Add" />
<input type="button" class="delRow" value="Delete" />
</div>
</div>
</div>
hope this helps some one in the future.
Incremental id attributes are an anti-pattern which leads to a lot of unnecessary maintenance work - as you've discovered.
You can make your code much more DRY, not to mention more simple by simply cloning each row and using DOM traversal to find elements related to the buttons and add/delete them as needed. Try this:
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
$clone.find('select').val('');
$('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
}).on('click', '.delRow', function() {
var $btn = $(this);
if (confirm('Your sure you want to remove this?')) {
$btn.closest('.error-container').remove();
$('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
}
});
});
#error-Column-Headings span {
margin-left: 8%;
}
.errorCount {
margin-left: 2%;
}
.errorName {
margin-left: 6%;
}
.error-Column .error-container:nth-child(1) .delRow {
display: none;
}
<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>Error Name</span>
</div>
<div class="error-Column">
<div class="error-container">
<select class="errorName">
<option selected disabled value="">----- Select Error -----</option>
</select>
<input type="button" class="addRow" value="Add" />
<input type="button" class="delRow" value="Delete" />
</div>
</div>
</div>
</div>
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"> <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.
I'm very new to javascript but I'm trying to create a simple program that makes formatting sources for the blog I edit very easy. I want the information that users type into the form to be printed out into one textarea. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function writeCode() {
var src1 = document.getElementById('src1').value,
src2 = document.getElementById('src2').value,
src3 = document.getElementById('src3').value,
var lnk1 = document.getElementById('lnk1').value,
lnk2 = document.getElementById('lnk2').value,
lnk3 = document.getElementById('lnk3').value,
outputValue = '<span style="color: #888888; font-size: xx-small;">Sources: </span>' + '<span style="color: #2200fc; font-size: xx-small;">' + src1 + '</span>' + ', ' + '<span style="color: #2200fc; font-size: xx-small;">' + src2 + '</span>'
document.getElementById('outputArea').value = outputValue;
if (src3.length + lnk3.length != 0){
outputValue2 = ', ' + '<span style="color: #2200fc; font-size: xx-small;">' + src3 + '</span>'
document.getElementById('outputArea2').value = outputValue2;
}
else {
document.getElementById('outputArea2').value = ' '
}
console.log(writeCode);
</script>
</head>
<body>
<form name="sources">
Source 1 <input type="text" id="src1"/>
Link 1 <input type="text" id="lnk1"/></br>
Source 2 <input type="text" id="src2"/>
Link 2 <input type="text" id="lnk2"/></br>
Source 3 <input type="text" id="src3"/>
Link 3 <input type="text" id="lnk3"/></br>
<input type="button" value="Write my code!" onclick="writeCode();"/>
<input type="button" value="Cite another article!" onClick="window.location.reload()"/></br>
<textarea style="width:600px;height:100px;" name="outputForm">
<p id="outputArea"></p>
<p id="outputArea2"><p>
<p id="outputArea3"></p>
</textarea>
</form>
</div>
</body>
Now, I got it working with multiple textareas by assigning them each a separate ID. But my goal is to have all the inputs that have been entered print out in one area. I've also tried assigning the ID outputArea to the textarea, and then having them all print out to outputArea, but it returns an error like 'Cannot assign value null.' Any advice on how to go about this?
Thanks!
I've come up with this:
HTML:
<form name="sources">Source 1
<input type="text" id="src1" />Link 1
<input type="text" id="lnk1" />
</br>Source 2
<input type="text" id="src2" />Link 2
<input type="text" id="lnk2" />
</br>Source 3
<input type="text" id="src3" />Link 3
<input type="text" id="lnk3" />
</br>
<input type="button" value="Write my code!" onclick="writeCode();" />
<input type="button" value="Cite another article!" onClick="window.location.reload()" />
</br>
<textarea style="width:600px;height:100px;" name="outputForm" id="outputForm"> </textarea>
</form>
JS:
function writeCode() {
var src1 = document.getElementById('src1').value,
src2 = document.getElementById('src2').value,
src3 = document.getElementById('src3').value,
lnk1 = document.getElementById('lnk1').value,
lnk2 = document.getElementById('lnk2').value,
lnk3 = document.getElementById('lnk3').value,
outputValue = '<span style="color: #888888; font-size: xx-small;">Sources: </span>' + '<span style="color: #2200fc; font-size: xx-small;">' + src1 + '</span>' + ', ' + '<span style="color: #2200fc; font-size: xx-small;">' + src2 + '</span>';
if (src3.length != 0 && lnk3.length != 0) {
outputValue += ', ' + '<span style="color: #2200fc; font-size: xx-small;">' + src3 + '</span>';
}
document.getElementById('outputForm').value = outputValue;
}
You need to be careful with the errors being displayed in the console, there were a few which might not have been crashing the page but definitely causing issues with what you were attempting to do.
Fiddle: http://jsfiddle.net/KyleMuir/kRRBR/1/
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
The form below is working as I want except for one thing. When I click the 'Add' link I the texts of all the textboxes go back to its default value like seen in the images. How can I fix it? Thanks.
before click:
after click on 'Add':
Code:
function addSection() {
var str = '<div>' +
'<input type="text" name="composer" value="Compositor" />' +
'<input type="text" name="peca" value="Peca" size="40" />' +
'<input type="button" value="x" style="width: 26px" onclick="delSection(this)" /><br />' +
'</div>';
document.getElementById("programa").innerHTML += str;
}
function delSection(field) {
field.parentNode.outerHTML = "";
}
window.onload = addSection;
</script>
<fieldset>
<legend>Programa</legend>
<div id="programa">
</div>
<a href="#" onclick="addSection()" >Add</a><br />
</fieldset>
<input type="submit" value="Inscrever Aluno" name="submit" />
You can overcome this, using appendChild()
JS
function newSet() {
var div = document.createElement("div");
var composer = document.createElement("input");
composer.type="text";
composer.value = "Compositer";
var peca = document.createElement("input");
peca.type = "text";
peca.value = "Peca";
var button = document.createElement("input");
button.type = "submit"
div.appendChild(composer);
div.appendChild(peca);
div.appendChild(button);
return div
}
function addSection() {
document.getElementById("programa").appendChild(newSet());
}
Demo
This is the correct JS to insert new elements:
function addSection() {
var newDiv = document.createElement('div');
var str = '<input type="text" name="composer" value="Compositor" />' +
'<input type="text" name="peca" value="Peca" size="40" />' +
'<input type="button" value="x" style="width: 26px" onclick="delSection(this)" /><br />';
newDiv.innerHTML = str;
document.getElementById("programa").appendChild(newDiv);
}
You need to find a solution for naming (or identification) of the elements so you can remove them with delSelection(field)
create a name like name="composer[]" and name="peca[]"
if you don't understand how to implement the above code then go to
http://www.randomsnippets.com/2008/02/21/how-to-dynamically-add-form-elements-via-javascript/