DEPENDENT SELECTS WITH CLASS = "chosen-select" - javascript

I'm trying to make a form with dependent dropdown, but the problem is when I go from select 1 to select 2 that has the "chosen-select" class, it does not show me the data in this dropdown, but if I change this class to this dropdown and I put "form-control", if you pass me the necessary data.
How can I use the "chosen-select" class in SELECT 2, so that I can read the data dynamically
Select 1
<select id="jornada" class="form-control" name="jornada" required>
<option value="">-- SELECCIONE --</option>
<?php
while ($row=mysqli_fetch_array($jornada)) {
echo '<option value='.$row["id"].'>'.$row["jornada"].'</option>';
}
mysqli_free_result($jornada)
?>
</select>
Select2 - the ideal is that in this dropdown I can search, instead of selecting
<select id="r_ruta" class="chosen-select" name="r_ruta" required>
<option value="">-- SELECCIONE --</option>
</select>
Script
$(document).ready(function(){
$("#jornada").change(function(){
$.get("get_colegios.php","jornada_id="+$("#jornada").val(), function(data){
$("#r_ruta").html(data);
console.log(data);
});
});
});
I try whits this script and addClass() jquery, but not work
$(document).ready(function(){
$("#jornada").change(function(){
$.get("get_colegios.php","jornada_id="+$("#jornada").val(), function(data){
$("#r_ruta").html(data);
console.log(data);
$("#r_ruta").addClass("chosen-select");
});
});
});
Im noob in this, very thnks for u help

since you mentioned you would like to search as well as selecting you could use select2.
https://select2.org/ then you can change your dependent dropdown data source like this
$('#example').on('select2:select', function (e) {
var data = e.params.data;
if (data.text == 'Dogs'){
$('#dependent').select2('destroy').empty().select2({data: dogs});
}
if (data.text == 'Birds'){
$('#dependent').select2('destroy').empty().select2({data: birds});
}
if (data.text == 'Snakes'){
$('#dependent').select2('destroy').empty().select2({data: snakes});
}
});
here is a fiddle
https://jsfiddle.net/rLmztr2d/2462/

Related

Filter Dropdown Based on Other Dropdown Selection

I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
This is the JavaScript that I have so far, however, if I do a console.log(classN), all that it is doing is just logging all of the dates. It doesn't actually filter anything:
$(document).ready(function () {
var allOptions = $('#date option')
$('#collector').change(function () {
$('#date option').remove();
var classN = $('#collector option:selected').prop('class');
var opts = allOptions.filter('.' + classN);
console.log(opts);
$.each(opts, function (i, j) {
$(j).appendTo('#date');
});
});
});
jquery can't run php on the page once it is loaded. You could use ajax, running the query to get the second set of options from another file.
<select id="collector">
<?php //code to generate initial collector options ?>
</select>
<select id="date">
<option>--Bill Date--</option>
</select>
In your jquery, target the first dropdown and then use load() to call a php file
$(document).ready(function(){
$("#collector").on('change', function(){
filterItems(this.value);
});
});
function filterItems(value){
var destination = "#date";
var url = "path/to/filterCode.php?v="+value;
$(destination).load(url);
});
In the filterCode php file, get the value selected by the user
$selectedCollector = $_GET['v'];
Then use $selectedCollector to query your database and get the appropriate date options.
Then, inside your results loop:
echo '<option class="'.$date['Date'].'" value="'.$date['Date'].'">'.$date['Date'].'</option>';
The load() will take these echoed options and put them into #date.
I think you need to populate #date drop-down based on #collector drop-down value, according to me best option is ajax.
here some basic example,
<select id="collector">
<option value=""></option>
</select>
jut think this as your #collector drop-down there will be some options based on your data. Now you need to populate #date drop-down,
<select id="collector">
<option value=""></option>
</select>
In page load you can load all the data if you want.
when #collector drop-down change you can send ajax request and retrieve data from database based on #collector value, like this
$("#collector").on('change', function(){
$.ajax({
type: method,
url: url,
data: data,
success: function(response) {
//populate select box
}
});
});
Below links will be helpful,
How to Use jQuery’s $.ajax() Function
Populate dropdown select with array using jQuery

Selecting multiple value from a dropdown and call a javaScript function

I know I can create a multiple select dorpdown like this -
<select name="city" multiple>
<option value="Dallas">Dallas</option>
<option value="New York">New York</option>
<option value="Kansas">Kansas</option>
<option value="Massachusetts">Massachusetts</option>
</select>
Using this multiple select dropdown I can select multiple city from. But can I select a javascript method separately for each of the city?
Thanks in advance.
You can get the value using jQuery '.val()' function.
Jquery.fn.val()
You can see how it works in the following example:
http://jsfiddle.net/uoL3s610/
$(document).ready(function(){
$('[name="city"]').change(function(){
$('#selected_container').text($('[name="city"]').val());
});
});
Or this example
http://jsfiddle.net/uoL3s610/1/
$(document).ready(function(){
$('[name="city"]').change(function(){
$('#selected_container').text('');
$.each($('[name="city"]').val(),function(index,value){
$('#selected_container').text($('#selected_container').text() + ', ' + value)
});
});
});
You are able to store the selected value of your dropdownlist in a variable and then continue with an If-structure or a switch:
$("city:selected").each(function () {
switch($(this).val()){
case "city1":
break;
}
});

How do I select displayed value as opposed to VALUE options?

We have the following SELECT combobox that is populated dynamically with ajax and httphandler web service (.ashx).
When SELECT combobox is dynamically populated, it looks like this:
<select name="selectid" id="selectid">
<option value="">-Select an option-</option>
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</o4tion>
<option value="4">Test5</option>
<option value="5">Test6</option>
<option value="6">Test7</option>
</select>
Below is the js:
function getText() {
$.ajax({
url: 'rulings.ashx',
dataType: 'json'
})
.done(function(textInfo) {
$(textInfo).each(function(i, texts) {
$('<option>').val(texts.dbtextID).text(texts.textToBeDisplayed).appendTo( $('#selectid') );
})
});
}
When we display the values from the dropdown, it displays the VALUE options instead of the displayed text.
Example from the combobox above, it displays 1 instead of Test1.
How do I modify the script to show displayed text instead of VALUE options?
Try this code , just put it inside
$(document).ready(function(event){
$("#selectid").on('change',function() {
//alert($("#selectid option:selected").text());
$('#summTextvalue').html($("#selectid option:selected").text());
});
})
The ON method in jQuery can bind events to dynamically created elements.
or you can also do something like
function _bindEvent()
{
$("#selectid").on('change',function() {
alert($("#selectid option:selected").text());
});
}
and call _bindEvent() from your AJAX done method
Try this to get text, instead of value.
$('#selectid').change(function(){
var selectedVal=$(this).val();
alert($(this).children("option[value='"+selectedVal+"']").text());
});

Display elements in dropdown with jquery

Good day community,
I have an ASP.NET MVC4 project, where on edit page I'm use jquery script. But I have a problem to display elements on the page.
Here is my dropdown's HTML markup before changes:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option value="3">testtsi</option>
<option selected="selected" value="4">testrtu3</option>
</select>
And here is after jquery changes
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
But it's display on the page not a selected element testrtu3, always display first element. And when I click save button saved my first value.
Here is my jQuery function:
$(document).ready(function () {
var values = [];
$(".checkboxUniversities:checked").each(function () {
values.push($(this).val());
});
$.getJSON('/Administrator/ProgramList/' + values, function (data) {
alert('Return json result new information');
var items = '<option disabled>Select a Program</option>';
$.each(data, function (i, program) {
items += "<option value='" + program.Value + "'>" + program.Text + "</option>";
});
$('#ProgramId').html(items);
});
//var selectedElement = $("#ProgramId").find(":selected").text();
});
I guess I need somehow add selected value when create my dropdown inside jquery, or after creating, but I don't know how. Can anybody help me?
Before appeding options to your dropdown you have to save selected index or text in variable and use it further.
Sample Code:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
<input id="click" type="button" value="click me"/>
$(document).ready(function(){
var option = '<option value="1">testrtu1</option><option value="2">testrtu2</option><option value="3">testtsi</option><option value="4">testrtu3</option>';
$("input#click").click(function(){
var selInx = $("select[name='ProgramId'] option:selected").index();
$('#ProgramId').html(option);
$('select#ProgramId').prop('selectedIndex', selInx);
});
});
DEMO FIDDLE
NOTE: As we cannot connect to your backend code to get options hardcoded in code itself and on click of button dropdown will be replaced with latest options and will update the selected index based on first one. You can use either selectedindex or text based on your requirement.

JQuery select2 set default value from an option in list?

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.
One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :
Markup
<select class="select2">
<option id="foo">Some Text</option>
<option id="bar" selected="selected">Other Text</option>
</select>
JavaScript
$('select').select2(); //oh yes just this!
See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:
$('select').select2("val", null); //a lil' bit more :)
After this, it is simple enough to set val to "Whatever You Want".
The above solutions did not work for me, but this code from Select2's own website did:
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed
Webpage found here
Hope this helps for anyone who is struggling, like I was.
$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
One way to accomplish this is...
$('select').select2().select2('val', $('.select2 option:eq(1)').val());
So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".
<select class=".select2">
<option id="foo">Some Text</option>
<option id="bar">Other Text</option>
</select>
Hope this is useful to someone else.
For 4.x version
$('#select2Id').val(__INDEX__).trigger('change');
to select value with INDEX
$('#select2Id').val('').trigger('change');
to select nothing (show placeholder if it is)
Came from the future? Looking for the ajax source default value ?
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
You're welcome.
Reference:
https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2
Step 1: You need to append one blank option with a blank value in your select tag.
Step 2: Add data-placeholder attribute in select tag with a placeholder value
HTML
<select class="select2" data-placeholder='--Select--'>
<option value=''>--Select--</option>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
</select>
jQuery
$('.select2').select2({
placeholder: $(this).data('placeholder')
});
OR
$('.select2').select2({
placeholder: 'Custom placeholder text'
});
e.g.
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
you can see it here https://select2.org/programmatic-control/add-select-clear-items
Don't know others issue, Only this code worked for me.
$('select').val('').select2();
Normally we usually use active but in select2, changes to selected="selected"
Example using Python/Flask
HTML:
<select id="role" name="role[]" multiple="multiple" class="js-example-basic-multiple form-control">
{% for x in list%}
<option selected="selected" value="{{x[0]}}">{{x[1]}}</option>
{% endfor %}
</select>
JQuery:
$(document).ready(function() {
$('.js-example-basic-multiple').select2();
});
$(".js-example-theme-multiple").select2({
theme: "classic",
placeholder: 'Select your option...'
});
It's easy. For example I want to select option with value 2 in default:
HTML:
<select class="select2" id="selectBox">
<option value="1">Some Text</option>
<option value="2">Other Text</option>
</select>
Javascript:
$("#selectBox").val('2').trigger('change')
$('select').select2("val",null);
If you are using an array data source you can do something like below -
$(".select").select2({
data: data_names
});
data_names.forEach(function(name) {
if (name.selected) {
$(".select").select2('val', name.id);
}
});
This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.
For ajax select2 multiple select dropdown i did like this;
//preset element values
//topics is an array of format [{"id":"","text":""}, .....]
$(id).val(topics);
setTimeout(function(){
ajaxTopicDropdown(id,
2,location.origin+"/api for gettings topics/",
"Pick a topic", true, 5);
},1);
// ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

Categories

Resources