First Dropdown Changes Second Dropdown Related Item display - javascript

Hi I have two dropdowns in my Html when I select my dropdown. my second dropdown needs to change related items.
My dropdown one has two item Domestic, international
second dropdown has three item INR, USD, EUR
When I change my first dropdown Domestic item selected need to display in my second dropdown INR Item only display other item need to hide.
Then I select an international item in my first dropdown that needs to display in my second dropdown USD, and EUR currency only displays. how to achieve it. (using jquery or javascript). My code below here.
<div class="input-group input-group-sm">
<select id="OrderType" asp-for="Type" title="Mode" class="form-control form-control-sm border selectpicker" onchange="GetCurrencybyType(this)">
<option id="DomId" value="1" selected>Domestic</option>
<option id="InterId" value="2">International</option>
</select>
</div>
<div class="input-group input-group-sm">
<select id="CurrencyType" asp-for="Currency" title="Mode" class="form-control form-control-sm border selectpicker">
<option id="InrId" value="1" selected>INR</option>
<option id="UsdId" value="2">USD</option>
<option id="EurId" value="2">EUR</option>
</select>
</div>
My Jquery function
function GetCurrencybyType(id) {
var value = id.value;
if (value == 2) {
$('#mySelect').children().remove().end()
.append('<option selected value="USD">USD</option>');
}
else {
$("option[value='2']").remove();
$('select[id=CurrencyType]').val('<option value="' + id.val + '">' + "INR" + '</option>');
}
//var value = id.value;
//var selectedCountry = $(this).children("option:selected").val();
//alert("You have selected the country - " + value);
//var InrIdValue = $("#InrId").val();
//if (value == "Domestic") {
// $("#CurrencyType").html("");
// var result = $("#CurrencyType").html("");
// alert(result);
// $("#CurrencyType").append($("<option />").val(InrIdValue).text(InrIdValue));
// var result1 = $("#CurrencyType").append($("<option />").val(InrIdValue).text(InrIdValue));
// alert(result1);
// //$('select[id=CurrencyType]').val(InrIdValue);
// //var result = $('select[id=CurrencyType]').val(InrIdValue);
// //alert(result);
// //$('select[id=CurrencyType]').val('<option value="' + InrIdValue + '">' + InrIdValue + '</option>');
//}
//else {
// alert("International");
//}
}
i not getting correct value in my UI please answer me.

Here is a working demo you could follow:
<div class="input-group input-group-sm">
<select id="OrderType" title="Mode" class="form-control form-control-sm border selectpicker" >
<option id="DomId" value="1">Domestic</option>
<option id="InterId" value="2">International</option>
</select>
</div>
<div class="input-group input-group-sm">
<select id="CurrencyType" title="Mode" class="form-control form-control-sm border selectpicker">
<option value="" selected>Select A Currency</option>
</select>
</div>
#section Scripts
{
<script>
$(function () {
var subjectObject = {
"1": [
"INR"
],
"2": [
"USD",
"EUR"
]
};
$('#OrderType').change(function () {
var OrderType = $(this).val()
var CurrencyType = subjectObject[OrderType] || [];
var html = $.map(CurrencyType, function (cnt) {
return '<option value="' + OrderType + '">' + cnt + '</option>'
}).join('');
$('#CurrencyType').html(html)
});
})
</script>
}
A JSFiddle you could check: https://jsfiddle.net/b6pe3vxq/

Related

Update Array with dynamically generated values

I'm very new to JavaScript, so I'm having a hard time with this relatively simple problem:
I wrote a function that dynamically adds or removes dropdown fields to the DOM if the user clicks the add or remove button. So far so good, everything is working fine until here.
Now I want to collect the data in an Array to send it to the api.
With the following code I can collect it, but I have a hard time to figure out how I can remove specific values from the array.
<div class="container mt-2" id="stores">
<div class="row">
<div class="col">
<h2>Marktet</h2>
<div class="col-form-label storesHint">Select at least one market</div>
</div>
</div>
<div id="form">
<div>
<div id="addAnotherMarket">
<div class="marketRow">
<select class="form-control" id="market" name="market">
<option value="1"> market1</option>
<option value="2"> market2</option>
<option value="3"> market3</option>
<option value="4"> market4</option>
<option value="5"> market5</option>
</select>
<input class="deleteButton" type="button" id="remove" value="" style="display: none; font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;">
</div>
</div>
</div>
</div>
<div>
<div class="addBtnContainer">
<div class="centerBtn">
<a class=" button btn_gray buttonWithIcon" id="add">
<i class=" fa fa-plus icn" id="btnIcon" style="font-size: 16px;" aria-hidden="true"></i>
<span class="btnText spn" style="top:0px !important">Add another market</span>
</a>
</div>
</div>
</div>
</div>
$(document).ready(function () {
let index = 0;
let store = {};
let stores = [];
var oldValue = [];
window.Stores = stores;
//set initial value for the first dropdown element
store = { "store_id": parseInt($('#market').val(), 10) };
stores.push(store);
oldValue[index] = store;
//update value if user changes first element
$('#market').on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add a new dropwdown element
$("#add").click(function () {
index++;
$(this).parent().parent().before($("#form").clone().attr("id", "form" + index));
$("#form" + index + " :input").each(function () {
$(this).attr("name", $(this).attr("name") + index);
$(this).attr("id", $(this).attr("id") + index);
});
//set initial value of the new dropdown element
store = { "store_id": parseInt($('#market' + index).val(), 10) };
stores.push(store);
oldValue[index] = store;
//set new value if user changes value
$('#market' + index).on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add remove button
$("#remove" + index).css("display", "inline-flex");
$(".marketRow").css({
'display': 'flex',
'align-items': 'center',
'margin-top': '5px'
});
//if user clicks remove button delete value from array
$("#remove" + index).click(function () {
var eleIndex = stores.indexOf({ "store_id": parseInt($('#market' + index).val(), 10) });
if (index !== -1) {
stores.splice(eleIndex, 1);
oldValue.splice(eleIndex);
}
$(this).closest("div").remove();
});
});
});
The following code also outputs -1 always, so I think indexOf makes no sense.
var eleIndex = stores.indexOf({"store_id": parseInt($('#market' + index).val(), 10)});
EDIT: I updated the post with the HTML part as requested. In short: When clicking on button(#add) div(#form) will be cloned, remove button will be added, and id's will be updated with index.
Values of all these selects will be stored and updated in the stores array. I just can't delete them.
I have also provided a working jsfiddel https://jsfiddle.net/proach1995/h1gtmyen/
With plain js you can add class to the dropdown you wish to collect from. in the code below it will build the array only if value was selected.
if you use jQuery you can replace document.querySelectorAll('.store'); with $('.store');
function saveArray() {
const selected = document.querySelectorAll('.store');
const stores = [];
selected.forEach(prop => {
if (!!prop.value) {
stores.push({store_id: parseInt(prop.value, 10)})
}
});
console.log(stores);
}
<select class="store">
<option disabled selected value>select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<button onclick="saveArray()">save array</button>

Dependent Dropdown select - How to get "names" of city instead of the "id" into submit?

I'm having a problem upon changing the code below "${region.code}" into "${region.name}"
regOpt += `<option value='${region.code}'> ${region.altName}</option>`;
What I want is to get the names of the region instead of the value on submit form but the problem is when I change the value into name I'm getting errors and the 2nd & 3rd dropdown won't show. probably because I'm using multiple JSON file and it filter the values to connect the files.
JS
$(function(){
let regOpt = "";
let provOption = "";
let cityOption = "";
//FOR REGION
$.getJSON('regions.json', function(result){
regOpt += `<option value="" disabled selected hidden>Region</option>`;
$.each(result.sort(), function(i, region){
regOpt += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regOpt);
});
//FOR PROVINCE
$('#region').change(function(){
let values = $(this).val();
$.getJSON('provinces.json', function(result){
let items = $(result).filter(function(i, n){
return n.region === values;
});
provOption += `<option value="" disabled selected hidden>Province</option>`;
//loop through dates
$.each(items, function(region, province){
provOption += `<option value='${province.code}'> ${province.name}</option>`;
});
$('#province').html(provOption);
});
});
//FOR CITY
$('#province').change(function(){
let values = $(this).val();
$.getJSON('citiesMunicipalities.json', function(result){
let items = $(result).filter(function(i, n){
return n.province === values;
});
cityOption += `<option value="" disabled selected hidden>City</option>`;
$.each(items, function(province, city){
cityOption += `<option value='${city.code}'> ${city.name}</option>`;
});
$('#city').html(cityOption);
});
});
});
</script>
HTML code
<div class="container form-group">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region">
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province">
<option value=""> Select Province</option>
</select>
</div>
<div class="form-group">
<select name="city" id="city">
<option value="">City</option>
</select>
</div>
<div class="form-group">
<button type="submit" form="addform" value="Submit">Submit</button>
</div>
</form>
</div>
JSON files i'm using is here
You can store value of region code as data-attribute . So, whenever your region dropdown gets changed get value of this data attribute using $(this).find('option:selected').data("code"); and then pass same to your filter method .
Demo Code :
//this is for demo
var regions = [{
"code": "130000000",
"name": "National Capital Region",
"altName": "NCR"
},
{
"code": "140000000",
"name": "Cordillera Administrative Region",
"altName": "CAR"
}
]
var provinces = [{
"code": "130100000",
"name": "Ab",
"altName": null,
"region": "130000000"
},
{
"code": "140100000",
"name": "Cd",
"altName": null,
"region": "140000000"
},
{
"code": "142700000",
"name": "Mn",
"altName": null,
"region": "140000000"
}
]
$(function() {
var regOpt = "";
//FOR REGION
/*$.getJSON('regions.json', function(result) {*/
regOpt += `<option value="" disabled selected hidden>Region</option>`;
$.each(regions.sort(), function(i, region) {
//use data attr here..
regOpt += `<option data-code ='${region.code}' value='${region.name}'> ${region.altName}</option>`;
});
$('#region').html(regOpt);
/* });*/
//FOR PROVINCE
$('#region').change(function() {
var provOption = "";
//get data attribute values..
let values = $(this).find('option:selected').data("code");
console.log(values)
/*$.getJSON('provinces.json', function(result) {*/
let items = $(provinces).filter(function(i, n) {
return n.region === $.trim(values);
});
provOption += `<option value="" disabled selected hidden>Province</option>`;
//loop through dates
$.each(items, function(region, province) {
provOption += `<option value='${province.code}'> ${province.name}</option>`;
});
$('#province').html(provOption);
/*});*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container form-group">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region">
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province">
<option value=""> Select Province</option>
</select>
</div>
<div class="form-group">
<select name="city" id="city">
<option value="">City</option>
</select>
</div>
<div class="form-group">
<button type="submit" form="addform" value="Submit">Submit</button>
</div>
</form>
</div>

Making text input invisible but tangible

I am working on a country dropdown filter for a search. This will allow users to search within the selected region.
Select 'Thailand' from the dropdown, 'Thailand + ' will be pushed to the search box which allows user to enter another keyword (e.g. Food) which forms into
'Thailand + Food'.
Due to technical constraints this is my only workaround creating a search filter. I am wondering can i make the selected region text invisible (Thailand +) yet when i press enter.. 'Thailand +' is part of the search results.
What i want to achieve:
User selects 'Thailand'
Thailand +' is pushed to textbox (Not visible to user)**
User types 'Food' in the search box
Both 'Thailand + Food' is in the search result
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testfloat">
<select id="quantity">
<option selected>Select Libraries</option>
<option value="Albanian + ">Albanian</option>
<option value="Singapore + ">Singapore</option>
<option value="Malaysia + ">Malaysia</option>
<option value="Germany + ">Germany</option>
<option value="France + ">France</option>
<option value="Thailand + ">Thailand</option>
</select>
<script type="text/javascript">
$('#quantity').change(function(){
var qty = $('#quantity').val();
var total = qty;
$("#ms-helperText").val(total);
});
</script>
<input type="text" id="ms-helperText">
Instead of putting the selected country in the input, store it in a variable and change it accordingly.
This is how should be your code:
var searchedCountry = "";
$('#quantity').change(function() {
searchedCountry = $('#quantity').val();
$("#preview").html(searchedCountry + " " + $('#ms-helperText').val());
});
$('#ms-helperText').keyup(function() {
$("#preview").html(searchedCountry + " " + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="testfloat">
<select id="quantity">
<option selected>Select Libraries</option>
<option value="Albanian + ">Albanian</option>
<option value="Singapore + ">Singapore</option>
<option value="Malaysia + ">Malaysia</option>
<option value="Germany + ">Germany</option>
<option value="France + ">France</option>
<option value="Thailand + ">Thailand</option>
</select>
<input type="text" id="ms-helperText">
<br/>
<div id="preview">
</div>
you could try to attach that value into a hidden input in html
<input type="hidden" id="somehiddenvalue"></input>
Concat both values into a hidden form element:
// Get all needed input elements
const $country = document.querySelector( '#country' );
const $quantity = document.querySelector( '#quantity' );
const $msHelperText = document.querySelector( '#ms-helperText' );
// Event handler
function inputChange() {
const collection = [];
$country.value && collection.push( $country.value );
$quantity.value && collection.push( $quantity.value );
// Only add + if both inputs have a value.
$msHelperText.value = collection.join( ' + ' );
console.log( 'Hidden element value: ', $msHelperText.value );
}
$country.addEventListener( 'input', inputChange );
$quantity.addEventListener( 'input', inputChange );
<select id="country">
<option value="" selected>Select Libraries</option>
<option value="Albanian">Albanian</option>
<option value="Singapore">Singapore</option>
<option value="Malaysia">Malaysia</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Thailand">Thailand</option>
</select>
<input type="text" id="quantity">
<!-- the new hidden form element, that will hold both values -->
<input type="hidden" id="ms-helperText">

How to reset chosen class li elements using jquery/javascript

I need some help. I need to reset all li elements again which are auto created by chosen-select jQuery plug-in.
<link href="css/chosen.css" rel="stylesheet">
<script type="text/javascript" src="js/chosen.jquery.js"></script>
<div class="popover-content">
<p>
<select class="chosen-select text-left" style="width:100%;" onchange="setCountry();" id="conid">
<option value="" selected>Select Country</option>
<?php
foreach ($country as $v) {
?>
<option value="<?php echo $v['country_id']; ?>"><?php echo $v['country_name']; ?></option>
<?php
}
?>
</select>
</p>
</div>
<div id="popupcity" class="popover" style="width:270px">
<div class="arrow"></div>
<h3 class="popover-title">Select City</h3>
<div class="popover-content" id="ctchoosen">
<p>
<select class="text-left" style="width:100%;" id="ctid" onchange="setCity();">
<option value="" selected>Select City</option>
</select>
</p>
</div>
</div>
When the user selects the country, the city values will be added into the city select list.
function setCountry(){
var conval=document.getElementById('conid');
var selectVal='';
if (conval.selectedIndex == -1){
return null;
}else{
selectVal=conval.options[conval.selectedIndex].text;
$("#popupcountry").removeClass("in");
}
document.getElementById('bindCon').innerHTML=selectVal;
$('#borderCon').css('border', '');
//console.log('contr',conval.options[conval.selectedIndex].value);
var url="common.php?action=getCity";
$.post(url,{"con_data":conval.options[conval.selectedIndex].value},function(data){
var obj=JSON.parse(data);
console.log('data1',obj);
var ctData='';
$('#ctid').find('option').not(':first').remove();
$('#ctid').removeClass('chosen-select');
$('.chosen-select').chosen();
if(obj.isData==1){
ctData=obj.cid;
$.each(ctData, function(idx, o) {
$("#ctid").append("<option value="+o.city_id+">"+o.city_name+"</option>");
//$("#ctchoosen > ul").append('<li class="active-result" data-option-array-index='+this.city_id+'>'+this.city_name+'</li>');
})
$('#ctid').addClass('chosen-select');
$('.chosen-select').chosen();
}
})
}
When the user selects any option in the country select list, the cities are appending and I need the cities in the select box/auto created list item elements to update.
I can reset the select box but am unable to reset the auto created list item elements for which when user is selecting any new country the cities belongs to this is not displaying to user. I am also using PHP for the database operations.
Chosen offers an event that can be triggered. From the documentation:
Updating Chosen Dynamically
If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.
$("#form_field").trigger("chosen:updated");
1
When the city list has options, instead of just calling
$('.chosen-select').chosen();
after adding the cities, trigger the updated event on it:
$('#ctid').trigger("chosen:updated");
See a demonstration of this below.
//track whether options have been added to the list
var cityOptionsAdded = false;
function setCountry() {
var conval = document.getElementById('conid');
var selectVal = '';
if (conval.selectedIndex == -1) {
return null;
} else {
selectVal = conval.options[conval.selectedIndex].text;
$("#popupcountry").removeClass("in");
}
$('#borderCon').css('border', '');
var url = conval.options[conval.selectedIndex].value + ".json";
$.post(url, function(obj) {
var ctData = '';
$('#ctid').find('option').not(':first').remove();
$('#ctid').removeClass('chosen-select');
chosenSelect = $('.chosen-select').chosen();
if (obj.isData == 1) {
ctData = obj.cid;
$.each(ctData, function(idx, o) {
$("#ctid").append("<option value=" + o.city_id + ">" + o.city_name + "</option>");
});
if (cityOptionsAdded) { //subsequent addition of cities to list
$('#ctid').trigger("chosen:updated");
} else { //first time adding cities to list
cityOptionsAdded = true;
$('#ctid').addClass('chosen-select');
chosenSelect = $('.chosen-select').chosen();
}
}
});
}
/**override jQuery ajax for this sandbox
because real AJAX requests are disabled
in this environment
*/
$.post = function(url, callback) {
var data;
if ($('#conid').val() == 'CA') {
data = {
"isData": true,
"cid": [{
"city_id": "OT",
"city_name": "Ottowa"
}, {
"city_id": "VA",
"city_name": "Vancouver"
}]
};
}
if ($('#conid').val() == 'SE') {
data = {
"isData": true,
"cid": [{
"city_id": "ST",
"city_name": "Stockholm"
}, {
"city_id": "LU",
"city_name": "Lund"
}]
};
}
callback(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.min.css" />
<div class="popover-content">
<p>
<select class="chosen-select text-left" style="width:100%;" onchange="setCountry()" id="conid">
<option value="" selected>Select Country</option>
<option value="CA">Canada</option>
<option value="SE">Sweden</option>
</select>
</p>
</div>
<div id="popupcity" class="popover" style="width:270px">
<div class="arrow"></div>
<h3 class="popover-title">Select City</h3>
<div class="popover-content" id="ctchoosen">
<p>
<select class="text-left" style="width:100%;" id="ctid">
<option value="" selected>Select City</option>
</select>
</p>
</div>
</div>
1https://harvesthq.github.io/chosen/#change-update-events

Symfony2 - Collection + jQuery

I use collection type with symfony:
When I choose value in select. This value is add in list but I don't know how to make this with symfony collection.
Here my html output:
<div id="equipe_joueurs" class="mes_joueurs"
data-prototype="
<div class="form-group">
<label class="control-label" for="equipe_joueurs___name__">__name__label__</label>
<select id="equipe_joueurs___name__" name="equipe[joueurs][__name__]" class="form-control">
<option value=""></option>
<option value="1" >Joueur1</option>
<option value="2" >Joueur2</option>
<option value="3" >Joueur3</option>
</select>
Here my js:
$(document).ready(function()
{
var container = $('#equipe_joueurs');
var index = container.find(':input').length;
var prototype = $(container.attr('data-prototype').replace(/__name__label__/g).replace(/__name__/g, index));
$('#equipe_joueurs').change(function()
{
var prototype = $(container.attr('data-prototype').replace(/__name__label__/g).replace(/__name__/g, index));
$('#equipe_list').append('<li id="equipe_joueur_' + index + '" name="equipe[joueurs][' + index + ']">' + 'prototype.text() + '</li>');
index++;
return false;
});
});
Thanks for your help,
HTML
<div id="list"></div>
JQUERY
$('#list').append(prototype)

Categories