on change function also affect on clone div - javascript

i want to show and hide div base on change function.. and its work well on first div whenever i add(append) new div that time change function affect in both div.
$(".transport_type").hide();
$(".rate").hide();
$(".adult").hide();
$(".child").hide();
$("body").on("change", "#transport_cat", function(e) {
e.preventDefault();
if($(this).val() == 'PVT') {
$('.rate').show();
} else {
$('.rate').hide();
}
if($(this).val() == 'SIC') {
$('.adult').show();
$('.child').show();
} else {
$('.adult').hide();
$('.child').hide();
}
});
here is a demo here
i want to do only show hide div on change that select div not want to affect on another div.please help me...

Couple of mistakes:
Do not use id attribute for transport_cat element as this element is getting cloned and multiple elements with same id is wrong
While hide/show div, set the context as well, just $('.rate').show() will show all divs with rate class. So set context.
Remove $("body").on("change", "#transport_cat", function(e) { binding of change event while cloning as you are using $.on() method
I have updated the fiddle - https://jsfiddle.net/swpL5xwp/2/
<select class="form_line_only form-control className transport_cat" name="tr_cartypes[]">
<option selected> Select Tour </option>
<option value="PVT"> PVT </option>
<option value="SIC"> SIC </option>
</select>
$("body").on("change", ".transport_cat", function(e) {
e.preventDefault();
var $context = $(this).parents('.entry_special_offers');
if ($(this).val() == 'PVT') {
$('.rate',$context).show();
} else {
$('.rate',$context).hide();
}
if ($(this).val() == 'SIC') {
$('.adult',$context).show();
$('.child',$context).show();
} else {
$('.adult',$context).hide();
$('.child',$context).hide();
}
});

Couple of things you need to look into,
You need to find the closest entry_special_offers class.
You need fix your current implementation where you find all elements with class rate / adult and others. You should find them withing current entry_special_offers div only.
Also you have attached change events twice which is not required.
$(".transport_type").hide();
$(".rate").hide();
$(".adult").hide();
$(".child").hide();
$("body").on("change", "#transport_cat", function(e) {
e.preventDefault();
if ($(this).val() == 'PVT') {
$(this).closest(".entry_special_offers").find('.rate').show();
} else {
$(this).closest(".entry_special_offers").find('.rate').hide();
}
if ($(this).val() == 'SIC') {
$(this).closest(".entry_special_offers").find('.adult').show();
$(this).closest(".entry_special_offers").find('.child').show();
} else {
$(this).closest(".entry_special_offers").find('.adult').hide();
$(this).closest(".entry_special_offers").find('.child').hide();
}
});
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls_special_offers:first'),
currentEntry = $(this).closest('.entry_special_offers'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry_special_offers:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function(e)
{
$(this).closest('.entry_special_offers').remove();
e.preventDefault();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container excursions margin_top">
<!--container hotel -->
<div class="controls_special_offers">
<div class="entry_special_offers input-group col-sm-12 col-xs-12 ">
<div class="col-sm-2 col-xs-6">
<div class="form-group">
<label for="exampleInputindate">Tour</label>
<div class="form-group">
<select class="form_line_only form-control className" name="tr_cartypes[]" id="transport_cat">
<option selected>Select Tour</option>
<option value="PVT">PVT</option>
<option value="SIC">SIC</option>
</select>
</div>
</div>
</div>
<div class="col-sm-3 col-xs-6 transport_type">
<div class="form-group">
<label for="exampleInputindate">transportation type</label>
<div class="form-group">
<select class="form_line_only form-control " name="tr_seattype[]">
<option selected>Select Type</option>
<option>7 Seater</option>
<option>15 Seater</option>
<option>34 Seater</option>
<option>50 Seater</option>
</select>
</div>
</div>
</div>
<div class="col-sm-2 col-xs-6 rate">
<div class="form-group ">
<label for="exampleInputindate">rate</label>
<div class="form-group">
<input type="number" name="tc_rates[]" id="tc_rate" class=" form_line_only form-control" placeholder="Enter Price" value="" autocomplete="off">
</div>
</div>
</div>
<div class="col-sm-2 col-xs-6 adult">
<div class="form-group">
<label for="exampleInputindate">Adult</label>
<div class="form-group">
<input type="number" name="tc_adults[]" id="tc_adult" class=" form_line_only form-control" placeholder="Adult Price" value="" autocomplete="off">
</div>
</div>
</div>
<div class="col-sm-2 col-xs-6 child">
<div class="form-group">
<label for="exampleInputindate">Child</label>
<div class="form-group">
<input type="number" name="tc_childs[]" id="tc_child" class=" form_line_only form-control" placeholder=" Child Price " value="" autocomplete="off">
</div>
</div>
</div>
<span class="input-group-btn day_plan pull-left">
<button class="btn btn-success btn-add add_col" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
<br>
</div>
</div>

Related

On change of a selected value show an input

I am trying to choose yes value in this dropdown, so I can show another input field to add discount.
I am trying but nothing is showing. Can you please help me?
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onclick="myFunction()" required>
<option value="" disabled selected >--Choose--</option>
<option value="yes" >Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
<script>
function myFunction() {
if (document.getElementById('is_offer').value = 'yes') {
document.getElementById('offer').innerText = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
}
</script>
function myFunction() {
if (document.getElementById('is_offer').value = 'yes') {
document.getElementById('offer').innerText = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
}
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onclick="myFunction()" required>
<option value="" disabled selected>--Choose--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
Your condition statement has issues. Use document.getElementById('is_offer').value === 'yes' (triple-equals)
function myFunction()
{
if (document.getElementById('is_offer').value === 'yes')
{
document.getElementById('offer').innerHTML = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div></div></div>';
}
}
and change onclick with onChange.
Use .innerHTML to set the div not innerText. innerText assumes all your html data is text and adds it like a text. ,For the yes condition, = is used for assignment but we have to compare so == is used. And call the function on onchange event not on click of the select tag
function myFunction()
{
if( document.getElementById('is_offer').value=='yes')
{
document.getElementById('offer').innerHTML='<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
else
document.getElementById('offer').innerHTML=''
}
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onChange="myFunction()" required>
<option value="" disabled selected >--Choose--</option>
<option value="yes" >Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
You had 3 issues should be changed.
If you want to listen the change of input, you shoule use onchange instead of onclick.
In if condition you use assigning variables instead of comparison (use == or ===).
It seems you would like to change HTML content. So you should use innerHTML instead of innerText.
After fixing all of them we have code like this:
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onchange="myFunction()" required>
<option value="" disabled selected>--Choose--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
<script>
function myFunction() {
if (document.getElementById('is_offer').value === 'yes') {
document.getElementById('offer').innerHTML = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
}
</script>
Prefer to use the onchange event on the select tag. Also, you should use === to compare the value with yes or no, not just = whish is an assignment.
By using a template and cloning it, you don't have to mix your JavaScript with HTML code, you just have to fetch the template, clone it and append it to your div.
Do not query the document to find your select in your handler, you have access to it via the event.target object, which you get access to as argument to your handler.
Also, don't forget to erase the discount when you select no.
function onSelect(event) {
const offer = document.getElementById('offer');
offer.innerHTML = '';
if (event.target.value === 'yes') {
const tpl = document.getElementById('discount-tpl');
const clone = document.importNode(tpl.content, true);
offer.appendChild(clone);
}
}
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onchange="onSelect(event)" required>
<option value="" disabled selected >--Choose--</option>
<option value="yes" >Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
<template id="discount-tpl">
<div class="form-group m-form__group row">
<label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label>
<div class="col-xl-9 col-lg-9">
<div id="asd"></div>
</div>
</div>
</template>

Optimize the repetitive code for adding new option to select jquery

Here is my fiddle : DEMO
I have repeated codes for adding new options to rule and event category select. How do I optimize the same to eliminate the repeated code?
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
Here you go - a common function helps a lot:
//Adding new category for rule
$(document).on('click', '.addrule', function() {
AddElement("categoryrule", "new-option-rule");
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
AddElement("categoryevent", "new-option-event");
});
function AddElement(selectId, newElementId){
var found = false; // Track if new value was found in list
// Loop through list options
$( "#" + selectId + " > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#" + newElementId).val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#' + newElementId).val('');
}
});
// If not found
if ($('#' + newElementId).val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#" + newElementId).val().trim();
var opt = '<option>' + val + '</option>';
$('#' + selectId).append(opt);
$('#' + selectId).val(val);
$('#' + newElementId).val('');
$("#" + selectId).click();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Here you go with some optimised code https://jsfiddle.net/3tLx884e/2/
//Adding new category for rule
$(document).on('click', '.addrule', function() {
var found = false; // Track if new value was found in list
// Loop through list options
var text = $("#new-option-rule").val().trim();
$("#categoryrule > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if (text.toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!");
found = true; // Set flag if value exists
}
if((idx + 1) === $('#categoryrule > option').length){
if ( !found && (text != '')) {
// Create new option and append to list
$('#categoryrule')
.append('<option>' + text + '</option>')
.val(text);
}
$('#new-option-rule').val('');
}
});
// If not found
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Hope this will help you.
This is my take on the problem, following jquery's slogan: "write less, do more" ...
I reduced the code further by working on local context. I. e. I only need to define one click event for everything. The click function itself figures out, what to change. It does not need any ids to do its job:
//Adding new category for rule and event
$('.form-group').on('click', 'button', addElement);
function addElement(){
var $grp=$(this).closest('.form-group'),
ival=$('input:text',$grp).val().trim(), // new input value
$sel=$('select',$grp.prev()), // select element
opts=$.makeArray($('option',$sel).map(function(i,op){
return op.textContent.toLowerCase(); }));
if ($.inArray(ival.toLowerCase(),opts)===-1){ // check existing option values
$sel.append('<option value="'+ival+'" selected>'+ival+'</option>');
}
else {alert(ival+' exists already in '+$sel[0].id);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>

Second Time Checkbox Not Working

I have created a two javascript.
1.When i click the checkbox the input field is appeared and when i unchecked input field is disappeared.
2.Second is when i click the add more items the all fields are created one more time.
Now the problem is when is created a second and more items the checkbox is not working.
HTML Code:
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12">
<div data-role="dynamic-fields">
<div class="form-inline">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="Name1" placeholder="Food Name" name="Name1" style="width:120%;" required data-rule-minlength="2">
<label class="sr-only" for="field-name">Name</label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="field-value" placeholder="Description" style="width:120%;" required>
<label class="sr-only" for="field-value">Description</label>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<select id="select1" name="select1" style="width:130%;" class="form-control" required>
<option value=""></option>
<option value="1">Food Type 1</option>
<option value="2">Food Type 2</option>
<select>
<label for="select1">Food Type</label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" value="" class="form-control" data-role="tagsinput" placeholder="Tags" />
<label class="sr-only" for="field-tags">Tags</label>
</div>
</div>
</div>
<div class="row">
<div class="form-inline">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="Name1" placeholder="Price" name="price" style="width:120%;" required data-rule-minlength="2">
<label class="sr-only" for="field-name">Price</label>
</div>
</div>
<div class="col-md-2">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" id="trigger2" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields2">
<input type="text" id="hidden_field2" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-35px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
<div class="col-md-3">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" id="trigger" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields">
<input type="text" id="hidden_field" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-100px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
</div>
</div>
<button class="btn btn-icon-toggle btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove"> <span class="md md-delete"></span> </button>
<button class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add"> Add More Items </button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
</div>
<!-- /div.col-md-12 -->
</div>
<div class="form-group">
<button type="button" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary">Submit Items</button>
</div>
<!--end .form-group -->
</div>
Checkbox Js:
<script type="text/javascript">
$(function() {
// Get the form fields and hidden div
var checkbox = $("#trigger");
var hidden = $("#hidden_fields");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
// Make sure that the hidden fields are indeed
// hidden.
hidden.hide();
$("#hidden_field").val("");
}
});
});
$(function() {
var checkbox = $("#trigger2");
var hidden = $("#hidden_fields2");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
hidden.hide();
$("#hidden_field2").val("");
}
});
});
</script>
Add more items JS:
$(function() {
// Remove button
$(document).on('click', '[data-role="dynamic-fields"] > .form-inline [data-role="remove"]', function(e) {
e.preventDefault();
$(this).closest('.form-inline').remove();
});
// Add button
$(document).on('click', '[data-role="dynamic-fields"] > .form-inline [data-role="add"]', function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function() {
$(this).val('');
});
container.append(new_field_group);
});
});
page Screenshot:
There are a couple of problems here:
You are cloning elements and then trying to access them via the same ID (you should use class)
Your functions don't target just clicked element but any element with the selector.
You are cloning elements so you need bind the click event to a non-cloned element: e.g. via $(document).on
I've updated some of your code to demonstrate what I'm talking about. In the html, I've added classes in the trigger2 and hidden_fields2 elements and display:none style to the hidden fields so they are hidden by default.:
<div class="col-md-2">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question"> </label>
</div>
</div>
<div class="col-md-1">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="hidden" placeholder="Price" class="form-control" style="width:140%;margin-left:-35px;height: 29px;margin-top: 24px;font-weight: 380;font-size: 16px;line-height: 1.5;"> </div>
</div>
In the javascript, I've changed the function to run from a $(document).on event bind and used the element class instead of the id. I've also changed the code so it only effects the checkbox you change and the closest hidden elements:
$(function() {
$(document).on('change', '.trigger2', function(){
var checkbox = $(this);
var parent = checkbox.closest('.form-inline');
var hidden = parent.find(".hidden_fields2");
hidden.hide();
if (checkbox.is(':checked')) {
// Show the hidden fields.
hidden.show();
} else {
hidden.hide();
$(".hidden_field2").val("");
}
});
});
You need to use the same logic on your other functions and inputs.

Unable to dynamically add name attribute to form element

I wish to dynamically add the name attribute as 'pickup_city2' and 'pickup_address2' to select elements with ids, pickup_cityExtend and pickup_addressExtend.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cityPick form-horizontal form-label-right" action="" method="POST" novalidate>{% csrf_token %}
<div class="form-group">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="city" name="pick_up_city">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="address" name="pick_up_address">
</div>
</div>
</div>
<div class="multiCheck col-md-4 col-sm-4 col-xs-12">
<input type="checkbox" value="Yes" id="multiCheck">Have more than one pickup point?
<br>
</div>
</div>
<div class="form-group hide" id="cityPickExtend">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="pickup_cityExtend" name="">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="pickup_addressExtend" name="">
</div>
</div>
</div>
<div class="removeBtn col-md-1 col-sm-1 col-xs-2">
<button type="button" id="removeBtn">Remove</button>
</div>
<div class="addBtn">
<button type="button" id="addBtn">Add another pickup location</button>
</div>
</div>
<div class="item form-group">
<label for="shipment_datetime" class="control-label dateTime">Pickup Date & time
<span class="required">*</span>
</label>
<div class="input-group date form_datetime col-md-4 col-sm-4 col-xs-12" data-date="" data-date-format="dd MM yyyy - HH:ii p" data-link-field="dtp_input1">
<input class="form-control" size="16" name="shipment_datetime" type="text" value="" readonly style="background-color: #fff;">
<span class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</span>
<span class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</span>
</div>
</div>
</form>
Below is my jquery code.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
Within the part that you clone, there are four elements that have an id attribute. As id values must be unique, the DOM API will always return the first match when you query for a certain id, such as in these lines:
var city = document.getElementById('pickup_cityExtend');
var address = document.getElementById('pickup_addressExtend');
The results do not match the elements in the part you added to the document.
In order to make it work, you need to replace the id values with something that is unique (by adding a 2 for instance).
As a side note: you are mixing jQuery syntax with native DOM methods to retrieve elements. It would be more consistent if you would not use document.getElementById, but the jQuery $('#...') equivalent.
Here is some adjusted code:
var $clone;
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id');
// Add '2' to all ID values, and set name value to the same.
$clone.find('[id]').each(function () {
var id = $(this).attr('id') + '2';
$(this).attr('id', id).attr('name', id);
});
// Now that the id value are unique, it is OK to add the clone:
$clone.insertAfter($pick);
} else if ($clone) { // Check whether we actually have a clone
$clone.remove();
}
});

Why does the change event never fire on a select box?

I've 3 list box like this one with a different id and name:
<div class="col-md-4 column">
<div class="form-group">
<input type="hidden" name="identityCardList[0].identityCardId">
<label for="identityCardType1" class="col-sm-3 control-label">Type</label>
<div class="col-sm-9">
<select id="identityCardType1" name="identityCardList[0].identityCardType" class="form-control">
</select>
</div>
</div>
<div class="form-group">
<label for="idCardValue1" class="col-sm-3 control-label">Valeur</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="idCardValue1" name="identityCardList[0].value" placeholder="Entrer la valeur">
</div>
</div>
<div class="form-group">
<label for="expirationDateCard1" class="col-sm-3 control-label">Expiration</label>
<div class="col-sm-9">
<div class="input-group date" id="expirationDateCardPicker1">
<input type="text" id="expirationDateCard1" name="identityCardList[0].expiration" class="form-control"><span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<div class="checkbox">
<label><input type="checkbox" name="identityCardList[0].lodgerOwn" value="">Garde sur eux</label>
</div>
</div>
</div>
</div>
<div class="col-md-4 column">
...
</div>
<div class="col-md-4 column">
...
</div>
In the list box, I've this kind of value:
<select id="identityCardType1" name="identityCardList[0].identityCardType" class="form-control">
<option value=""></option>
<option value="1" data-card-expiration="false">Certificat de naissance</option>
<option value="2" data-card-expiration="false">N.A.S</option>
<option value="3" data-card-expiration="true">N.A.M</option>
</select>
When I select a value in the list box, I'd like to read the data-card-expiration value and disable expiration input text if needed.
This is my generic attempt:
$("select[id^='identityCardType']").on('change', 'select', function (e){
debugger;
if($(e.target).data("data-card-expiration")){
//disabled the nearest component expirationDateCard after this select
}
});
Why does the change event never occur?
You don't need to pass the selector 'select' to .on() just remove it. the selector filters the descendant of element.
$("select[id^='identityCardType']").on('change', function (e){ //Removed 'select'
});
Try this easy code
$("select#identityCardType1").on('change', function (e){
if($(this).data("cardexpiration")){
//disabled the nearest component expirationDateCard after this select
}
});

Categories

Resources