Perform operations on a cloned form - javascript

I have created a form that contains two drop-down lists, when the user selects an item from the first list, the data for the second is automatically updated. I use jquery to do this and it works perfectly except that when I duplicate the form, the drop-down list N ° 1 of the duplicated form no longer updates the drop-down list N ° 2 so I would like to know how can I perform the same action on a cloned form (update a drop-down list by selecting one entered in another) and save the entries of all the cloned forms in a database.
Cordially!
here is the code i use
<form id="myForm">
<div id="clonedSection1" class="clonedSection">
<select class="form-control" name="productName[]" id="productName" >
<option value="0" selected>Selectionner le produit</option>
<option value="copy">Copie</option>
<option value="scan">Scan</option>
</select>
<select class="form-control" name="productPrice[]" id="quant" disabled>
<option value="pu" selected>P.U</option>
</select>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
<!-- script that allows you to modify the data in a drop-down list when an item is selected in another-->
<script type="text/javascript">
$("#productName").change(function () {
var val = $(this).val();
if (val == "copy") {
$("#quant").html("<option value='25'> 25$ </option>");
} else if (val == "scan") {
$("#quant").html("<option value='50'> 10$ </option>");
}
});
</script>
<!-- script that clones the form-->
<script type="text/javascript">
$(document).ready(function() {
$("#btnAdd").click(function() {
var num = $(".clonedSection").length;
var newNum = new Number(num + 1);
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":nth-child(5)").children(":first").attr("id", "productName" + newNum).attr("name", "productName[]" + newNum);
newSection.children(":nth-child(6)").children(":first").attr("id", "quant" + newNum).attr("name", "productPrice[]" + newNum);
$(".clonedSection").last().append(newSection)
$("#btnDel").attr("disabled","");
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length; // how many "duplicatable" input fields we currently have
$("#clonedSection" + num).remove(); // remove the last element
// enable the "add" button
$("#btnAdd").attr("disabled","");
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$("#btnDel").attr("disabled","disabled");
});
$("#btnDel").attr("disabled","disabled");
});
</script>

I have written simple and clean code.
Follow below steps:
Don't use ID so you need to use class name instead of id because of ID should be unique.
If appending dynamically element then need to use .on() instead of .change() method.
.cloned-section section should be separate from Add Button.
Each time pick clone element by .cloned-section>div:nth-child(1) this nth-child method.
Set value in input field by onchange .product-name class.
Remove element by onclick .btn-remove class.
When append clone element by append() method then select+input values need to set null so you can see in my jQuesy code and also see commented text.
I hope below snippet will help you lot.
$(document).on('click', '#btnAdd', function(){
// Make clone by clone() method and append REMOVE button for remove section
var cloneElement = $('.cloned-section>div:nth-child(1)').clone();
cloneElement.append('<button type="button" class="btn btn-danger btn-remove"><span aria-hidden="true">×</span></button>');
// Select value set Zero (0)
cloneElement.find('select').val(0);
// Input value set empty
cloneElement.find('input').val('');
$('.cloned-section').append(cloneElement);
});
// On change product name then set price on price field
$(document).on('change', '.product-name', function(){
var getValue = $(this).val();
$(this).parent().find('.product-price').val(getValue+'%');
});
// Click on Remove button and delete product/price section
$(document).on('click', '.btn-remove', function(){
$(this).parent().remove();
});
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div class="container my-2">
<div class="row">
<div class="col-sm-12">
<form class="form-inline" id="myForm">
<div class="cloned-section w-100">
<div class="w-100 mt-2">
<select class="form-control w-50 product-name" name="productName[]">
<option value="0" selected>Select Product</option>
<option value="25">Copy</option>
<option value="50">Scan</option>
<option value="75">Paste</option>
<option value="100">Cut</option>
</select>
<input class="form-control w-25 product-price text-center" name="productPrice[]" readonly>
</div>
</div>
<div class="w-100 mt-2">
<button type="button" id="btnAdd" class="btn btn-success">Add Another Name</button>
</div>
</form>
</div>
</div>
</div>

There are some minor problems of your code:
Use classname instead of id for DOM elements that going to be cloned.
It is because id is unique. Different elements should not share the
same id. If you clone an element with id, there would be elements
sharing the same id.
Use .on() instead of .change() for elements that generate
dynamically.
I'm not sure if you really want to insert a new "clonedSection"
inside the last "clonedSection". If you are not going to do this and
would like to insert new "clonedSection" right after the last
"clonedSection", use
newSection.insertAfter($(".clonedSection").last());
value of .attr("disabled", <>) should be either true or false, but not "" and disabled
$(document).ready(function() {
//use on() instead of change() for elements that generate dynamically
$("body").on("change", ".productName", function() {
var _this = $(this);
var quant = _this.closest(".clonedSection").find(".quant");
var val = _this.val();
if (val == "copy") {
quant.html("<option value='25'> 25$ </option>");
} else if (val == "scan") {
quant.html("<option value='50'> 10$ </option>");
}
});
$("#btnAdd").click(function() {
var num = $(".clonedSection").length;
var newNum = num + 1;
var newSection = $("#clonedSection" + num).clone().attr("id", "clonedSection" + newNum);
newSection.children(":nth-child(5)").children(":first").attr("id", "productName" + newNum).attr("name", "productName[]" + newNum);
newSection.children(":nth-child(6)").children(":first").attr("id", "quant" + newNum).attr("name", "productPrice[]" + newNum);
newSection.insertAfter($(".clonedSection").last()); //insert right after the last clonedsection
$("#btnDel").attr("disabled", false); //disabled should be either true/false but not ""
});
$("#btnDel").click(function() {
var num = $(".clonedSection").length;
$("#clonedSection" + num).remove();
$("#btnAdd").attr("disabled", false);
if (num - 1 == 1)
$("#btnDel").attr("disabled", true);
});
$("#btnDel").attr("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<!--If you are going to clone DOM element, please use classname instead of id-->
<div id="clonedSection1" class="clonedSection">
<select class="form-control productName" name="productName[]">
<option value="0" selected>Selectionner le produit</option>
<option value="copy">Copie</option>
<option value="scan">Scan</option>
</select>
<select class="form-control quant" name="productPrice[]">
<option value="pu" selected>P.U</option>
</select>
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
Hope this help :D

Related

JQuery remove element from parent

I have a "Try Again!" message that appears when the inserted value exists in my dropdown select list, this is my code:
//I am trying to remove this message once the user starts typing again:
$('#new_day').on('input', function(){
//Get input value
var input_value = $(this).val();
//Remove disabled from the button
$('#new_day_save').removeAttr('disabled');
//iterate through the options
$(".days > option").each(function() {
//If the input value match option text the disable button
if( input_value == $(this).text()){
$('#new_day_save').attr('disabled', 'disabled');
$('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>");
}else{
$('#new_day_save').parent().remove("#error_message");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="days">
<option>Monday</option>
<option>Friday</option>
</select>
<p>You have another proposition? Add it to the list.</p>
<div>
<input id="new_day" type="text" />
</div>
<input id="new_day_save" type="button" value="save new day"/>
you can just remove the #error_message by adding this to your event handler just before you compare input value to option
$('#new_day_save').parent().find('#error_message').remove()
and you can remove the else condition.
$('#new_day').on('input', function(){
//Get input value
var input_value = $(this).val();
//Remove disabled from the button
$('#new_day_save').removeAttr('disabled');
$('#new_day_save').parent().find('#error_message').remove();
//iterate through the options
$(".days > option").each(function() {
//If the input value match option text the disable button
if( input_value == $(this).text()){
$('#new_day_save').attr('disabled', 'disabled');
$('#new_day_save').parent().append("<p id=\"error_message\" style=\"color: red\">Try again !</p>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="days">
<option>Monday</option>
<option>Friday</option>
</select>
<p>You have another proposition? Add it to the list.</p>
<div>
<input id="new_day" type="text" />
</div>
<input id="new_day_save" type="button" value="save new day"/>
This line $('#new_day_save').parent().remove("#error_message"); will remove parent element.
To remove specific element in jQuery, do simply since it's a id selector which is unique element,
$("#error_message").remove();

jQuery clone form not working twice in the same page

I am trying to use the same form twice in the same page the form is working once but not twice i think the problem is with id or something but i am not sure i am not very good with javascript
Help appreciated.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
$('#btnAdd').click(function () {
var num = $('.clonedInput').length, // Checks to see how many "duplicatable" input fields we currently have
newNum = new Number(num + 1), // The numeric ID of the new input field being added, increasing by 1 each time
newElem = $('#entry' + num).clone().attr('id', 'entry' + newNum).fadeIn('slow'); // create the new element via clone(), and manipulate it's ID using newNum value
// H2 - section
newElem.find('.heading-reference').attr('id', 'ID' + newNum + '_reference').attr('name', 'ID' + newNum + '_reference').html('Entry #' + newNum);
// Title - select
newElem.find('.label_ttl').attr('for', 'ID' + newNum + '_title');
newElem.find('.select_ttl').attr('id', 'ID' + newNum + '_title').attr('name', 'ID' + newNum + '_title').val('');
// First name - text
newElem.find('.label_fn').attr('for', 'ID' + newNum + '_first_name');
newElem.find('.input_fn').attr('id', 'ID' + newNum + '_first_name').attr('name', 'ID' + newNum + '_first_name').val('');
// Insert the new element after the last "duplicatable" input field
$('#entry' + num).after(newElem);
$('#ID' + newNum + '_title').focus();
// Enable the "remove" button. This only shows once you have a duplicated section.
$('#btnDel').attr('disabled', false);
// Right now you can only add 4 sections, for a total of 5. Change '5' below to the max number of sections you want to allow.
if (newNum == 5)
$('#btnAdd').attr('disabled', true).prop('value', "You've reached the limit"); // value here updates the text in the 'add' button when the limit is reached
});
$('#btnDel').click(function () {
// Confirmation dialog box. Works on all desktop browsers and iPhone.
if (confirm("Are you sure you wish to remove this section? This cannot be undone."))
{
var num = $('.clonedInput').length;
// how many "duplicatable" input fields we currently have
$('#entry' + num).slideUp('slow', function () {$(this).remove();
// if only one element remains, disable the "remove" button
if (num -1 === 1)
$('#btnDel').attr('disabled', true);
// enable the "add" button
$('#btnAdd').attr('disabled', false).prop('value', "add section");});
}
return false; // Removes the last section you added
});
// Enable the "add" button
$('#btnAdd').attr('disabled', false);
// Disable the "remove" button
$('#btnDel').attr('disabled', true);
});
</script>
</head>
<body>
<div id="wrapper">
<div class="sign-up_box">
<form action="#" method="post" id="sign-up_area">
<div id="entry1" class="clonedInput">
<h2 id="reference" name="reference" class="heading-reference">Entry #1</h2>
<fieldset>
<label class="label_ln" for="last_name">Last name:</label>
<input class="input_ln" type="text" name="last_name" id="last_name" value="">
</fieldset>
</div><!-- end #entry1 -->
<div id="addDelButtons">
<input type="button" id="btnAdd" value="add section"> <input type="button" id="btnDel" value="remove section above">
</div>
<fieldset class="form-actions">
<input type="submit" value="Submit">
</fieldset>
</form>
</div><!-- end sign-up_box -->
</div>
<div id="wrapper">
<div class="sign-up_box">
<form action="#" method="post" id="sign-up_area">
<div id="entry1" class="clonedInput">
<h2 id="reference" name="reference" class="heading-reference">Entry #1</h2>
<fieldset>
<label class="label_ln" for="last_name">Last name:</label>
<input class="input_ln" type="text" name="last_name" id="last_name" value="">
</fieldset>
</div><!-- end #entry1 -->
<div id="addDelButtons">
<input type="button" id="btnAdd" value="add section"> <input type="button" id="btnDel" value="remove section above">
</div>
<fieldset class="form-actions">
<input type="submit" value="Submit">
</fieldset>
</form>
</div><!-- end sign-up_box -->
</div>
</body>
</html>
Id tags must be unique within an HTML document or they won't work right. You'll probably want to "class" instead of "id" and use jQuery class selectors to select the appropriate fields, depending on what exactly you're trying to do.
Here are a few existing StackOverflow questions related to this:
Using same ID for in multiple HTML tags?
Several elements with the same ID responding to one CSS ID selector
javascript duplication ID conflict
You cannot simply clone elements which have an id attribute. There mustn't be two elements with the same id on any single page. So please change the ids of the cloned elements accordingly, and the references to them in the code.

JQuery - dynamically selecting inputs with "nth"

I have a question that I've been stuck on. I have a form and want to dynamically be able to call upon the n-th set of input fields in a form to use them in equations that will output the n-th set of answers. For example "footage2" should be plugged into an equation that will give me "postQuantity2" and then "footage3" should be used to determine "postQuantity3". The problem is that the form can add input areas dynamically so I can't just hard code it to do what I want. Any ideas of how to get the nth set of numbers to be used for an equation and then give me the nth set of answers? If anyone can explain how this would work, or just point out how it wouldn't it'd be very much appreciated! Thanks!
Here is a snippet - http://jsfiddle.net/gv0029/QGW7R/ - to give you a basic idea of what I'm working with and here is some html and js.
HTML
<fieldset id="fence">
<div id="inputFence1" class="clonedInputFence">
<fieldset id="fenceDescripton">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input type="number" id="footage" name="footage" value="" /></label>
<select name="fenceHeight" id="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
</fieldset>
<fieldset id="post">
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input type="postQuantity" name="postQuantity" id="postQuantity" value="" />
</label>
<select name="postMeasurements" id="postMeasurements">
<option value="select">Select Post Measurements</option>
<option value="23/8 x .065 x 8" id="23/8 x .065 x 8">2 3/8 x .065 x 8</option>
<option value="23/8 x .095 x 8" id="23/8 x .095 x 8">23/8 x .095 x 8</option>
</select>
</fieldset>
</div>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
JS
//Quantity for Posts
$('#footage, #manualOverrideNo').bind('keypress keydown keyup change', function(){
var footage = parseFloat($(':input[name="footage"]').val(),10);
var total = '';
if(!isNaN(footage)){
total = Math.ceil(footage /7);
$(':input[name="postQuantity"]').val(total.toString());
} else {
$(':input[name="postQuantity"]').val("");
}
});
//Dynamic Fence Input Fields
$('#btnAddFence').click(function() {
var num = $('.clonedInputFence').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#inputFence' + num).clone().attr('id', 'inputFence' + newNum);
//Fieldset creation
newElem.find('fieldset').attr('id', 'fence' + newNum);
//Fence Description
newElem.find("select[name=fenceHeight]").attr('id', 'fenceHeight' + newNum).attr('name', 'fenceHeight' + newNum);
newElem.find(':input[name="footage"]').attr('id', 'footage' + newNum).attr('name', 'footage' + newNum);
//Post Type
newElem.find(':input[name="postQuantity"]').attr('id', 'postQuantity' + newNum).attr('name', 'postQuantity' + newNum);
newElem.find("select[name=postMeasurements]").attr('id', 'postMeasurements' + newNum).attr('name', 'postMeasurements' + newNum);
// insert the new element after the last "duplicable" input field
$('#inputFence' + num).after(newElem);
// enable the "remove" button
//$('#btnDel').attr('disabled','');
$('#btnDelFence').removeAttr('disabled');
});
$('#btnDelFence').click(function() {
var num = $('.clonedInputFence').length; // how many "duplicatable" input fields we currently have
$('#inputFence' + num).remove(); // remove the last element
// enable the "add" button
//$('#btnAdd').attr('disabled','');
$('#btnAddFence').removeAttr('disabled');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDelFence').attr('disabled','disabled');
});
$('#btnDelFence').attr('disabled','disabled');
I don't think nth-child will work in this case since there are multiple child elements and the op wants to match them up.
On your footage elements, add a data attribute of, let's say, data-which-pair with a pattern like
id = n data-which-pair = n
$("#footage"+n).click(function(){
var n = $(this).attr("data-which-pair");
Do something cool with $("#postQuantity"+n);
}
You might be able to just do a function(n) but I usually follow this longer-winded approach because it is easier to see what's going on. Keep in mind, obviously, that the above is pseudocode that you will need to adapt.

JQuery - New name based off of old name

I'm building a form that can add extra fieldsets and inputs. I am trying to get the fieldsets and inputs to have an individual ids and names (such as fenceDescription2, fenceDescription3) but I can't figure out how to have the new element (for either the fieldset or the inputs) call on its own name so that it can add a new number to it. I got it to work with just one field but cant get the names to and the newNum correctly when I have multiple fieldsets. Ideally every time you clicked "add new fence" a clone of the elements would pop up underneath, each with a matching newNumber that corresponds to their order in the form (fenceHeight2 with postQuantity2 and postMeasurement2, and then 3 with 3, etc). Any help explaining how this is done would be greatly appreciated! Thanks! Here is a JSFiddle - http://jsfiddle.net/gv0029/3dnNP/1/
HTML :
<fieldset id="fence">
<div id="inputFence1" class="clonedInputFence">
<fieldset id="fenceDescripton">
<legend><strong>Fence Description</strong>
</legend>Fence Description:
<select name="fenceHeight" id="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
</fieldset>
<fieldset id="post">
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input type="postQuantity" name="postQuantity" id="postQuantity" value="" />
</label>
<select name="postMeasurements" id="postMeasurements">
<option value="select">Select Post Measurements</option>
<option value="23/8 x .065 x 8" id="23/8 x .065 x 8">2 3/8 x .065 x 8</option>
<option value="23/8 x .095 x 8" id="23/8 x .095 x 8">23/8 x .095 x 8</option>
</select>
</fieldset>
</div>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
JS:
//Dynamic Fence Input Fields
$('#btnAddFence').click(function() {
var num = $('.clonedInputFence').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#inputFence' + num).clone().attr('id', 'inputFence' + newNum);
//Fieldset creation
newElem.find('fieldset').attr('id', 'name' + newNum);
//Fence Description
newElem.find($("select[name=fenceHeight]")).attr('id', 'fenceHeight' + newNum).attr('name', 'fenceHeight' + newNum);
//Post Type
newElem.find($(':input[name="postQuantity"]')).attr('id', 'postQuantity' + newNum).attr('name', 'postQuantity' + newNum);
newElem.find($("select[name=postMeasurements]")).attr('id', 'postMeasurements' + newNum).attr('name', 'postMeasurements' + newNum);
// insert the new element after the last "duplicable" input field
$('#inputFence' + num).after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
// business rule: you can only add 5 names
//if (newNum == 5)
//$('#btnAdd').attr('disabled','disabled');
});
$('#btnDelFence').click(function() {
var num = $('.clonedInputFence').length; // how many "duplicatable" input fields we currently have
$('#inputFence' + num).remove(); // remove the last element
// enable the "add" button
//$('#btnAdd').attr('disabled','');
$('#btnAddFence').removeAttr('disabled');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDelFence').attr('disabled','disabled');
});
$('#btnDelFence').attr('disabled','disabled');

JS works in one place but not another

I'm stumped on something that is a little odd. I was tinkering with some code in an html file that had js and html on it until I got it to work like I wanted then I copied and pasted it to the php file that is linked to a JS page. The trouble is that in the php page I get the error message unrecognized expression: select[name=gateHeight] option: selected. If anyone could explain what I messed up I would appreciate it very much!
Here is the html file with JS and HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children($("select[name=gateHeight] option: selected")).attr('id', 'gateHeight' + newNum).attr('name', 'gateHeight' + newNum);
//newElem.children('input[type=text]:first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newElem.children('input[type=checkbox]:first').attr('id', 'chk' + newNum).attr('name', 'chk' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
//$('#btnDel').attr('disabled','');
$('#btnDel').removeAttr('disabled');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
//$('#btnAdd').attr('disabled','');
$('#btnAdd').removeAttr('disabled');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
});
</script>
</head>
<body>
<form id="myForm">
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<!-- <input type="text" name="name1" id="name1" /> -->
<select name="gateHeight" id="gateHeight">
<option value="select">Select Gate Height</option>
<option value="4fg">4 Ft. Gate</option>
<option value="6fg">6 Ft. Gate</option>
<option value="8fg">8 Ft. Gate</option>
</select>
Include Spring Pool Latch: <input type="checkbox" name="chk1" id="chk1" />
</div>
<div>
<input type="button" id="btnAdd" value="add another name" />
<input type="button" id="btnDel" value="remove name" />
</div>
</form>
</body>
And here is the JS and HTML of the other file:
JS:
//Dynamic Gate Input Fields
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children($("select[name=gateHeight] option: selected")).attr('id', 'gateHeight' + newNum).attr('name', 'gateHeight' + newNum);
//newElem.children('input[type=text]:first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);
newElem.children('input[type=checkbox]:first').attr('id', 'chk' + newNum).attr('name', 'chk' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
//$('#btnDel').attr('disabled','');
$('#btnDel').removeAttr('disabled');
// business rule: you can only add 5 names
if (newNum == 5)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
//$('#btnAdd').attr('disabled','');
$('#btnAdd').removeAttr('disabled');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$('#btnDel').attr('disabled','disabled');
HTML:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<select name="gateHeight" id="gateHeight">
<option value="select">Select Gate Height</option>
<option value="4fg">4 Ft. Gate</option>
<option value="6fg">6 Ft. Gate</option>
<option value="8fg">8 Ft. Gate</option>
</select>
Include Spring Pool Latch: <input type="checkbox" name="chk1" id="chk1" />
</div>
<div>
<input type="button" id="btnAdd" value="Add Another Gate" />
<input type="button" id="btnDel" value="Remove Gate" />
</div>
You are missing the document ready wrapper function your code is called before the element exist therefore fail.
Try with
$("select[name=gateHeight] option :selected")
:selected is the right one not : selected (no space)
OR
$("select[name=gateHeight] option").filter(":selected")
This will work
You need to get rid of the space after the colon in option: selected. Just change that to option:selected.
First you should use the updated version of jquery like jquery-1.9 or higher.
Second you should use newElem.children("select[name=gateHeight]") in place of
newElem.children($("select[name=gateHeight] option: selected"))
like
newElem.find("select[name='gateHeight']")
.attr({'id': 'gateHeight'+newNum, 'name': 'gateHeight' + newNum});// combine attr() using json
Demo

Categories