Matching two ID attributes from cloned dependent dropdown list - html

In this code I have 2 dependent dropdown lists and a button to duplicate/clone the form. The color selection changes based on what is selected in item. When I duplicate the dropdown list the function didn't work. I tried changing the id of the duplicated dropdown list but still can't manage to match the id of 2 dropdown list. Is there any solution? Thanks.
var count = 1;
var duplicate_div = document.getElementById('duplicate_1');
function addRecord() {
var clone = duplicate_div.cloneNode(true);
clone.id = "duplicate_" + ++count;
duplicate_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0];
$(clone).find("*[id]").each(function() {
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength - 1], count);
$(this).attr('id', newId);
});
}
$(document).ready(function() {
$("#item_" + count).change(function() {
var val = $(this).val();
if (val == "shirt") {
$("#color_" + count).html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$("#color_" + count).html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$("#color_" + count).html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate" id="duplicate_1">
<br>
<label>item</label>
<select id="item_1">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select id="color_1">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button" onclick="addRecord()">add</button>

Since you've imported jQuery into the project, I suggest you fully use it.
It's recommended to use jQuery's .on method instead of onclick attribute.
The change event will not work on the dynamically created elements.
You should instead use "event delegation".
Last but not least, you can remove the ids if they serve as selectors. You can use jQuery to easily transverse the DOM
Try this
$(document).ready(function() {
var $cloned = $('.duplicate').first().clone(true);
var $container = $('.select-form');
$('#add-button').click(function() {
$container.append($cloned.clone());
})
$('.select-form').on('change', '.item', function() {
var val = $(this).val();
var $color = $(this).closest('.duplicate').find('.color');
if (val == "shirt") {
$color.html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$color.html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$color.html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate">
<br>
<label>item</label>
<select class="item">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select class="color">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button">add</button>

Related

Jquery check if multiple drop down list has any selected option

I am trying to display in console a message when a user removes all options from a multiple drop down list. My current code creates a JSON object when there are options selected and encodes the items into a URI string component.
How can I display a message when the user removes all selected options?
<div class="form-group row">
<label class="col-sm-3 col-form-label">Customer</label>
<div class="col-sm-9">
<select id="Customers" class="js-select2-custom custom-select" name="CustomerID" multiple size="1" style="opacity: 0;" asp-for="CustomerID" onchange="getSelects()"
data-hs-select2-options='{
"minimumResultsForSearch": "Infinity"
}'>
#{
var selectedCustomer = Model.CustomerList.Where(x => Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID));
var Customers = Model.CustomerList.Where(x => !Model.SelectedCustomers.Any(c => c.CustomerID == x.CustomerID));
}
#foreach (var item in selectedCustomer)
{
<option value="#item.CustomerID" selected>#item.CustomerName</option>
}
#foreach (var item in Customers)
{
<option value="#item.CustomerID">#item.CustomerName</option>
}
</select>
</div>
</div>
function getSelects() {
$('#selectedText').val('');
var items = $("#Customers > option:selected").map(function () {
var opt = {};
$('#Customers > option:selected').each(function() {
if ($(this).not(':selected')) {
alert('Yes')
}
});
return opt;
}).get();
$('#selectedText').val(encodeURIComponent(JSON.stringify(items)));
console.log($('#selectedText').val());
}
How about something like this? Press and hold the "Ctrl" key to select/deselect multiple:
$('#cars').change(function(){
// get selected values:
var values = $(this).val();
console.log('selected values: ', values);
// send alert if none are selected:
if (!values.length) alert('No values selected!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

How to remove attr 'select' from dropdown list options that is repopulate with ajax request

I made a form that has a chained dropdown lists. Each subsequent dropdown list will be repopulated with ajax request based on the first dropdown list selection. In each dropdown list the first selected field is "---------" which has the attribution selected. When user selects another option the previous selected option still has the attribute of "selected". What I want to achieve is that the new selected option will be the one which has the selected attribute.
I have tried the .removeProp('selected', false)
and .removeAttr('selected') but the problem is persisting.
Here is the HTML Code:
<div id="div_id_CommonForm-country" class="form-group">
<label for="id_CommonForm-country" class=" requiredField">
country :
<span class="asteriskField">*</span>
</label>
<div class="">
<select name="CommonForm-country" class="select form-control" required="" id="id_CommonForm-country">
<option value="" selected="">---------</option>
<option value="1">USA </option>
<option value="5">Canada</option>
</select>
</div>
Here is the ajax request:
<script type="text/javascript">
$("#id_CommonForm-country").change(function(){
var url_province = $("#ads_main_post_form").attr("data-provinces-url"); // get the url of the `load_provinces` view
var countryId = $(this).val(); // get the selected country ID from the HTML input
$("#id_CommonForm-country option:selected").each(function () {
$(this).attr('selected', '');
});
var value = $(this).val();
$(this).find('option[value="'+value+'"]').attr("selected", "selected");
$.ajax({ // initialize an AJAX request
url: url_province, // set the url of the request (= localhost:8000/twons/ajax/load-rovinces/)
data: {
'user_country': countryId, // add the country id to the GET parameters
csrfmiddlewaretoken: '{{csrf_token}}',
},
success: function (data) { // `data` is the return of the `load_provinces` view function
var json = JSON.parse(data);
var provinces_list = $("#id_CommonForm-province").html('');
var city_list = $("#id_CommonForm-city").html('');
city_list.append('<option selected disabled>'+'---------'+ '</option>');
var first_item =
'<option selected disabled>'+'---------'+ '</option>';
var list=""
for(var j = 0; j < json.province_id.length; j++) {
list+=
'<option value="'+json.province_id[j]+'">'+json.province_name[j]+'</option>';
// replace the contents of the province input with the data that came from the server
}
complete_list = first_item.concat(list);
provinces_list.append(complete_list);
}
});
});
Any help or suggestion is highly appreciated:
Note: I have tried many suggested solutions posted on stackover flow but nothing helpt.
You can simply use removeAttr('selected'); to remove selected and then use attr("selected", "selected"); to add option selected to only to choosen option.
Demo code :
$("#id_CommonForm-country").change(function() {
var url_province = $("#ads_main_post_form").attr("data-provinces-url");
var countryId = $(this).val();
$("#id_CommonForm-country option").removeAttr('selected'); //remove attr selected
$(this).find('option[value="' + countryId + '"]').attr("selected", "selected"); //add selected to option actual selected
console.log(countryId)
//your ajax call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_id_CommonForm-country" class="form-group">
<label for="id_CommonForm-country" class=" requiredField">
country :
<span class="asteriskField">*</span>
</label>
<div class="">
<select name="CommonForm-country" class="select form-control" required="" id="id_CommonForm-country">
<option value="" selected>---------</option>
<option value="1">USA </option>
<option value="5">Canada</option>
</select>
</div>

show selected option value info to other select tag [duplicate]

i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<select class="select" id="city" disabled>
<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>
this one is not visible, and acts as a container for all the elements filtered out by the selection:
<span id="option-container" style="visibility: hidden; position:absolute;"></span>
Finally, the script that filters:
<script>
function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip
It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle.
//Get html elements
var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
Fiddle Demo
I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
</script>
</head>
<body>1
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Japn</option>
<option>Shuidong</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
</body>
</html>
This is an example that I've done. I wish that will be useful for you.
$(document).ready(function(){
var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);
function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {
if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}
$("#cycles").change(function(){
remplirListNiveau(this.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>

How to make span class for drop down list required?

<a class="btn btn-info btn-select btn-select-light">
<input type="hidden" class="btn-select-input" id="" name="shopcollection"
value="" required="required"/>
<span class="btn-select-value">Select Shop</span>
<span class='btn-select-arrow glyphicon glyphicon-chevron-down'
required="required"></span>
<ul>
<li>example1</li>
<li>example2</li>
<li>example3</li>
</ul>
</a>
$(document).ready(function () {
$(".btn-select").each(function (e) {
var value = $(this).find("ul li.selected").html();
if (value != undefined) {
$(this).find(".btn-select-input").val(value);
$(this).find(".btn-select-value").html(value);
}
});
});
$(document).on('click', '.btn-select', function (e) {
e.preventDefault();
var ul = $(this).find("ul");
if ($(this).hasClass("active")) {
if (ul.find("li").is(e.target)) {
var target = $(e.target);
target.addClass("selected").siblings().removeClass("selected");
var value = target.html();
$(this).find(".btn-select-input").val(value);
$(this).find(".btn-select-value").html(value);
}
ul.hide();
$(this).removeClass("active");
}
else {
$('.btn-select').not(this).each(function () {
$(this).removeClass("active").find("ul").hide();
});
ul.slideDown(300);
$(this).addClass("active");
}
});
$(document).on('click', function (e) {
var target = $(e.target).closest(".btn-select");
if (!target.length) {
$(".btn-select").removeClass("active").find("ul").hide();
}
});
I am trying to make it so the user has to select one of the elements (example1) however my required code does not work so the user can bypass the drop down list. I have include the drop down code (top section) and the drop down javascript file (bottom section), any tips?
You are going to need to use a select to conform to your need:
<select required>
<option value="">None</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Further reading: https://www.w3schools.com/tags/att_select_required.asp

Get value from dropdownlist and create another dropdown list

I have created a dropdownlist and it looks like this
<select id="mySelect">
<option value="one">Do one</option>
<option value="two">Do two</option>
</select>
Firstly I would like NOT to have a submit button. The second thing I was searching is that when I select the first choice to appear another dropdown list and when i choose the second to appear a text input for the user to type something. Thank you and sorry for the English!
If you do not want to import any jQuery you can still do it with pure JavaScript.
Here is a demo
Just include the below script in your file as,
function myFun(){
var val = document.getElementById("mySelect");
var input = document.getElementById("myIn");
var sel = document.getElementById("myOtherSelect");
var sub = document.getElementById("mySubmit");
if(val.value == "one"){
sel.style.display = "block";
input.style.display = "none";
sub.style.display = "none";
}else if(val.value == "two"){
input.style.display = "block";
sub.style.display = "block";
sel.style.display = "none";
}else{
input.style.display = "none";
sub.style.display = "block";
sel.style.display = "none";
}
}
Now add the onchange event on your select as,
<select id="mySelect" onchange="myFun()">
<option value="emp" selected>Choose something</option>
<option value="one">Do one</option>
<option value="two">Do two</option>
</select>
<select id="myOtherSelect">
<option value="three">Do three</option>
<option value="four">Do four</option>
</select>
<input type="text" id="myIn">
<input type="submit" id="mySubmit">
Use jQuery to do something simple like:
$('#mySelect').on('change', function() {
$('#input').html('<input name="myname" value="'+this.value +'">');
})
JSFiddle