There will be two drop down lists,
First have the list of mobile vendor, and the second have the list of models per vendor.
When one select a vendor from the first drop down list, the second drop down list should populate with relevant model for that vendor dynamically. This is for mobile web site, it's better to use jquery-mobile
The option values for the second will in a json map.
<select class="mobile-vendor">
<option value="motorola">Motorola</option>
<option value="nokia">Nokia</option>
<option value="android">Android</option>
</select>
selectValues = {"nokia" : {"N97":"download-link",
"N93":"download-link"},
"motorola": {"M1":"download-link",
"M2":"download-link"}}
<select class="model">
<option></option>
</select>
For example, if the user selects nokia in the first drop down list, the second drop down list should have N97, N93 as the options.
EDIT: New javascript to take into account your updated json structure:
$(function() {
var selectValues = {
"nokia": {
"N97": "http://www.google.com",
"N93": "http://www.stackoverflow.com"
},
"motorola": {
"M1": "http://www.ebay.com",
"M2": "http://www.twitter.com"
}
};
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
});
Working example is available in jsFiddle.
Note that this should work with jQuery mobile just fine.
Related
I have 2 dynamic dropdown lists namely Levels and Grades that can also do multi-select. “Grades” dropdown changes its values whenever I choose an option in “Levels” dropdown. If I select High School in “Levels” dropdown, then the “Grades” dropdown values will now be grades 7-10. Now, the problem is, if I select Kinder in “Levels” dropdown while High School has been previously selected, “Grades” dropdown values like Kinder and Prep duplicates. That’s not the only situation where duplicate is happening. The same thing happens when I deselect either one or both in “Levels” dropdown.
Here's my screenshot:
image
Here are my codes:
* I am using select2 plugin for my dropdown lists
HTML - send_sms_non.blade.php
//Levels dropdown list
<select multiple="multiple" class="form-control select2meAdd selectelement" required id="levels" name="levels[]" style="width:50%;">
<option value="" selected disabled></option>
#foreach ($data['stages'] as $stage)
<option value="{{ $stage->id }}">{{ $stage->stage }}</option>
#endforeach
</select>
//Grades dropdown list
<select multiple="multiple" class="form-control select2meAdd selectelement" required id="grades" name="grades[]" style="width:50%;">
</select>
PHP
public function getIndexNon()
{
if (!(require_school_access('ACCESS-SMS', 4))) {
return redirect('/home/invalid-access');
}
$data['subscription'] = $this->subscription;
$data['schoolfront'] = $this->schoolfront;
$data['accounts'] = SchoolAccount::where('school_id',$this->subscription->subscription->id)->get();
$data['stages'] = SchoolStages::where('school_id',$this->subscription->subscription->id)->get();
return view('school.send_sms_non', array('data' => $data));
}
public function getAjaxDataGrades(Request $request)
{
$level_ids = explode(',', Input::get('level_ids'));
// $selected_levels = array();
// foreach ($level_ids as $level_id) {
// if ($level_id) {
// if (!in_array($level_id,$selected_levels)){
// $selected_levels[] = $level_id;
// }
// }
// }
$grades = SchoolStages::leftJoin('school_stage_levels','school_stage_levels.stage_id','=','school_stages.id')
->whereIn('school_stage_levels.stage_id',$level_ids)
->where('school_stages.school_id',$this->subscription->subscription->id)
->get();
return Response::json($grades);
}
JAVSCRIPT
$('.select2me').select2();
$('#levels').on('change',function(){
var level_ids = $(this).val();
$.get('/sms/ajax-data-grades?level_ids='+level_ids, function(data){
// $('#grades').empty();
$('#grades').append('<option value="0" selected disabled>
</option>');
$.each(data, function(index, gradeObj){
$('#grades').append('<option
value="'+gradeObj.id+'">'+gradeObj.level_code+'</option>');
});
});
});
Thank you very much.
In .each function, you may use the following code to detect whether the incoming item existed in grades down drop box already.
var grades=$('#grades');
var allOptions=grades.children('option');
option = allOptions.find("[value='"++gradeObj.id+"']");
if (option.length==0) //that mean does not exist
{
$('#grades').append('<option
value="'+gradeObj.id+'">'+gradeObj.level_code+'</option>');
}
I'm using chosen for my multiple select box, but I don't know how to get the selected items?
<select class="multiselect" multiple="" name="parlementId">
#foreach (Politicus p in politici)
{
<option value="#p.politicusID">#Html.DisplayName(p.Account.voornaam.ToString())</option>
}
</select>
$('.multiselect').chosen({ width: '500px', allow_single_deselect: true, max_selected_options: 5 });
$('.multiselect').on('change', function (evt, params) {
//this is where I need to know which options are selected
});
you can get like this:
var values = $(".multiselect").chosen().val();
// this will give you values in an array
See Documentation here
or:
var values = $(".multiselect").val();
I have an issue with the data which is sent from a drop down menu, the selector only returns a single value, even when multiple values are selected. I have searched online for a solution to this, but they all use PHP, JQuery or some method outside the scope of the course I am taking; to capture multiple selected items. I have tried .value of the individual options, but that returns all of the options rather than just the ones which are selected. Is there some kind of trick to sending multiple values?
Here is my code for the menu. For example If I select JAVA PROGRAMMING, NETWORKS and VIDEO GAMES, only JAVA PROGRAMMING is sent.
<select multiple id="CK_Expertise">
<option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
<option id="CK_Exp2" value="Networks">NETWORKS</option>
<option id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
<option id="CK_Exp4" value="Accounter">ACCOUNTER</option>
<option id="CK_Exp5" value="Help Desk">HELPDESK</option>
<option id="CK_Exp6" value="C++ programming">C++</option>
<option id="CK_Exp7" value="Programming">PROGRAMMING</option>
</select>
I have also tried using the Select Object in the DOM, http://www.w3schools.com/jsref/dom_obj_select.asp
which has a few methods for accessing the options in the dropdown menu. One method in particular called selectedIndex, seemed to be what I am looking for, however it only returns the the index of the first selected option, instead of all of the selected options.
Is there a simple solution to this using just Javascript and the DOM?
Thanks
- Chris
Get the options, iterate and check if they are selected, and add the values to an array
var select = document.getElementById('CK_Expertise'),
options = select.getElementsByTagName('option'),
values = [];
for (var i=options.length; i--;) {
if (options[i].selected) values.push(options[i].value)
}
console.log(values)
FIDDLE
or being a little more fancy
var select = document.getElementById('CK_Expertise'),
values = Array.prototype.filter.call(select.options, function(el) {
return el.selected;
}).map(function(el) {
return el.value;
});
console.log(values)
FIDDLE
You could use the select.selectedOptions property:
select.onchange = function() {
var values = [].map.call(this.selectedOptions, function(opt){
return opt.value;
});
};
document.getElementById('CK_Expertise').onchange = function() {
document.querySelector('pre').textContent = JSON.stringify([].map.call(
this.selectedOptions, function(opt){ return opt.value; }
));
}
<select multiple id="CK_Expertise">
<option id="CK_Exp1" value="Java programming">JAVA PROGRAMMING</option>
<option id="CK_Exp2" value="Networks">NETWORKS</option>
<option id="CK_Exp3" value="Video game programming">VIDEO GAMES</option>
<option id="CK_Exp4" value="Accounter">ACCOUNTER</option>
<option id="CK_Exp5" value="Help Desk">HELPDESK</option>
<option id="CK_Exp6" value="C++ programming">C++</option>
<option id="CK_Exp7" value="Programming">PROGRAMMING</option>
</select>
<pre></pre>
If you can use jQuery, this will give you all the values
$(document).ready(function(){
$('#CK_Expertise').change(function(e){
var values = $('#CK_Expertise').val()
alert(values);
});
});
HTH,
-Ted
You could iterate storing select.selectedIndex in an array and unselecting the corresponding option to get the next one:
select.onchange = function() {
var i, indices=[], values = [];
while((i=this.selectedIndex) > -1) {
indices.push(i);
values.push(this.value);
this.options[i].selected = false;
}
while((i=indices.pop()) > -1)
this.options[i].selected = true;
console.log(values);
}
Demo
This way you avoid iterating over all options, but you must iterate twice over the selected ones (first to unselect them, them to select them again).
Why not using an indexed variable in the SELECT command?
<SELECT MULTIPLE id="stuff" name="stuff[]">
<OPTION value=1>First stuff</option>
<OPTION value=2>Second stuff</option>
<OPTION value=3>Third stuff</option>
</SELECT>
In that case it's easy to read the array:
$out=$_REQUEST['stuff'];
foreach($out AS $thing) {
echo '<br />'.$thing;
}
Sorry for the poor indentation, but I just wanted to show the way I use for solving this case!
var select = document.getElementById('CK_Expertise'),
options = select.selectedOptions,
values = [];
for(let i=0;i<options.length;i++)
{
values.push(options[i].value);
}
console.log(values);
I have two drop-downs and a text box. First drop down is a list with static values. Second drop down is dynamically filled from a json array. Here is what I would like to achieve. Filter the second drop down based on the value selected from the first drop down. And the text box will output the value based on the selected value from the second drop down. Here is where I am currently:
On change I am able to populate the 2nd drop-down and able to output the matched value to the text-box. However my 2nd drop down not being filtered properly. Instead it populates all the available option values. I checked different posts here and tried filtering values before appending but, no avail so far.
HTML:
<select name="make" id="make">
<option value="0">Select Make:</option>
<option value="1">Acura</option>
<option value="2">BMW</option>
</select>
<select name="model" id="model">
<option value="model">Select Model</option>
</select>
<label for="CarSize"> Your car's size is : </label>
<input type="text" name="carsize" id="size">
Script:
var a = {
Cars:[
{
"id":1,
"make":"Acura",
"model":"2.2CL/3.0CL",
"size":"Car"
},
{
"id":12,
"make":"Acura",
"model":"RDX ",
"size":"Compact SUV"
},
{
"id":10,
"make":"Acura",
"model":"MDX",
"size":"Large SUV"
},
{
"id":74,
"make":"BMW",
"model":"128",
"size":"Car"
},
{
"id":75,
"make":"BMW",
"model":"135",
"size":"Car"
},
{
"id":129,
"make":"BMW",
"model":"X3 ",
"size":"Compact SUV"
},
{
"id":130,
"make":"BMW",
"model":"X5",
"size":"Large SUV"
}
]
};
$("#make").change(function(){
if ("#model" !='Select Model')
$('#model').empty().append($('<option></option>').val('Select Model').html('Select Model'));
else;
$.each(a.Cars, function (key, value) {
$("#model").append($('<option></option>').val(value.size).html(value.model
));
});
});
$('#model').change(function () {
//alert($(this).val());
//var getModelval = $('#model').val();
$('#size').val($(this).val());
//$('#size').val(.val(id));
});
Here is a fiddle link: http://jsfiddle.net/kamuflaj/6vvfr/9/
There are several options for JSON filtering. Below is one way you can change your onchange event to filter the model dropdown.
$("#make").change(function () {
$('#model').empty().append($('<option></option>').val('Select Model').html('Select Model'));
var matchVal = $("#make option:selected").text();
a.Cars.filter(function (car) {
if (car.make == matchVal) {
$("#model").append($('<option></option>').val(car.size).html(car.model));
}
});
});
Here is an updated fiddle.
I have two dropdown lists that filter content. The first one is the locations and the second one is the jobs. The first list filters the second. I'm using a :contains to read the string values that allow my filter to work. I'm running into a problem when I want to use two contains at once as a filter. Here is the code:
HTML
<div class="holder">
<label for="volunteerLocation">Where do you want to volunteer?</label><br>
<select id="locations">
<option value="0">--Select a Campus--</option>
<option value="5">Location 1</option>
<option value="6">Location 2</option>
<option value="7">Location 3</option>
</select>
</div>
<br />
<div class="holder">
<label for="volunteerJobs">In which area would you like to serve?</label><br />
<select id="jobs">
<option value="1">Job 1 (Location 1)</option>
<option value="2">Job 2 (Location 2)</option>
<option value="3">Job 3 (Location 3)</option>
<option value="4">Job 4 (All locations)</option>
</select>
</div>
Javascript
var select = $('#jobs');
var options = [];
$(select).find('option').each(function () {
options.push({ value: $(this).val(), text: $(this).text() });
});
$(select).data('options', options);
$('#locations').change(function () {
filterText = $("#locations option:selected").text();
var optionList = $(select).empty().data('options');
var j = 0;
$.each(optionList, function (i) {
var option = options[i];
if (option.text.indexOf(filterText) !== -1) {
if (j == 0) {
$('#jobs').prepend("<option value=''>--Select a Job--</option>").val('');
j++;
};
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
if (filterText == "--Select a Campus--") {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
})
})
Here is a JSLint of this so you can see it in action Full Example
I'm trying to get "Job 4" to show up on everything but the "Select a Campus" option. How do I do that?
instead of looping with .each every time location change, and going through exceptions, me would create an index upon page load
var locJobs=new Array();
then you fill it with your data, for example
locJobs['5']=new Array();
locJobs['5'] = ['job 1','job 2']
then on change
$("#jobs").html('<option>'+locJobs[$(this).val()].join('</option><option>')+'</option>');
if you need to add the value on the options of #jobs you'll have to complicate that snippet a bit.
It shall be more efficient & also make maintenance much easier (no exceptions to deal with just an array to populate from whatever data source you are using) as you'll end up with a very flexible solution
nb: you declare var select = $("#jobs") but then you use $(select); that is a useless overhead use select directly
a convention to keep code clear is to add $ to any variable that is caching a jquery object :
var $select=$("#select")
then you use $select.whtever(//...