I have a form with a drop-down with contains names of food items and another with an input field to allow the user to input price. beneath this, i have another drop down with class="IfNotAvailableSelectable" which contains 3 option, with values:0,1,2.
and I have a button called "addMore" to clone everything within the div with class="divContainer"
the following is what I want to achieve:
1.When the user clicks on the "addmore" button, it should clone everything within the div with class="divContainer" and append it to the div with class="addMoreContent". Of which I have been able to do successfully.
2.When the user selects the drop-down with class="IfNotAvailableSelectable" and value =0, it show div with class="thenBuy" , else it should hide it.
now the problem am facing is that, whenever i click the addmore button and select the drop down with option value 1 or 0 or 2, the original cloned div also changes with it,
so e,g: if i select value 1 ,i expect the div with class="thenBuy" to hide but when on the addmore button, and select the dropdown with value = 0, it show the div with class="thenBuy" in the 1st one too,while i don't want it to.
Please help,or if there;s a better solution to this.Will really appreciate.Thank you
HTML:
$(document).ready(function () {
//clone
var divContainer = $(".divContainer");
var addMoreContent = $(".addMoreContent");
var addMoreBtn = $(".addMoreBtn");
var removeItem = $(".removeItem");
addMoreBtn.click(function () {
divContainer.clone(true).appendTo(addMoreContent);
});
removeItem.click(function (e) {
$(this).closest('div').remove();
e.preventDefault();
});
//then buy functionO(when user selects "buy alternative")
$(document).on('change', '.IfNotAvailableSelectable', function () {
console.log($(this).val())
var MainNav = $(this).val();
if (MainNav == 0) {
$(".thenBuy").show();
} else {
$(".thenBuy").hide();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- card body-->
<div class="card-body bg-white divContainer" >
<!-- delete button -->
<button type="button" class="close col-1 bg-white removeItem" >
<span>×</span>
</button>
<!-- items -->
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
<br>
<br>
<!-- price -->
<div >
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
<br>
<!-- if item is not available -->
<div style="font-size: medium;" >
<select class="custom-select text-capitalize IfNotAvailableSelectable">
<option value="0" >If item is not available</option>
<option value="1" >Remove it from my order </option>
<option value="2">Cancel entire order</option>
</select>
<br>
<!-- then buy -->
<div class="thenBuy" >
<div>
<span>Then Buy</span>
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
</div>
<br>
<!-- price -->
<div >
<span>Price</span>
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
</div>
</div>
<!-- end of card body -->
</div>
<br>
<div class="addMoreContent" ></div>
<!-- onclick of add more,display the fiels here -->
<button type="button" class="float-right btn btn-outline-dark btn-sm addMoreBtn">Add More</button>
<br>
With $(".thenBuy") you select all the elements with class name thenBuy you need to use .parent().find(".thenBuy")
To let the new .IfNotAvailableSelectable take change effect after cloned use .IfNotAvailableSelectable
$(document).ready(function () {
//clone
var divContainer = $(".divContainer"),
addMoreContent = $(".addMoreContent"),
addMoreBtn = $(".addMoreBtn"),
removeItem = $(".removeItem");
addMoreBtn.click(function () {
divContainer.clone(true).appendTo(addMoreContent);
addMoreContent.find(".IfNotAvailableSelectable").last().change(); //<<<<<<<<<< trigger the change event for the last/new IfNotAvailableSelectable
});
removeItem.click(function (e) {
$(this).closest('div').remove();
e.preventDefault();
});
//then buy functionO(when user selects "buy alternative")
$(document).on('change', '.IfNotAvailableSelectable', function () {
console.log($(this).val())
var ThisSelect = $(this); // define this
var MainNav = ThisSelect.val(); // get this val
if (MainNav == 0) {
ThisSelect.parent().find(".thenBuy").show(); // use .parent().find
} else {
ThisSelect.parent().find(".thenBuy").hide(); // use .parent().find
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- card body-->
<div class="card-body bg-white divContainer" >
<!-- delete button -->
<button type="button" class="close col-1 bg-white removeItem" >
<span>×</span>
</button>
<!-- items -->
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
<br>
<br>
<!-- price -->
<div >
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
<br>
<!-- if item is not available -->
<div style="font-size: medium;" >
<select class="custom-select text-capitalize IfNotAvailableSelectable">
<option value="0" >If item is not available</option>
<option value="1" >Remove it from my order </option>
<option value="2">Cancel entire order</option>
</select>
<br>
<!-- then buy -->
<div class="thenBuy" >
<div>
<span>Then Buy</span>
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
</div>
<br>
<!-- price -->
<div >
<span>Price</span>
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
</div>
</div>
<!-- end of card body -->
</div>
<br>
<div class="addMoreContent" ></div>
<!-- onclick of add more,display the fiels here -->
<button type="button" class="float-right btn btn-outline-dark btn-sm addMoreBtn">Add More</button>
<br>
Related
Can you please tell me how to change the values of divs depending on the select?
And then when the button is clicked, check whether the fields are filled with a certain selected div.
That is, if select is selected with a value of 1, a div with id 1 appears below, and when a button with id btn_save is pressed, it checks whether the field with id user1 is filled.
For select with value 2, a div with id 2 appears below, and when a button with id btn_save is pressed, it checks if the field with id user2 is filled.
Etc.
<select id="selects">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- DIVs -->
<div id="boxes">
<div id="1">
<p>1 ...</p>
<p><input id="user1"></p>
</div>
<div id="2">
<p>4 ...</p>
<input id="user2">
</div>
<div id="3">
<p>3 ...</p>
<input id="user3">
</div>
</div>
<button type="button" id="btn_save">Подтвердить</button>
Here is a version using recommended event listeners
Note I use hidden on each div and I changed the ID from numeric. It is not recommended to have numeric IDs since they cannot be easily accessed by CSS
const divs = document.querySelectorAll("#boxes div");
const save = document.getElementById("btn_save")
document.getElementById("selects").addEventListener("change", function() {
const val = this.value;
divs.forEach(box => box.hidden = box.id !== `d${val}`)
})
save.addEventListener("click", () => {
const visible = [...divs].find(div => !div.hidden);
if (visible && visible.querySelector("input").value.trim() ==="") {
alert("Please enter a value")
}
})
<select id="selects">
<option selected value="">Please select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- DIVs -->
<div id="boxes">
<div id="d1" hidden>
<p>1 ...</p>
<p><input id="user1"></p>
</div>
<div id="d2" hidden>
<p>2 ...</p>
<input id="user2">
</div>
<div id="d3" hidden>
<p>3 ...</p>
<input id="user3">
</div>
</div>
<button type="button" id="btn_save">Подтвердить</button>
//Hide All Divs
$('#boxes').find('div').hide();
$('#btn_save').hide();
//Change div on select
$('#selects').on('change', function() {
$('input').removeClass('active');
$('input').val('');
$('#boxes').find('div').hide();
$('#d' + $(this).val()).show();
$('#btn_save').show();
$('#d' + $(this).val() + ' ' + 'input').addClass('active');
});
//button check input filed or not
$('#btn_save').on('click', function() {
if ($('#' + $('.active').attr('id')).val().trim() == '') {
alert('Please enter a value');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="selects">
<option selected value="">Please select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- DIVs -->
<div id="boxes">
<div id="d1">
<p>1 ...</p>
<p><input id="user1"></p>
</div>
<div id="d2">
<p>2 ...</p>
<input id="user2">
</div>
<div id="d3">
<p>3 ...</p>
<input id="user3">
</div>
</div>
<button type="button" id="btn_save">Save</button>
Value showing in span but I need to get value in the input field.
There will also be Product 3, 4, and so on.
The input field name, price, id, class is being populated dynamically from a database so they are the same for different Items.
If one product exists then it's fine however with multiple products and their options the price for the first ID only changes. As an example, if I change the select from Product 2 then the price of Product 1 changes only. How can I get it to stick to its own Product and change the price for that one only?
$(".readers").change(function() {
var productParent = $(this).parent().parent();
var newPrice = parseFloat(productParent.find('.price').attr('data-price'));
productParent.find(".readers option:selected").each(function() {
newPrice += +$(this).attr('data-price')
});
productParent.find(".price").html("£" + newPrice.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><span data-name="product_name">Addon Product</span></p>
<p data-name="product_desc"> Addon product descriptions</p>
<hr class="line">
<div>
<div class="form-group">
<label>Size: </label>
<select class="product-variants readers form-control input-sm" id="readers" name="product_size">
<option data-price="0" value="Small">Small</option>
<option data-price="40" value="Medium">Medium</option>
<option data-price="60" value="Large">Large</option>
</select>
</div>
<span class="price pull-left" itemprop="price" id="price" data-price="5.99">£5.99</span>
<hr/>
</div>
<div>
<p><span data-name="product_name">2nd Product</span></p>
<p data-name="product_desc">2nd Addon product description</p>
<hr class="line">
<div>
<div class="form-group">
<label>Size: </label>
<select class="product-variants readers form-control input-sm" id="readers" name="product_size">
<option data-price="0" value="Small">Small</option>
<option data-price="40" value="Medium">Medium</option>
<option data-price="60" value="Large">Large</option>
</select>
</div>
<span class="price pull-left" itemprop="price" id="price" data-price="5.99">£5.99</span>
<hr/>
</div>
</div>
Am working on an application whereby I have some cards that have
select dropdown fields. On the Cards I have written a JavaScript
logic whereby if the user selected a wife or husband as an option
on the any of the cards select drop down, any of the other husband
or wife dropdown field should add a CSS class of disabled.
The problem is that the CSS class is not added on other options on the cards which match husband or wife. Basically, I want when the user selects wife or husband option on any card, all other husband or wife options on other cards should change the class to be disabled (which has pointer-vents of none).
My code:
var menus = document.querySelectorAll('.otherMenu');
for (let menu of menus) {
menu.addEventListener('change', function() {
var selectedOption = this.value;
var selectWife = document.querySelectorAll('.otherMenu option[value="Wife"]');
var selectHusband = document.querySelectorAll('.otherMenu option[value="Husband"]');
selectWife.forEach(function(option) {
var change1 = option.classList.add('disabled');
change = selectedOption === 'Wife';
});
selectHusband.forEach(function(option) {
var change2 = option.classList.add('disabled');
change2 = selectedOption === 'Husband';
});
});
}
.disabled {
pointer-events: none;
opacity: 0.5;
color: blue;
}
<!-- Card 1 -->
<form method="POST" action="#" id="phase3">
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Gender -->
<div class="row registerRelationph3">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
<!-- DOb -->
<div class="row">
<label class="fm-input" style="font-size: 10px;"> Date Of Birth :</label>
<input type="text" id="dob" class="fm-inputph3" placeholder="Date of Birth" value="" required>
</div>
<!-- END dob -->
<button class="btn btn-lg" type="submit"> Save Details <i class="fa fa-check-circle" ></i></button>
</form>
<!-- End card 1 -->
<!-- Card 2-->
<form method="POST" action="#" id="phase3">
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Gender -->
<div class="row registerRelationph3">
<label class="fm-input otherMenu"> Relation :</label>
<select class="fm-input" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
<!-- DOb -->
<div class="row">
<label class="fm-input" style="font-size: 10px;"> Date Of Birth :</label>
<input type="text" id="dob" class="fm-inputph3" placeholder="Date of Birth" value="" required>
</div>
<!-- END dob -->
<button class="btn btn-lg" type="submit"> Save Details <i class="fa fa-check-circle" ></i></button>
</form>
<!-- End card 2-->
<!-- Card 3-->
<form method="POST" action="#" id="phase3">
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Gender -->
<div class="row registerRelationph3">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
<!-- DOb -->
<div class="row">
<label class="fm-input" style="font-size: 10px;"> Date Of Birth :</label>
<input type="text" id="dob" class="fm-inputph3" placeholder="Date of Birth" value="" required>
</div>
<!-- END dob -->
<button class="btn btn-lg" type="submit"> Save Details <i class="fa fa-check-circle" ></i></button>
</form>
<!-- End card 3-->
As per the linked question from Maaz, you cannot style an individual option element (except for color/background-color). However for this use case you don't need to, option has a disabled property which does what you want: Disables selecting and fades the option.
Javascript:
var menus = document.querySelectorAll('.otherMenu');
for (let menu of menus) {
menu.addEventListener('change', function() {
var selectedOption = this.value;
var thisMenu = this;
var selectWife = document.querySelectorAll('.otherMenu option[value="Wife"]');
var selectHusband = document.querySelectorAll('.otherMenu option[value="Husband"]');
selectWife.forEach(function(option) {
if(!(thisMenu === option.parentNode)){
if(selectedOption === 'Wife'){
option.disabled = true;
}
}
});
selectHusband.forEach(function(option) {
if(!(thisMenu === option.parentNode)){
if(selectedOption === 'Husband'){
option.disabled = true;
}
}
});
});
}
CSS:
.other-menu option:disabled {
color: blue;
}
Notes: you have otherMenu class incorrectly assigned incorrectly placed in your HTML, and I'd recommend having a placeholder value before a selection is made, as in this JSFiddle:
I have a dropdown menu where list is selected from mysql database and a textbox contain datepicker. How can i display value selected from the dropdown menu and datepicker on every click on add button? The code can add div dynamically onclick on add button but the value selected to be displayed in the div are changed on every selected dropdown menu because of the javascript onchange function.
How can i display the value correctly?
$( ".js-datepicker" ).datepicker();
$("#choose_exam").on("change", function() {
var selected = $(this).val();
$("#exam").html("" + selected);
});
$("#t_exam").on("change", function() {
var selected = $(this).val();
$("#exam_date").html("" + selected);
})
//contents of the div added after clicking on add button in the form
$(".add-more").click(function() {
var html = $("#copy-fields").html();
$("#validation-step2").append(html);
$('.js-datepicker').datepicker('update');
});
//remove button
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- This is the form contain dropdown menu and datepicker textbox -->
<div class="tab-pane push-30-t push-50" id="validation-step2">
<div class="form-group">
<select class="form-control" name="choose_exam[]" id="choose_exam">
<!--<?php
$sql = "Select name from exam_list order by id asc";
$result = mysql_query( $sql );
while(list($category) = mysql_fetch_row($result)){
$option = '<option value="'.$category.'">'.$category.'</option>';
echo ($option);}
?>-->
<option value="0">Please choose</option>
<option value="1">Sample Category 1</option>
<option value="2">Sample Category 2</option>
<option value="3">Sample Category 3</option>
<option value="4">Sample Category 4</option>
<option value="5">Sample Category 5</option>
</select>
<label for="choose_exam">Exam List</label>
</div>
<div class="form-group">
<input class="js-datepicker form-control" type="text" name="t_exam" id="t_exam" data-date-format="dd/mm/yyyy">
<label for="t_exam">Date</label>
</div>
<div class="form-group">
<button class="btn btn-default add-more pull-right" type="button">Add</button>
</div>
<!-- This is for dynamically add every div contains exam and date value upon clicking add button -->
<div class="copy-fields hide" id="copy-fields">
<div class="control-group">
<div class="form-group">
<div id="exam" name="exam[]"></div>
<div id="exam_date" name="exam_date[]"></div>
</div>
<div class="form-group">
<button class="btn btn-default remove pull-right" type="button">Delete</button>
</div>
</div>
</div>
Your code has several problems:
The HTML you're copying using var html = $("#copy-fields").html(); contains elements with the id attribute specified, which will lead you to having a bunch of elements with the same id. Turn #exam to .exam and #exam_date to .exam_date to fix that.
Then, inside the change event, use first() or last(), so that only the first or the last of .exam and .exam_date change when the event is triggered. In the first snippet, I use last() as in $(".exam").last().html(this.value);.
The line $(".js-datepicker").datepicker("update"); throws an error, perhaps because you haven't set which date to update to. In the snippets below, I assume you want to reset it.
Snippet 1:
(This snippet follows your code as much as possible including a live update of the data 'onchange'.)
/* ----- JavaScript ----- */
/* Initialise the datepicker. */
$(".js-datepicker").datepicker();
/* Set the 'change' event. */
$("#choose_exam").on("change", function() {
$(".exam").last().html(this.value);
});
$("#t_exam").on("change", function() {
$(".exam_date").last().html(this.value);
})
/* Insert the given data to the DOM. */
$(".add-more").click(function() {
/* Cache the innerHTML of the '#copy-fields'. */
var html = $("#copy-fields").html();
/* Insert it as last inside '#validation-step2'. */
$("#validation-step2").append(html);
/* Reset the 'select' element and the date picker. */
$("#choose_exam").val(0);
$(".js-datepicker").val("");
});
/* Remove the saved data when the remove button is clicked. */
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="tab-pane push-30-t push-50" id="validation-step2">
<div class="form-group">
<select class="form-control" name="choose_exam[]" id="choose_exam">
<option value="0">Please choose</option>
<option value="1">Sample Category 1</option>
<option value="2">Sample Category 2</option>
<option value="3">Sample Category 3</option>
<option value="4">Sample Category 4</option>
<option value="5">Sample Category 5</option>
</select>
<label for="choose_exam">Exam List</label>
</div>
<div class="form-group">
<input class="js-datepicker form-control" type="text" name="t_exam"
id="t_exam" data-date-format="dd/mm/yyyy">
<label for="t_exam">Date</label>
</div>
<div class="form-group">
<button class="btn btn-default add-more pull-right" type="button">Add</button>
</div>
<!-- This is for dynamically add every div contains exam and date
value upon clicking add button -->
<div class="copy-fields hide" id="copy-fields">
<div class="control-group">
<div class="form-group">
<div class="exam" name="exam[]"></div>
<div class="exam_date" name="exam_date[]"></div>
</div>
<div class="form-group">
<button class="btn btn-default remove pull-right" type="button">Delete</button>
</div>
</div>
</div>
</div>
Snippet 2:
(This snippet presents an alternate approach using a template to add the data to the DOM.)
/* ----- JavaScript ----- */
/* Create a template. */
var template = `
<div class="control-group">
<div class="form-group">
<div class="exam" name="exam[]">[_EXAM_]</div>
<div class="exam_date" name="exam_date[]">[_DATE_]</div>
</div>
<div class="form-group">
<button class="btn btn-default remove pull-right" type="button">Delete</button>
</div>
</div>
`;
/* Initialise the datepicker. */
$(".js-datepicker").datepicker();
/* Insert the given data to the DOM. */
$(".add-more").click(function() {
/* Cache the data. */
var
exam = $("#choose_exam").val(),
date = $("#t_exam").val(),
editedTemplate = template.replace("[_EXAM_]", exam).replace("[_DATE_]", date);
/* Insert it as last inside '#validation-step2'. */
$("#validation-step2").append(editedTemplate);
/* Reset the 'select' element and the date picker. */
$("#choose_exam").val(0);
$(".js-datepicker").val("");
});
/* Remove the saved data when the remove button is clicked. */
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
<!----- HTML ----->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="tab-pane push-30-t push-50" id="validation-step2">
<div class="form-group">
<select class="form-control" name="choose_exam[]" id="choose_exam">
<option value="0">Please choose</option>
<option value="1">Sample Category 1</option>
<option value="2">Sample Category 2</option>
<option value="3">Sample Category 3</option>
<option value="4">Sample Category 4</option>
<option value="5">Sample Category 5</option>
</select>
<label for="choose_exam">Exam List</label>
</div>
<div class="form-group">
<input class="js-datepicker form-control" type="text" name="t_exam"
id="t_exam" data-date-format="dd/mm/yyyy">
<label for="t_exam">Date</label>
</div>
<div class="form-group">
<button class="btn btn-default add-more pull-right" type="button">Add</button>
</div>
</div>
So i prefer to discuss about your question under this answer, because i still feel something is wrong, it's not clear to me what you want to do exactly, but here is you can get #t_exam and #choose_exam value after click on add button. Also it dynamically add selected values to your html but with a little changes.
$(".js-datepicker").datepicker();
$(".add-more").click(function() {
var selectedExam = $('#choose_exam option:selected').val();
var selectedDate = $('#t_exam').val();
var html = '<div class="control-group">'+
'<div class="form-group">'+
'<div class="exam" name="exam[]">'+selectedExam+'</div>'+
'<div class="exam_date" name="exam_date[]">'+selectedDate+'</div></div>'+
'<div class="form-group">'+
'<button class="btn btn-default remove pull-right" type="button">Delete</button>'+
'</div></div>'
;
$("#copy-fields").append(html);
// $('.js-datepicker').datepicker('update');
});
//remove button
$("body").on("click", ".remove", function() {
$(this).parents(".control-group").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- This is the form contain dropdown menu and datepicker textbox -->
<div class="tab-pane push-30-t push-50" id="validation-step2">
<div class="form-group">
<select class="form-control" name="choose_exam[]" id="choose_exam">
<!--<?php
$sql = "Select name from exam_list order by id asc";
$result = mysql_query( $sql );
while(list($category) = mysql_fetch_row($result)){
$option = '<option value="'.$category.'">'.$category.'</option>';
echo ($option);}
?>-->
<option value="0">Please choose</option>
<option value="1">Sample Category 1</option>
<option value="2">Sample Category 2</option>
<option value="3">Sample Category 3</option>
<option value="4">Sample Category 4</option>
<option value="5">Sample Category 5</option>
</select>
<label for="choose_exam">Exam List</label>
</div>
<div class="form-group">
<input class="js-datepicker form-control" type="text" name="t_exam" id="t_exam" data-date-format="dd/mm/yyyy">
<label for="t_exam">Date</label>
</div>
<div class="form-group">
<button class="btn btn-default add-more pull-right" type="button">Add</button>
</div>
<!-- This is for dynamically add every div contains exam and date value upon clicking add button -->
<div class="copy-fields hide" id="copy-fields"></div>
I have three cascading select lists. When I try to reset them with this code:
function resetSearch(advancedSearch){
document.getElementById("advancedSearch").reset();
submitQuery();
};
It resets the select lists, but because the select lists are cascading, so one depends on another to fill the select list with the correct values, it sets the values of the lists that are selected at that moment to the default.
So in my case I have three selectlists, one for the table names, one for the field names and one for the attributes. When I select a table it gives me the matching column names and attributes. If I than push teh reset button, it resets the table name to default, but the fieldnames and attribute select lists are set to the default of the other table.
Here is a picture to clarify my question:
This is my form with the select lists in it and the reset button;
<form action="javascript:submitQuery()" id="advancedSearch">
<!-- Search by name input field -->
<div class="form-group">
<div id= "selectListContent">
<div class="row">
<div id="content-a">
<div class='content-row'>
<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>
<div class="select_column col-md-6">
<label for="invoerColumnNaam">Select column:</label>
<span>
<select class="form-control" name="column_names" id="slctField">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="select_attribute col-md-9">
<label for="invoerAttribuutNaam">Select attribute:</label>
<span>
<select class="form-control" name="attribute_names" id="slctAttribute">
</select>
</span>
</div>
</div>
</div>
</div>
<!-- Buttons search en reset voor tab advanced search -->
<div class="form-group">
<div class="col-md-6">
<button type="reset" class="btn btn-block btn-primary" onclick="resetSearch()">
<span class="glyphicon glyphicon-repeat" aria-hidden="true"></span>   Reset
</button>
</div>
</div>
</div>
I assume that you have some event which populates other selects when value in first select is chosen. In that case you need to trigger it after form is reset.
For e.g.:
function resetSearch() {
$('#slctTable').closest('form')[0].reset();
$('#slctTable').trigger('change');
}
To clarify: how reset could 'know' that for 'table 1' correct list of fields is 'field1' and 'field2' and for 'table 2' it is 'other1' and 'other2'? It can just set selection to first items of lists.
var data = {
'table1': {
'tab1_column1': ['tab1_col1_attr_1', 'tab1_col1_attr_2'],
'tab1_column2': ['tab1_col2_attr_1', 'tab1_col2_attr_2']
},
'table2': {
'tab2_column1': ['tab2_col1_attr_1', 'tab2_col1_attr_2'],
'tab2_column2': ['tab2_col2_attr_1', 'tab2_col2_attr_2']
}
}
function resetSearch() {
$('#slctTable').closest('form')[0].reset();
$('#slctTable').trigger('change');
}
$(function() {
var table = $('#slctTable'),
field = $('#slctField'),
attr = $('#slctAttribute');
table.on('change', function() {
field.html('').val('');
$.each(data[$(this).val()], function(k, v) {
field.append($("<option />").val(k).text(k))
});
field.trigger('change');
});
field.on('change', function() {
attr.html('').val('');
$.each(data[table.val()][$(this).val()], function(k, v) {
attr.append($("<option />").val(v).text(v))
});
});
$.each(data, function(k, val) {
table.append($("<option />").val(k).text(k))
});
//populate fields for the first time
table.trigger('change');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="javascript:submitQuery()" id="advancedSearch">
<!-- Search by name input field -->
<div class="form-group">
<div id="selectListContent">
<div class="row">
<div id="content-a">
<div class='content-row'>
<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>
<div class="select_column col-md-6">
<label for="invoerColumnNaam">Select column:</label>
<span>
<select class="form-control" name="column_names" id="slctField">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="select_attribute col-md-9">
<label for="invoerAttribuutNaam">Select attribute:</label>
<span>
<select class="form-control" name="attribute_names" id="slctAttribute">
</select>
</span>
</div>
</div>
</div>
</div>
<!-- Buttons search en reset voor tab advanced search -->
<div class="form-group">
<div class="col-md-6">
<button type="reset" class="btn btn-block btn-primary" onclick="resetSearch()">
<span class="glyphicon glyphicon-repeat" aria-hidden="true"></span>   Reset
</button>
</div>
</div>
function resetSearch(advancedSearch){
change for this:
function resetSearch(){
I have create from your initial HTML and description this Codepen with cascading population of field. I do not see your problem. Could you provide more explaination or to say if this resolve your problem?
Codepen: http://codepen.io/anon/pen/ezmErd
HTML
<form class="container" action="javascript:submitQuery()" id="advancedSearch">
<div class="form-group">
<div id="selectListContent">
<div class="row">
<div id="content-a">
<div class='content-row'>
<div class="select_table col-md-6">
<label for="invoerTabelNaam">Select table:</label>
<span>
<select class="form-control" name="table_names" id="slctTable">
</select>
</span>
</div>
<div class="select_column col-md-6">
<label for="invoerColumnNaam">Select column:</label>
<span>
<select class="form-control" name="column_names" id="slctField">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="select_attribute col-md-9">
<label for="invoerAttribuutNaam">Select attribute:</label>
<span>
<select class="form-control" name="attribute_names" id="slctAttribute">
</select>
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-3">
<button type="reset" class="btn btn-block btn-primary" onclick="resetSearch('advancedSearch')">
<span class="glyphicon glyphicon-repeat" aria-hidden="true"></span>   Reset
</button>
</div>
</div>
</form>
JS
var table = document.getElementById("slctTable"),
field = document.getElementById("slctField"),
attrib = document.getElementById("slctAttribute"),
populate = function (dropdown, name) {
for (var i = 0, temp; i < 4; i++) {
temp = document.createElement("option")
temp.value = i + 1;
temp.textContent = name + " " + +(i + 1);
dropdown.appendChild(temp);
}
},
submitQuery = function () {
console.log("Submit !");
},
resetSearch = function (advancedSearch) {
document.getElementById(advancedSearch).reset();
submitQuery();
};
// Populate dynamicly the first Dropdown.
populate(table, "Table");
// When you select an item of first Dropdown...
table.addEventListener("change", function() {
field.innerHTML = "";
// ...populate dynamicly the second Dropdown.
populate(field, "Field");
});
// When you select an item of second Dropdown...
field.addEventListener("change", function() {
attrib.innerHTML = "";
// ...populate dynamicly the last Dropdown.
populate(attrib, "Attribute");
});