I´ve a form where user can add as much dropdowns as he needs.
I need to save the text from the selected options from the dropdowns to the session.
HTML:
<select name="codes[]" class="form-control-edited coinsurers-sv d-inline-block" placeholder="Please select">
<option value="">Please select</option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
Javascript:
<script>
let coInsuredPersonsSV = $('.coinsurers-sv').map(function (){ return $('.coinsurers-sv').find("option:selected").text() }).toArray();
sessionStorage.removeItem('co-insured-persons-hi-sv');
if (coInsuredPersonsSV.length > 0) {
sessionStorage.setItem('co-insured-persons-hi-sv', JSON.stringify(coInsuredPersonsSV));
}
</script>
Now lets say a user needs 3 dropdown forms and selects on every dropdown field another option.
Dropdown 1: Test 1
Dropdown 2: Test 2
Dropdown 3: Test 3
the result at my session storage is:
["Test 1 Test 2 Test 3", "Test 1 Test 2 Test 3", "Test 1 Test 2 Test 3"]
But the result should be:
["Test 1", "Test 2", "Test 3"]
Can someone help me on how I need to change the .find function so that I get my desired results?
In the map callback function you select all dropdown lists, instead of the iterated one. So replace this code:
return $('.coinsurers-sv').find
...with:
return $(this).find
Related
I am trying to get items when selected by user to an array with onchange action, The problem is when user select lower option according to the arrangement it does not record the higher options when selected, but rather it retain the value of the lower option untill you select an lower option if it exists.
<select name="tasks[]" id="activities" multiple="multiple" onchange="getSeleted()">
<option value="1">lifting</option>
<option value="2">jogging</option>
<option value="3">sleeping</option>
<option value="4">working</option>
<option value="5">praying</option>
</select>
</script>
var myarr = [];
function getSeleted(){
var activityValue =document.getElementById('activities').value;
myarr.push(activityValue);
console.log(myarr);
}
</script>
Whenever I select lower option it stuck with that option untill you select another lower.
e.g if you select option 1, and then 2, and then 3 the console prints.
//1,2 and 3
console ['1',]
console ['1','1']
console ['1','1','1']
//3,2 and 1
console ['3',]
console ['3','2']
console ['3','2','1']
//3,4 and 4
console ['3']
console ['3','3']
console ['3','3','3']
//5,2 and 4
console ['5']
console ['5','2']
console ['5','2','2']
It acts the same even with string, Why does it behave like this, and how can I handle it.
Why not make things little bit easier with filter and map.
Example:
function getSeleted() {
var select = document.getElementById('activities');
var selected = [...select.options]
.filter(option => option.selected)
.map(option => option.value);
console.log(selected);
}
<select name="tasks[]" id="activities" multiple="multiple" onchange="getSeleted()">
<option value="1">lifting</option>
<option value="2">jogging</option>
<option value="3">sleeping</option>
<option value="4">working</option>
<option value="5">praying</option>
</select>
This question already has answers here:
adding onclick event to html select option
(3 answers)
Closed 1 year ago.
I am building my own shopping website, and I got stuck in this part:
<label for="option">Option</label>
<select id="option">
<optgroup>
<option onclick="changeValueA()">Option A</option>
<option onclick="changeValueB()">Option B</option>
</optgroup>
</select>
<p>You choosed Option <span id="option-value"></span></p>
<script>
function changeValueA(){
document.getElementById("option-value").innerHTML = "Option A";
}
function changeValueB(){
document.getElementById("option-value").innerHTML = "Option B";
}
</script>
I want to make "option-value" display "Option A" if changeValueA() is called by clicking the Option A from <select>, and I want to make "option-value" display "Option B" if changeValueB() is called by clicking the Option B from <select>.
However, the code doesn't work. It would be really grateful if you help me this part!
option elements don't respond to click events (as you can see by the added console.logs below); you instead need to check the <select>'s value:
// these functions never run:
function changeValueA() {
console.log("A")
document.getElementById("option-value").innerHTML = "Option A";
}
function changeValueB() {
console.log("B")
document.getElementById("option-value").innerHTML = "Option B";
}
// This one will be triggered by the select's onchange handler,
// and passes the selected value in so you don't need multiple
// similar functions:
function changeValue(val) {
document.getElementById("option-value").innerHTML = val;
}
<label for="option">Option</label>
<select id="option" onchange="changeValue(this.value)">
<optgroup>
<option onclick="changeValueA()">Option A</option>
<option onclick="changeValueB()">Option B</option>
</optgroup>
</select>
<p>You chose <span id="option-value"></span></p>
I'm displaying two <select> elements. The second <select> is disabled depending on the <option> selected on the first <select>. The problem is when I select an <option> on the first <select>, I want the data shown on the second <select> to be changed. For example, if I select District 1 on the first <select>, I want to see john and mary as options in the second <select>, but if I select District 2, I want josef and charles. Consider that I'm doing this on Laravel and using Vue.
I have done the first part using Vue, disabling the second <select> depending on what has been chosen on the first <select> (only third option on the first <select> will enable the second <select>):
https://jsfiddle.net/vowexafm/122/
Template:
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<select #change="treat">
<option value="District1">District 1</option><!--disable 2nd select-->
<option value="District2">District 2</option><!--disable 2nd select-->
<option value="District3">District 3</option><!--enable 2nd select-->
</select>
<br><br>
<select :disabled="isDisabled">
<option>cds 1</option>
<option>cds 2</option>
<option>cds 3</option>
</select>
</div>
Script:
new Vue({
el:'#app',
data: {
isDisabled: true,
},
methods: {
treat: function(e) {
if (e.target.options.selectedIndex == 0 ||
e.target.options.selectedIndex == 1) {
return this.disable();
}
if (e.target.options.selectedIndex != 0 &&
e.target.options.selectedIndex != 1) {
return this.enable();
}
},
enable: function() {
return this.isDisabled = false; // enables second select
},
disable: function() {
return this.isDisabled = true; // disables second select
}
},
});
Now the solution I want,for example: if i'I select District 1 on the first , I want to see john and mary as options in the second , but if I select District 2, I want to see josef and charles on the second .
Populate data object from laravel to have the options for the second select in it and a value for the current selected index from the first select
data: {
secondSelect: [
['john', 'mary'],
['josef', 'charles']
],
currentIndex: 0
}
Define a computed property that returns the values for the second select depending on currentIndex
computed: {
persons () {
return this.secondSelect[parseInt(this.currentIndex)]
}
}
Generate the second select using the computed property persons and use v-model to capture currentIndex.
<div id="app">
<select #change="treat" v-model="selectedIndex">
<option value="0">District 1</option><!--diable-->
<option value="1">District 2</option><!--diable-->
<option value="2">District 3</option><!--unable-->
</select>
<br><br>
<select :disabled="isDisabled">
<option v-for="option in persons" :value="option">{{option}}</option>
</select>
</div>
now the solution I want,for example if i select 'District 1 'on the
first i want to see 'john' and 'mary' as options in the second , but
if I select 'District 2' i want to see 'josef' and 'charles' on the
second .
is that whats in your mind?
new Vue({
el:'#app',
data:{
district:'-1',
options:{
'District1':false,
'District2':false,
'District3':false
},
},
methods:{
getOptions(){
axios.get('https://jsonplaceholder.typicode.com/users',{district:this.district}).then(res=>
this.options[this.district]=res.data)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<select v-model="district" #change="getOptions()">
<option value="-1" selected disabled hidden>choose a district</option>
<option value="District1">District 1</option>
<option value="District2">District 2</option>
<option value="District3">District 3</option>
</select>
<br><br>
<select v-if="options[district]">
<option v-for="option in options[district]">{{option.name}}</option>
</select>
</div>
edit:
after your comment, i edited this answer so now its fetching the data from some api.
to fetch the options from a db, you first have to create an api for your app, and when the request comes out of your vue client side - the server will retrieve rows from the db, do some caculations based on the parameters you sent in the request, and bring back a json data array.
(i wont cover the server side now - thats completely off-topic. but you can easily google for 'laravel json response')
in this snippet, i used some example json api, just to show you how its done on the client side:
i use v-if to cause late- rendering of the second select. it will be rendered only after i get the options, via axios (a very common npm package used to make ajax requests in modern js frameworks).
im also registering an event listener to the change event of the first select - to make my ajax request and populate my options every time the disrict changes (i used a default option to avoid unneeded requests)
i'm trying to build a select box that trigger show on options of other select in angular way.
the json that i use build select boxs is
[
{"item_id":1,"item":"rubber","type":"x","facility":"school a"},
{"item_id":2,"item":"pen","type":"x","facility":"school b"},
{"item_id":3,"item":"book","type":"y","facility":"school b"},
]
what i need is 3 select boxes, first one shows all unique type. in above json that would be 'x,y'.
when user select one of them, then it should show all unqiue facility values in other selectbox that has same type as selected.
--if user selected x, then it would show school a and school b
when user select facility, a 3rd selectbox show all uiqiue item as label, and item_id as value where facility = selected facility
<select ng-model="selected.type">
<!-- need to show unique types here -->
</select>
<select ng-model="selected.facility">
<option ng-repeat="s in json" ng-if='selected.type == s.type'>{{s.item}}</option>
</select>
<select ng-model="selected.item">
<option ng-repeat="s in json" ng-if='selected.facility == s.facility'>{{s.item}}</option>
</select>
Current solution
currently what i'm doing is that i wrote a filter
.filter('unique', function() {
return function (arr, field) {
var r = [],final=[];
for(i in arr){
if(r.indexOf(arr[i][field]) == -1){
r.push(arr[i][field]);
final.push(arr[i]);
}
}
return final;
};
})
and doing
<select class="form-control" ng-model="nrequest.facility">
<option ng-repeat="s in facility_services |unique:'facility'" value="{{s.facility}}">{{s.facility}}</option>
</select>
<select class="form-control" ng-model="nrequest.item">
<option ng-repeat="s in facility_services" ng-if='s.facility == nrequest.facility'>{{s.item}}</option>
</select>
it works yet i'm not sure if this is correct way to do it angular way, since i'm still learning this new toy i was hoping for some directions on how to achieve this using ngoptions, or other angularjs best practice
I needed some help updating the price on a page based on a dropdown selection.
This is what code with some help we came up with:
var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Which works if my dropdown is structured like this:
<select name="material">
<option value="">-- Please Select --</option>
<option value="1">Wood</option>
<option value="2">Plastic</option>
<option value="3">Metal</option>
</select>
But if for any reason the the dropdown was to be like this:
<select name="material">
<option value="">-- Please Select --</option>
<option value="3">Metal</option>
<option value="4">Cloth</option>
<option value="5">UPVC</option>
</select>
it would not work (because the value option is not 1,2,3). The value is the id for the material. Hope this makes sense and that someone can help me to get this working.
Thanks
Dino
You're changing the price based on the value, and using that as the item from your price array... but your price array only has 4 values. In your second select, you're asking it to return price[4] or price[5], which would cause an error.
Change this:
var price = new Array('','$2.00','$45.00','$60.00');
To this:
var price = new Array('','$2.00','$45.00','$60.00','$cloth price','$upvc price');
Fiddle here.
EDIT: Updated method (with minimal change to your existing layout/logic)
$(function() {
$('select[name=material]').change(function() {
var price = $(this).val().split("_");
$("#id").html(price[0]);
$("#price").html("$" + price[1]);
});
});
HTML (adding the price to each option value, split by "_" in JS)
<select name="material">
<option value="0_0">-- Please Select --</option>
<option value="1_2">Wood</option>
<option value="2_2">Plastic</option>
<option value="3_45">Metal</option>
</select>
<select name="material">
<option value="0_0">-- Please Select --</option>
<option value="3_60">Metal</option>
<option value="4_50">Cloth</option>
<option value="5_80">UPVC</option>
</select>
<div>ID: <span id="id">TBD</span><br />Price: <span id="price">TBD</span></div>
Just select price using the selectedIndex of your <select>:
var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[this.selectedIndex];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Or, use an object instead of an array for price:
var price = {
"4": "$2.00",
"5": "$45.00",
"6": "$60.00"
};
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Update: Here is a jsfiddle with updated code to get your single price array to work:
Your price arrayhas a length of 4 and starts at index 0.
Your first option must have a value of '0' or it will return undefined from the price array:
<select name="material">
<option value="0">-- Please Select --</option>
<option value="1">Wood</option>
<option value="2">Plastic</option>
<option value="3">Metal</option>
</select>
When you set your option values from 3 to 5, you are trying to access non-existent indexes outside the bounds of your price array.