The problem in my case is I can dynamically add / remove input boxes, but the problem is when I manually add a set of input box and remove button instead of press add button to create one, it can not remove it.
Is it possible to have 3 sets of input boxes but 2 remove buttons?
Thank you for any kind of help.
JSFiddle
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var label = $("<label>Field Name</label>");
var labelType = $("<label>Field Type</label>");
var labelReq = $("<label>Require</label>");
var labelTag = $("<label>Tag</label>");
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var fName = $("<input type=\"text\" name=\"inputName[]\" class=\"required\" />");
var fTag = $("<input type=\"text\" name=\"inputTag[]\" class=\"required\" />");
var fReq = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"1\">Yes</option><option value=\"0\">No</option></select>");
var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(label);
fieldWrapper.append(fName);
fieldWrapper.append('<br>');
fieldWrapper.append(labelType);
fieldWrapper.append(fType);
fieldWrapper.append('<br>');
fieldWrapper.append(labelReq);
fieldWrapper.append(fReq);
fieldWrapper.append('<br>');
fieldWrapper.append(labelTag);
fieldWrapper.append(fTag);
fieldWrapper.append('<br>');
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
</script>
</head>
<body>
<form id="config" method="post" action="config.php" >
<fieldset id="buildyourform">
<legend>Build your own form!</legend>
<!-- I manually create a set of input box here -->
<div class="fieldwrapper" id="field1"><label>Field Name</label><input type="text" name="inputName[]" class="required"><br><label>
Field Type</label><select class="fieldtype">
<option value="checkbox">Checked</option><option value="textbox">Text</option><option value="textarea">Paragraph</option></select><br><label>Require</label>
<select class="fieldtype"><option value="checkbox">Checked</option>
<option value="1">Yes</option><option value="0">No</option></select><br><label>
Tag</label><input type="text" name="inputTag[]" class="required"><br><input type="button" class="remove" value="Remove"></div>
<!-- I manually create a set of input box here -->
<input type="text" name="input[]" value="test">
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="submit" value="Submit">
</form>
</html>
Try setting the remove button actions when the document is loaded.
Try it here or use the code below.
<script>
$(document).ready(function() {
$('.remove').click(function(){
$(this).parent().remove();
});
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var label = $("<label>Field Name</label>");
var labelType = $("<label>Field Type</label>");
var labelReq = $("<label>Require</label>");
var labelTag = $("<label>Tag</label>");
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var fName = $("<input type=\"text\" name=\"inputName[]\" class=\"required\" />");
var fTag = $("<input type=\"text\" name=\"inputTag[]\" class=\"required\" />");
var fReq = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"1\">Yes</option><option value=\"0\">No</option></select>");
var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
var removeButton = $("<input type=\"button\" class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(label);
fieldWrapper.append(fName);
fieldWrapper.append('<br>');
fieldWrapper.append(labelType);
fieldWrapper.append(fType);
fieldWrapper.append('<br>');
fieldWrapper.append(labelReq);
fieldWrapper.append(fReq);
fieldWrapper.append('<br>');
fieldWrapper.append(labelTag);
fieldWrapper.append(fTag);
fieldWrapper.append('<br>');
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
</script>
</head>
<body>
<form id="config" method="post" action="config.php" >
<fieldset id="buildyourform">
<legend>Build your own form!</legend>
<!-- I manually create a set of input box here -->
<div class="fieldwrapper" id="field1"><label>Field Name</label><input type="text" name="inputName[]" class="required"><br><label>
Field Type</label><select class="fieldtype">
<option value="checkbox">Checked</option><option value="textbox">Text</option><option value="textarea">Paragraph</option></select><br><label>Require</label>
<select class="fieldtype"><option value="checkbox">Checked</option>
<option value="1">Yes</option><option value="0">No</option></select><br><label>
Tag</label><input type="text" name="inputTag[]" class="required"><br><input type="button" class="remove" value="Remove"></div>
<!-- I manually create a set of input box here -->
<input type="text" name="input[]" value="test">
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="submit" value="Submit">
</form>
</html>
This is an excellent case to use templates as it makes the hole thing much more maintainable rather than create the entire form div in JavaScript.
Live code: http://jsbin.com/uzelix/edit#javascript,html
HTML
<fieldset id="buildyourform">
<legend>Build your own form!</legend>
<div id="fields"></div>
</fieldset>
<button class="btn-add">Add field</button>
<!-- I manually create a set of input box here -->
<script id="fieldTemplate" type="text/x-jquery-tmpl">
<div class="fieldwrapper" id="field_${Id}">
<label>Field Name</label>
<input type="text" name="fieldname_${Id}" class="required">
<label>Field Type</label>
<select class="fieldtype_${Id}">
<option value="checkbox">Checked</option>
<option value="textbox">Text</option>
<option value="textarea">Paragraph</option>
</select>
<label>Require</label>
<select class="fieldtype_${Id}">
<option value="checkbox">Checked</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<label>Tag</label>
<input type="text" name="fieldtag_${Id}" class="required">
<div class="control-button">
<button class="btn-remove">Remove</button>
</div>
</div>
</script>
<!-- I manually create a set of input box here -->
jQuery
$(function(){
$(".btn-add").click(function() {
addField();
});
$(".btn-remove").live("click", function() {
$(this).closest(".fieldwrapper").slideUp("slow", function() {
$(this).remove();
clearRemove();
});
});
// add first field
addField();
});
function addField() {
var i = $(".fieldwrapper").length;
$("#fieldTemplate").tmpl({ Id: i }).appendTo("#fields");
clearRemove();
}
function clearRemove() {
// hide all remove buttons except last one so we don't get
// multiple ids... or use a counter to keep ids unique.
if($(".fieldwrapper").length > 1) {
$(".btn-remove:last").show();
$(".btn-remove:not(:last)").hide();
}
else
$(".btn-remove").hide();
}
Related
In my View, I'm dynamically add divs like this via JS:
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" value="Delete" />
</div>
The question is how to delete the chosen one by clicking the Delete button in div?
JavaScript that adds new divs:
<script>
$(function() {
var i = 0;
$('.plus').click(function()
{
++i;
var html2add = "<div id='detail[" + i + "]'>" +
"<input name='detail.Index' type='hidden' value='" + i + "' />" +
"<input name='detail[" + i + "].details_name' type='text' />" +
"<input name='detail[" + i + "].details_value' type='text' />" +
"<input class='btn' type='button' value='Delete' />"+
"</div>";
$('#details_part').append(html2add);
})
})
To delete the div containing the delete button, just use the remove() function:
$(document).on('click', '.btn', function(){
var cur = $(this);
cur.parent().remove();
});
A node cannot commit suicide (remove itself), therefore you must remove it from its parent node like this:
<script>
function deleteItem (id) {
var item = document.getElementById(id);
item.parentNode.removeChild(item)
}
</script>
<div>
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" value="Delete" onclick="deleteItem('detail[0]')" />
</div>
</div>
Codepen example: https://codepen.io/getreworked/pen/MmVMJB
If you are using Jquery you can do
$(".btn").click(function () {
$(this).closest("div").remove();
})
There are many ways to do this.
This one will hide the div using purely JavaScript.
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" onclick="removeDiv('detail[0]')" value="Delete" />
</div>
<script>
function removeDiv(id){
document.getElementById(id).style.display = 'none';
}
</script>
Just pass the parameter of the ID of your parent div.
This is Using jQuery:
<div id="detail[0]">
<input name="detail.Index" type="hidden" value="0" />
<input name="detail[0].details_name" type="text" />
<input name="detail[0].details_value" type="text" />
<input class="btn" type="button" value="Delete" />
</div>
<script>
$(function(){
$('.btn').click(function(){
$(this).parent().remove();
});
});
</script>
Cheers,
// Include below jquery 1.7 script in your file first
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js">
// then use this code to remove
<script type="text/javascript">
$(function(){
$('.btn').live('click' , function(){
$(this).parent('div').remove();
});
});
</script>
http://www.quirksmode.org/dom/domform.html
I am trying to implement this extend form function in my project. Since I am compiling with CakePHP naming convention, in my extend form I have 2 field names:
[Student][0][age]
[Student][0][grade]
The script doesn't work because it is appending the counter only at the end of a field name all alike like this: fieldName + counter, whereas I am trying to increment, as you might have guessed it, like this:
[Student][1][age]
[Student][1][grade]
[Student][2][age]
[Student][2][grade]
I am new to Javascript and hopefully someone can advise how to work this out.
HTML:
<span id="readroot" style="display: none">
<input class="btn btn-default" type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
<br /><br />
<div class="row">
<div class="col-lg-3">
<div class="form-group required"><label for="Student1Age">Age</label><input name="data[Student][0][age]" class="form-control" placeholder="Age" maxlength="11" type="text" id="Student1Age" required="required"/></div>
</div>
<div class="col-lg-3">
<div class="form-group required">
<label for="Student1Grade">級別</label>
<select name="data[Student][0][grade]" class="form-control" id="Student1Grade" required="required">
<option value="">Please Select</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
</select>
</div>
</div>
</div></span>
<span id="writeroot"></span><input class="btn btn-default" type="button" onclick="moreFields()" value="Give me more fields!" />
Javascript:
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
You have to replace this one line like follows.
Yours:
newField[i].name = theName + counter;
New one:
newField[i].name = "[Student][" + counter + "][" + theName + "]";
I made a working sample page out of your script. Check the following link.
http://sugunan.net/demo/extend_form.php
I have a rather long complicated form to be used to record field data. One section of the form requires the ability to add a "Field Blank" section with no data recorded AND the ability to add a duplicate section where everything (including the data from the field blank section) is duplicated. The only different thing that would change on the duplicate would be the SampleID
The field blank script
<script>
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
</script>
The duplicate script
<script>
$(document).ready(function(){
var template_index=0;
$("#add_FieldDup").click(function(){
template_index++;
$(this).parent().before($("#template").clone().attr("id","template" + template_index));
$("#template" + template_index).css("display","inline");
$("#template" + template_index + " :input").each(function(){
$(this).attr("name",$(this).attr("name") + template_index);
$(this).attr("id",$(this).attr("id") + template_index);
});
$("#remove_Dup" + template_index).click(function(){
$(this).closest("fieldset").remove();
});
});
});
</script>
My form
<h3>Water Samples</h3>
<fieldset id="template"> <!--for the duplicate-->
<div id="template"> <!--for the duplicate-->
Sample ID: <input type="text" id="SampleID" name="SampleID"></div>
<div class="_40" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label> Collection Method</label><br />
<input type="radio" id="radGrab" value="grab" name="Collection" />
<label for="radGrab">Grab</label>
<input type="radio" id="radEWI" value="EWI" name="Collection" />
<label for="radEWI">EWI</label>
</div>
<fieldset> <!--For the field blank-->
<div id="readroot" class="hidden"> <!--For the field blank-->
QA Sample ID:<input type="text" id="QASampleID" name="QASampleID">
<div class="_30" data-role="controlgroup" data-mini="true" data-type="horizontal">
<label>Collection Method</label><br />
<input type="radio" id="radGrab1" value="Grab" name="Collection1" />
<label for="radGrab1">Grab</label>
<input type="radio" id="radEWI1" value="EWI" name="Collection1" />
<label for="radEWI1">EWI</label></div>
</div>
<label class="analysis-label" for="analysis">Analyte:</label>
<select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "TN">TN</option>
<option value = "TP,NO2+3">TP,NO2+3</option>
</select>
<label class="preserve-label" for="preserve">Preserved</label>
<select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "HNO3">HNO₃</option>
<option value = "H2SO4">H₂SO₄</option>
</select>
<label class="cool-label" for="cool">Cooled</label>
<select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
<option>Select</option>
<option value = "Ice">Ice</option>
<option value = "Frozen">Frozen</option>
<option value = "None">None</option>
</select>
</div> <!--Fieldblank-->
</fieldset> <!--Fieldblank -->
<hr /><span id="writeroot"></span>
</div> <!--duplicate template-->
</fieldset> <!--duplicate template-->
<button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
<button type="button" data-theme="b" data-icon="plus" id="add_FieldDup">ADD FIELD DUP</button>
I got the duplicate to work (when the field blank wasn't hidden) but I cannot get the field blank to work. Any assistance would be greatly appreciated!
You should extract your javascript from your dom, put it in separate js and make function work in any of this blocks, create class="template" block and inside give any needed interaction buttons and inputs classes so there can exist multiple parent elements with same inside structure... then cloning does not get in a way of your interaction logic.
In js go like:
$(document).ready(function() {
$(".template .interaction_button_one").on('click', function(){
//... here you go traversing like
$(this).parents('.template').find('.some_important_div').show();
})
});
Notice .on(), this is delegation, and it will give same interaction bindings to all of your elements.
Hi I'm trying to create a family tree of some sort. I have a drop down box that's it options are being dynamically added when I make a new family and prompts the user to add a child of the selected family.
I'm trying to append the child after the table of the selected family but I have no idea what kind of ID are being generated when they're dynamically made
code is below
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
//To Create Familes
$('#submit').on('click', function() {
var table = $('<table></table>').addClass('table');
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each( function() {
str = '<td>' + $(this).val() + '</td>';
$(this).val('');
table.append( str );
});
$('#container').append(table);
$('#select').append($('<option />', { text: family } ) );
});
//To Create child to right family
$('#submit2').on('click', function() {
var child = prompt("Enter the name of the child you wanna put to the selected family ");
something.after(child);
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id = "child">
<select id ="select"></select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id = "container">
</div>
</body>
</html>
any idea's of how to append after the selected families? or is there a better of doing this
the best way is to actually add elements rather than HTML for example:
var test = document.createElement('table');
test.setAttribute('id', 'test_id');
document.body.appendChild(test);
console.log(document.getElementById('test_id'));
to reference it, be sure to add an id and/or a class using the setAttribute javascript call or the .attr() or .prop() methods in jquery.
That's not very clear as to exactly what you're trying to do, but here's a tidier version that adds the child as a new row after the family's row:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script>
$(function() {
var cur_id = 0;
//To Create Familes
$('#submit').on("click", function(ev) {
var id = "family" + cur_id++,
$row = $('<tr id="' + id + '"></tr>');
$('#select').append('<option value="' + id + '">' + $("#famname").val() + '</option>');
$('#family :text')
.each(function() {
$row.append('<td>' + $(this).val() + '</td>');
})
.val("");
$('#container table').append($row);
});
//To Create child to right family
$('#submit2').click(function(ev) {
var child = prompt("Enter the name of the child you wanna put to the selected family "),
id = $("#select").val();
$("#" + id)
.after("<tr><td>" + child + "</td></tr>");
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
<label>Enter Family Name <input type="text" name="famname" id="famname"></label><br>
<label>Enter Address <input type="text" name="address"></label><br>
<label>Enter Father's name <input type = "text" name="dad"></label><br>
<label>Enter Mother's name <input type="text" name="mom"></label><br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id="child">
<select id="select"></select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id="container">
<table class="table"></table>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
//To Create Familes
$('#submit').on('click',function(){
var table = $('<table></table>').addClass('table');
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each(function() {
str = '<td>' + $(this).val() + '</td>';
$(this).val('');
table.append(str);
table.addClass(family);
});
$('#container').append(table);
$('#select').append($('<option />', {text: family, value:family}));
});
//To Create child to right family
var fam, child, str;
$(document).on('change', '#select', function(){
$('#submit2').show();
$('#child_name').show();
fam = $(this).children('#select :selected').val();
});
$(document).on('click', '#submit2', function(){
child = $('#child_name').val();
$('#submit2').hide();
$('#child_name').hide();
str = '<td>' + child + '</td>'
$('.'+fam).append(str);
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<select id ="select">
</select>
<input type="text" id="child_name" style="display:none;">
<input id="submit2" type="submit" value="button" name="submit" style="display:none;">
<div id = "container">
</div>
</body>
</html>
this should do, I tested this already...hope this helps
I have HTML like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
</div>
<input type='button' id='add' value='Add'>
jQuery:
$("input#add").live( 'click', function(){
$("#main").append("<br />");
$("#child-0").clone(false).appendTo( $("#main") );
});
Above code is working but it is creating elements with same name. I want to generate it something like this:
<div id='main'>
<div id='child-0'>
<input type='text' name='data[0][name]'>
<input type='text' name='data[0][dob]'>
<input type='text' name='data[0][location]'>
</div>
<div id='child-1'>
<input type='text' name='data[1][name]'>
<input type='text' name='data[1][dob]'>
<input type='text' name='data[1][location]'>
</div>
</div>
What is the simple solution.
Thanks
$("input#add").live( 'click', function(){
$("#main").append("<br />");
var cloned = $("#main div:last").clone(false).appendTo( $("#main") );
cloned.find('[name^=data]').attr('name', function() {
var index = this.name.match(/\[(\d)\]/);
if (index != null && index.length > 1) {
var newIndex = parseInt(index[1], 10) + 1;
return this.name.replace(/\[(\d)\]/, '[' + newIndex + ']');
}
return this.name;
});
});