Drop-down box with Json data - javascript

I am trying to use jquery to populate the dropdown box with the following JSON data
{
"Name":["A","B","C"],
"Movie":["X","Y","Z"]
}
And this the script what I have done so far
$("#firstbox").change(function(){
var $selection=$(this);
$.getJSON("data.json",function(data){
var i=$selection.val();
var arr=[];
switch(i){
case 'Name':
arr=data.Name.split(",");
break;
case 'Movie':
arr=data.Movie.split(",");
break;
}
});
});
My basic index.html is just like this
<select id="firstbox">
<option selected value="">---Select---</option>
<option value="Name">Name</option>
<option value="Movie">Movie</option>
</select>
<select id="secondbox" name="">
<option selected value="">---Generate---</option>
<script src="myjs.js"> </script>
</select>
The 'secondbox' drop-down should generate the value corresponding to the selections of 'firstbox' drop-down. The error I received is 'undefined split function'. Can anyone give me a hint ?
Thanks

split is a method of the String object, here you use it on the Array object.
You dont need to split as the Name and Movie keys are allready arrays in the JSON object.
$("#firstbox").on("change", function(e){
var sel=$(this).val();
$("#secondbox").empty();
$.getJSON("data.json",function(data){
var values=data[sel] || ['Error : key not found'];
$(values).each(function(index,element) {
$("<option />", {value: element, text:element}).appendTo("#secondbox");
});
});
});
Here is a working exemple : http://jsfiddle.net/cKBeE/

$("#firstbox").on("change", function(e){
writeOptions();
}
function getJSONData(firstboxval) {
//make ajax call to get data for second dropdown
//that corresponds to the value selected in firstbox
//then make function return the array of options
}
function writeOptions() {
var firstboxval = $("#firstbox").val();
var optionValues = getJSONData(firstboxval);
var dropDown = document.getElementById("secondbox");
for(var i=0; i<optionValues.length; i++) {
var key = i;
var value = optionValues[i];
dropDown.options[i] = new Option(value, key);
}
}

Related

How to obtain multiple select options when serializing Form data in javascript (vanilla or jQuery)?

I wrote the following function that turns a div/Form into serialized object. I use this returned to pass into my database javascript calling methods.
Tater.prototype._formToObject = function(formData) {
var p = {};
jQuery.each(jQuery(formData).serializeArray(),function(i, e){
p[e.name] = e.value;
});
return p;
};
The only issue is if I change my form to have a multiple select option, it only grabs the first value of the multiple selected. How would I extend this to allow for such behavior?
Try something along these lines to get the array of values.
If you give us a working snippet of what you are doing it will be easier to adapt to what you want.
Most likely you need to add a check for the multiple attribute on e (see comments below)
else do the current logic that seems to be working
in the below logic replace this with e for your scenario
`
Tater.prototype._formToObject = function(formData) {
const p = {};
jQuery.each(jQuery(formData).serializeArray(),function(i, e){
//check for multiple attr
e.getAttribute('multiple') == null ?
(p[e.name] = e.value) :
(p[e.name] = $(e).val());
});
return p;
};
`
document.getElementById('multi').addEventListener('change', function () {
//jquery
this.getAttribute('multiple') != null && console.log($(this).val());
//vanilla
if(this.getAttribute('multiple') != null) {
const arr = [], nodes = this.querySelectorAll(':checked');
for(let i = 0; i < nodes.length; i++) {
arr.push(nodes[i].value);
}
console.log(arr);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="multi">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<!-- from https://www.w3schools.com/tags/att_select_multiple.asp -->

How to populate select options from an array based on a select value?

Trying to get my second select element's options to populate from an array based on the value of the first select element. I can't seem to understand why it only populates the items from the array of the first select element. I know the appendChild is causing the items to keep tacking on at the need, but I've tried to clear the variables, but it seems the option elements that were created stay.
Any help would be great, thanks!
<select id="makeSelect" onChange="modelAppend()">
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect">
</select>
<script>
var audiModels = ["TT", "R8", "A4", "A6"]; //audimodels
var mercModels = ["C230", "B28", "LTX",]; //mercmodels
var bmwModels = ["328", "355", "458i",]; //bmwmodels
var selectedMake = document.getElementById("makeSelect"); //grabs the make select
var selectedModel = document.getElementById("modelSelect"); //grabs the model select
var appendedModel = window[selectedMake.value + "Models"]; // appends "Models" to selectedMake.value and converts string into variable
function modelAppend() {
for (var i = 0; i < appendedModel.length; i ++) { // counts items in model array
var models = appendedModel[i]; // // sets "models" to count of model array
var modelOptions = document.createElement("option"); //create the <option> tag
modelOptions.textContent = models; // assigns text to option
modelOptions.value = models; // assigns value to option
selectedModel.appendChild(modelOptions); //appeneds option tag with text and value to "modelSelect" element
}
}
</script>
This line is fishy:
var appendedModel = window[selectedMake.value + "Models"];
You need to get the element when the value has changed, not on page load. Then you need to remove the options on change too, or you will get a very long list if the user selects multiple times. Use an object to store the arrays, that makes it much easier to access them later. Also better use an event listener instead of inline js (though that's not the main problem here).
Try below code:
let models = {
audiModels: ["TT", "R8", "A4", "A6"],
mercModels: ["C230", "B28", "LTX"],
bmwModels: ["328", "355", "458i"]
}
document.getElementById('makeSelect').addEventListener('change', e => {
let el = e.target;
let val = el.value + 'Models';
let appendTo = document.getElementById('modelSelect');
Array.from(appendTo.getElementsByTagName('option')).forEach(c => appendTo.removeChild(c));
if (!models[val] || !Array.isArray(models[val])) {
appendTo.style.display = 'none';
return;
}
models[val].forEach(m => {
let opt = document.createElement('option');
opt.textContent = opt.value = m;
appendTo.appendChild(opt);
});
appendTo.style.display = '';
});
<select id="makeSelect">
<option value=""></option>
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect" style="display:none">
</select>

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

Displaying key and values of the options in a dropdown using javascript

function keyy(id)
{
var value;
var selected;
var select = document.getElementById(id);
if(value != null)
select.options[selected].text = value;
selected = select.selectedIndex;
var key;
key =select.options[selected].value;
value= select.options[selected].text;
select.options[selected].innerHTML = key;
}
<select id="Carss" name="Cars" onchange="keyy(this.id)" >
<option value="A">Audi</option>
<option value="M">Mercedes</option>
</select>
I have n dropdown values. When I select one value, the corresponding key should be displayed. The drop down should be the values and the display item shoud be the coresponding key.
Have atached the image for the reference.
My code :
var value;
var selected;
function keyy(id) {
var select = document.getElementById(id);
if(value != null)
select.options[selected].text = value;
selected = select.selectedIndex;
var key;
key =select.options[selected].value;
value= select.options[selected].text;
select.options[selected].text = key;
}
What you're trying to do is impossible (with a native <select>). The item you see in the closed <select> is simply the <option> that is currently selected. When you open the drop-down, you see the same <option> in two places - in the "selection" and in the "list". You cannot see a different value in each of the places, when it's the same <option>.
You could, however, show the selected value somewhere else, e.g. in a second element next to the <select>.
This is not a perfect answer..
But a possible work around..
function key() {
document.getElementById("Carss").style.width = "100px"
}
function key2() {
document.getElementById("Carss").style.width = "34px"
document.getElementById("Carss").blur();
}
<select id="Carss" name="Cars" onfocus="key()" onchange="key2()" style="width:34px">
<option value="A">Audi</option>
<option value="M">Mercedes</option>
</select>

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories