How to select an option of a slim select with jquery - javascript
I have some concatenated selects that work fine. By the way, I would like to convert those selects into slim selects but I found some difficulties in doing that.
For example, I have a select with ID level_incarico.
When I select an option of level_incarico greater than zero other selects should appear.
After that, when I change an option of a concatenated select for example in select_nazione, the option change correctly.
But when I select another time the option zero in level_incarico and the I select another time an option greater than zero in level_incarico appears another time the select select_nazione with the option already selected previously.
This is my javascript code:
$("#level_incarico").change(function(){
var option_selected = $('option:selected', this).attr('value');
document.getElementById('level_incarico_selected').value = option_selected;
if (option_selected > 0) {
$('.nazione').css('display','block');
$('.regione').css('display','none');
$('.provincie').css('display','none');
$('.comune').css('display','none');
$('.altro_nazione').css('display','none');
$("#select_regione").val(0);
$("#select_provincia").val(0);
$("#select_comune").val(0);
$("#select_nazione").val(0);
$("#altro_input_nazioni").val("");
} else {
$('.nazione').css('display','none');
$('.regione').css('display','none');
$('.provincie').css('display','none');
$('.comune').css('display','none');
$('.altro_nazione').css('display','none');
$("#select_nazione").val(0); //here
$("#select_regione").val(0);
$("#select_provincia").val(0);
$("#select_comune").val(0);
$("#altro_input_nazioni").val("");
}
});
This is how I create the selects:
new SlimSelect({
select: '#select_nazione'
})
new SlimSelect({
select: '#level_incarico'
})
In other words, the reset of the selected options $("#select_nazione").val(0); does not work correctly. It works with normal selects, but not with slim select.
Here how I fill in level_incarico:
echo "<select id='level_incarico' name='level_incarico'>";
echo "<option></option>";
echo "<option value='0' " . (($ra_level == 0 && $id > 0) ? 'selected' : '') . " >Mondiale</option>";
echo "<option value='1' " . (($ra_level == 1 && $id > 0) ? 'selected' : '') . " >Nazionale</option>";
echo "<option value='2' " . (($ra_level == 2 && $id > 0) ? 'selected' : '') . " >Regionale</option>";
echo "<option value='3' " . (($ra_level == 3 && $id > 0) ? 'selected' : '') . " >Provinciale</option>";
echo "<option value='4' " . (($ra_level == 4 && $id > 0) ? 'selected' : '') . " >Comunale</option>";
echo "</select>";
Here how I fill in select_nazione:
echo "<select id='select_nazione' name='select_nazione' required>";
echo "<option value='0'>Seleziona...</option>";
while($row = $result->fetch_assoc())
{
$nazione_id_val=intval($row['country_id']);
$nazione_nome_val=$row['country_name'];
if($ra_level > 0) {
if ($nazione_id_val == $id_nazione)
{
$selected = "selected" ;
} else {
$selected = "" ;
}
}
echo"<option value='$nazione_id_val' $selected>$nazione_nome_val</option>";
}
echo "</select>";
Can help?
Why do you have an else for the values that are all 0
Why do you have display none in both branches?
Would this help you? I got the code from the manual
const $slimNazione = new SlimSelect({
select: '#select_nazione',
onChange: (info) => {
console.log(info.value)
}
})
const $slimIncario = new SlimSelect({
select: '#level_incarico',
onChange: (info) => {
console.log(info.value)
const val = +info.value;
$('.nazione').toggle(val > 0);
$('.regione').hide();
$('.provincie').hide();
$('.comune').hide();
$('.altro_nazione').hide();
$slimNazione.set('0')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slim-select/1.27.0/slimselect.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slim-select/1.27.0/slimselect.css"/>
<select id='select_nazione' name='select_nazione'>
<option value="0">Seleziona...</option>
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
</select>
<select id='level_incarico' name='level_incarico'>
<option></option>
<option value='0'>Mondiale</option>
<option value='1'>Nazionale</option>
<option value='2'>Regionale</option>
<option value='3'>Provinciale</option>
<option value='4'>Comunale</option>
</select>
slim-select is built without jQuery...on purpose. If you have jQuery (and plan on keeping it in your stack), I would recommend using select2 instead. slim-select is a great library and has a smaller foot print due to not being dependent on jQuery. But, select2...dare I say...is better. Or, at least has more convenience features. I found select2 easier to use, but my desire to cut out jQuery led me to adopt slim-select.
Related
Uncheck checkbox when certain values(php) from drop down is chosen
i need to uncheck a checkbox when a value is chosen from multi dropdown. The problem is the value is a php value which is generate from foreach. below is the code of the javascript $("#multi_search_filter").on('change', function () { var val = $(this).val(); if (val === <?php"'.$row['batch_name'].'" ?>) { $('#checkUncheckAll').prop('checked', false); return; } $('#checkbox1').prop('checked', true); }); this is the code of the PHP and HTML <select name="multi_search_filter" id="multi_search_filter" multiple class="form-control selectpicker"> <?php foreach($result as $row) { echo '<option value="'.$row["batch_id"].'">'.$row["batch_name"].'</option>'; } ?> </select> this is the input checkbox <input type="checkbox" id="checkUncheckAll"> I tried to search for solution but failed to do so. Appreciate any help
Limiting the options in a combobox, based on the selected one
I made a similar question yesterday, but couldn't come up with a solution since then, so i went and refined my code a bit to a logic that seemed more plausible to work. However, it didn't. I want to have only a couple of options in a combobox available to the user, depending on what option was pre-selected. Here is the Combobox: <SELECT class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus onchange= "StatusTest(); hideField();" > <option selected></option> <option value="Planned" id="optionPlanned" <?php if ($row['task_status']=='Planned') echo 'selected="selected"';?>>Planned</option> <option value="Started" id="Started" <?php if ($row['task_status']=='Started') echo 'selected="selected"';?>>Started</option> <option value="Available" id="Available" <?php if ($row['task_status']=='Available') echo 'selected="selected"';?>>Available</option> <option value="Finished" id="Finished" <?php if ($row['task_status']=='Finished') echo 'selected="selected"';?>>Finished</option> <option value="Impeded" id="Impeded" <?php if ($row['task_status']=='Impeded') echo 'selected="selected"';?>>Impeded</option> </SELECT> For example, when "Planned" is selected, the only other available option should be "Started". So i went and made a Javascript, for a Onchange Event, like so: function hideField(){ var e = document.getElementById("cbostatus"); var strUser = e.options[e.selectedIndex].value; if( strUser == 'Planned' ) { document.getElementById("Impeded").style.display = 'none'; document.getElementById("Available").style.display = 'none'; document.getElementById("Finished").style.display = 'none'; } } And for some reason, it is wrong. Any ideas? (Also, i'd aprecciate if you didn't suggest using Jquery, as i have never used before and don't really have time to learn for this)
I suggest you start with an empty select, and add the options dynamically. var e=document.getElementById("cbostatus"); var strUser = 'Planned'; // get this value from somewhere, maybe a hidden field if( strUser == 'Planned' ) { e.options[e.length]=new Option("Planned", "optionPlanned", true, true); e.options[e.length]=new Option("Started", "Started"); } else if ..
Use this code. Html <select class=caixas id=cbostatus style="WIDTH: 3cm;" tabIndex=25 name=cbostatus> <option selected></option> </select> jQuery var insertoption = ""; first add options in ready function $(document).ready(function() { insertoption += "<option value='Planned' id='Planned'>Planned</option>"; insertoption += "<option value='Started' id='Started'>Started</option>"; insertoption += "<option value='Available' id='Available'>Available</option>"; insertoption += "<option value='Finished' id='Finished'>Finished</option>"; insertoption += "<option value='Impeded' id='Impeded'>Impeded</option>"; $("#cbostatus").append(insertoption); insertoption = ""; }); This is create your option and now create onchange function $("#cbostatus").on("change",function() { if($("#cbostatus").val() == "Planned") { $("#cbostatus").children().remove(); insertoption = "<option value='Started' id='Started'>Started</option>"; $("#cbostatus").append(insertoption); } });
Reset a dynamic dropdown back to initial state
I have an ajax dynamic dropdown form that onchange changes a second dropdown based on the firsts selection. However, if someone were to reset the form, all elements get cleared except for the dynamic one. I made a reset button function that does: $('#myForm')[0].reset(); However it doesn't reset the dynamic dropdown. Then I added $('#state').prop('selectedIndex',0); which only then selects the initial subitem. Essentially I want it to go back to the default <option value="">State/Province</option> state that was there prior to becoming dynamic and I cannot figure out how to exactly to do this. I am very very new and used previous questions and google to even get me this far. Thanks Update: This is what I need reset: <select name="state" class="dropdown" id="state"> <option value="">State/Province</option> <!-- this is populated by ajax --> </select> This form changes the above: <select name="country" class="dropdown" id="country" onchange="getStates();"> <option value="">Select Country</option> <?php $con = mysql_connect($db_host, $db_user, $db_pass); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db('earth'); $query = "select id,country from regions order by country"; $result = mysql_query($query); while ( $row = mysql_fetch_object( $result ) ) { ?> <option value=<?php echo $row->id; ?>><?php echo $row->country;?> </option> <?php } mysql_free_result($result); ?> </select> Additional code: function getStates() { $('#state').html(''); var e = document.getElementById("country"); var countryID = e.options[e.selectedIndex].value; $.ajax({ type: "POST", url: "getStates.php", data: {countryID:countryID}, dataType:'json', //success: function(result){ success: function(data){ var toAppend = ''; $.each(data,function(i,o){ toAppend += '<option value=' +o.id + '>' + o.name + '</option>'; }); $('#state').append(toAppend); }, }); } function reset_select_box(selector, default_value) { if(typeof default_value !== 'string') default_value = ""; var select_box = $(document).find(selector), children = select_box.children(); console.log(children); for(var i in children){ if(children[i].value === ""){ select_box.prop('selectedIndex', i); } } }; function resetForm() { // since the form is dynamic, reset form does not reset the states $('#frmSigGen')[0].reset(); }
This seems to do the trick: function resetForm() { $('#frmSigGen')[0].reset(); $('#state').empty(); $('#state').append('<option value="">State/Province</option'); }
Maybe try looping through the select elements children looking for the default value? var reset_select_box = function(selector, default_value){ if(typeof default_value !== 'string') default_value = ""; var select_box = $(document).find(selector), children = select_box.children(); console.log(children); for(var i in children){ if(children[i].value === ""){ select_box.prop('selectedIndex', i); } } }; <html> <head> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script> </head> <body> <select id="test"> <option value="">Default</option> <option value="1">option 1</option> <option value="2">option 2</option> <option value="3">option 3</option> <option value="4">option 4</option> <option value="5">option 5</option> </select> <button type="button" onclick="reset_select_box('#test');">Reset</button> </body> </html>
You could mark the newests options adding a particular data tag, i.e. data-toreset. Then, when you need to reset, remove only options with that tag. The newest options: <option data-toreset="1"></option> The JQuery script could be like: $('*[data-toreset="1"]').remove(); And then you could select the first element of your combo.
Javascript to hide selected option
I have this code to hide selected options: function connect() { $(".selectbox option").show(); $(".selectbox").each(function(i) { var obj = $(".selectbox option[value='" + $(this).val() + "']"); if($(this).val() != "") obj.hide(); }); } function to() { $(".selectboxes option").show(); $(".selectboxes").each(function(i) { var obj = $(".selectboxes option[value='" + $(this).val() + "']"); if($(this).val() != "") obj.hide(); }); } but my problem now is that, I use PHP to generate the select tag, and in that php code i have a condition that once it sees this value it will automatically add selected=selected. but my JS would still display that variable in the drop down even though it is already selected. i tried adding: $('.selectboxes option:selected').find("option").hide(); but it did not work. any idea on how should i solve this problem? BTW: i forgot to mention that, the php code will generate multiple select tags with the same values that will use that function, thus when i have 3 select tags 1 will have the pre selected value and the other 2 will be null, now when i click on either 2 of those that have no values selected yet i can still see in the drop down the choice that was already pre selected in select 1, what i wanted to do is that it should be automatically hidden, with that function it will not hide it until i select other choices from the drop down. since this line: $(".selectbox option").show(); would display all choices in the drop down, is there a condition for it to exempt "this" value? SELECT PART: for($z=0;$z<$rows_updatedrow;$z++) { ?> <select id = "sc" name = "connect_array[]" class="input-select selectbox" onchange = "connect()"> <option value = "">--Select--</option> <?php for($zz=0;$zz<$rows_getconnect;$zz++) { $data_getconnect = mysql_fetch_assoc($query_getconnect); $field_name_getconnect[] = $data_getconnect['field_name']; $field_display_getconnect[] = $data_getconnect['field_display']; $field_type_getconnect[] = $data_getconnect['field_type']; if((($field_name_getconnect[$zz] == "friends_name" && $connect == 2) || $field_type_getconnect[$zz] == "email") && $z == 0){ $selected = "selected=selected"; }else{ $selected = ""; } ?> <option value = "<?php echo $field_name_getconnect[$zz]; ?>" <?php echo $selected; ?>><?php echo $field_display_getconnect[$zz]; ?></option> <?php } ?> </select> connect to <br/> <?php } ?> </div> <div class = "right"> <?php for($a=0;$a<$rows_updatedrow;$a++) { ?> <select name = "to_array[]" class="input-select selectboxes" onchange = "to()"> <option class = "option" value = "">--Select--</option> <?php for($aa=0;$aa<$rows_getto;$aa++) { $data_getto = mysql_fetch_assoc($query_getto); $field_name_getto[] = $data_getto['field_name']; $field_display_getto[] = $data_getto['field_display']; $field_type_getto[] = $data_getto['field_type']; if((($field_name_getto[$aa] == "friends_name" && $to == 2) || $field_type_getto[$aa] == "email") && $a == 0){ $selected = "selected=selected"; }else{ $selected = ""; } ?> <option class = "option" value = "<?php echo $field_name_getto[$aa]; ?>" <?php echo $selected; ?>><?php echo $field_display_getto[$aa]; ?></option> <?php } thank you
You already have the selected option in your selector - no need to find option - as that will return you an empty array $('.selectboxes option:selected').hide(); // get rid of .find('option') To exempt this value.. I'm guessing you're referring to the selected value.. you can use :not as undefined stated $(".selectbox option:not(:selected)").show(); You can take out the inline onChange since you are using jQuery.. and bind the change event handler to the select elements on dom ready $(function(){ $('select').change(function(){ var $sel = $('option:selected'); // get all selected options $('option').show(); // show all options $sel.each(function(i,v){ // loop through selected options var $index = $(v).index(); // get index of selected option $('select').not($(this).parent()).each(function(){ // loop through other select - not current one if($index != 0){ // not default index $(this).find('option').eq($index).hide(); // hide selected option in other dropdowns } }); }); }).change(); // <-- trigger change right away }); http://jsfiddle.net/VE7jA/
$('.selectboxes option:selected').find("option").hide(); You are trying to find('option') inside option.. Try this $('.selectboxes option:selected').hide(); You can also remove the element once and for all if you are using it again.. $('.selectboxes option:selected').remove(); To remove a option based on value you can try $('.selectboxes option[value="0"]').remove() ; // Removes option with value 0
As it's been said, you're trying to find an option within an option, so you'll have to get rid of the .find call. Apart from that, hiding <option> elements do not work cross-browser, so you'll have to remove the options instead, and add them back when necessary. There are several ways to manage that, all involving storing the full list of options in a variable (as an array, an object, or even HTML string).
Hiding option elements is not always supported. A more idiomatic approach would be to disable it. obj.prop("disabled", true); Or simplify it like this. $(".selectbox option:selected").prop("disabled", true); Or this. $(".selectbox").each(function() { this.options[this.selectedIndex].disabled = true; });
Sort table by selected value
I have an online rugby game and I want to make a page where users have displayed in a table with only one column player name. If they select something from the dropdown list (speed, kicking, etc), the players are sorted based on what user selected. Here is what I tried to do: <script type="text/javascript"> var arr_head = ['name','age','ss','experience','leadership','weight','height','stamina','strength','breakthroughs','tackling,'handling','speed','kicking']; var arr_ord = ['asc','asc','desc','desc','desc','desc','desc','desc','desc','desc','desc','desc','desc','desc']; var arr_players = new Array(); var col = 0; // the array bellow is generated with a function: $arr_players = player_list($teamid); arr_players[0] = ['Bruce Ewing',20,151,2,3,84,182,21,22,21,23,24,23,17]; arr_players[1] = ['Barbu Frates',18,113,2,3,105,185,3,99,3,1,2,3,2]; arr_players[2] = ['Costi Buhaescu',24,116,2,1,95,198,2,99,2,3,4,4,2]; arr_players[3] = ['Corneliu Kirita',20,113,1,1,88,183,1,99,2,4,2,4,1]; arr_players[4] = ['Cristi Stelea',23,116,2,4,93,197,2,99,2,4,4,4,1]; arr_players[5] = ['Codrin Sarapatin',23,115,2,5,103,200,3,99,2,4,1,3,3]; arr_players[6] = ['Cosmin Tadici',19,113,1,5,99,203,2,99,2,1,2,4,3]; arr_players[7] = ['Dudu Dumea',21,115,1,5,87,179,2,99,3,3,2,4,2]; arr_players[8] = ['Dorian Hizo',24,115,1,4,98,195,4,99,3,2,1,3,3]; arr_players[9] = ['Ernest Cazacu',18,113,2,5,93,193,2,99,3,1,1,3,4]; arr_players[10] = ['Emil Siman',18,115,1,2,88,187,4,99,2,3,2,1,4]; arr_players[11] = ['Grigorie Banciu',20,116,2,5,102,198,3,99,2,4,2,4,2]; arr_players[12] = ['Horea Profis',19,112,2,5,104,185,3,99,2,2,3,1,2]; arr_players[13] = ['Iuliu Alexandrescu',19,112,1,4,99,174,3,99,1,2,4,1,2]; arr_players[14] = ['Ionut Halipa',20,117,2,4,87,171,2,99,4,4,2,1,5]; arr_players[15] = ['Ioan Ogasanu',20,120,1,5,85,198,4,99,4,4,3,3,3]; arr_players[16] = ['Larie Lozovan',19,115,1,5,102,180,3,99,4,4,2,1,2]; arr_players[17] = ['Mugur Buscan',20,114,1,3,93,192,2,99,1,2,2,3,5]; arr_players[18] = ['Nicusor Lucescu',22,113,2,4,94,193,4,99,2,2,2,3,1]; arr_players[19] = ['Olimpu Plesu',25,117,1,4,90,177,3,99,1,3,2,4,5]; arr_players[20] = ['Razvan Corlatean',23,112,1,1,92,194,1,99,2,3,4,1,2]; arr_players[21] = ['Sorin Halmageanu',21,115,1,4,101,193,2,99,2,2,2,3,5]; arr_players[22] = ['Sebi Ioanovici',21,116,1,3,104,179,2,99,4,3,2,3,3]; arr_players[23] = ['Titu Baldovin',25,113,2,2,100,185,2,99,3,3,2,2,2]; function sortMultiDimensional(a,b) { if (arr_ord[col] == 'asc') return ((a[col] < b[col]) ? -1 : ((a[col] > b[col]) ? 1 : 0)); else return ((a[col] > b[col]) ? -1 : ((a[col] < b[col]) ? 1 : 0)); } function sort_arr(crit) { for (i=0; i<arr_head.length; i++) { if (arr_head[i] == crit ) { col = i; arr_players.sort(sortMultiDimensional); } } var tbl = document.getElementById('players').getElementsByTagName('tr'); for (i=0; i<arr_players.length; i++) { linie = i + 2; tbl[linie].getElementsByTagName('td')[1].innerHTML = arr_players[i][1]; } } </script> <table id="players" border="0" width="100%"> <tr> <th style="text-align: center;"><?php echo $text['PLAYERS']; ?></th> </tr> <tr> <td> <select onchange="sort_arr(this.options[selectedIndex].value)"> <option></option> <option value="name"><?php echo $text['NAME']; ?></option> <option value="age"><?php echo $text['AGE']; ?></option> <option value="ss"><?php echo $text['SS']; ?></option> <option value="experience"><?php echo $text['EXPERIENCE']; ?></option> <option value="leadership"><?php echo $text['LEADERSHIP']; ?></option> <option value="weight"><?php echo $text['WEIGHT']; ?></option> <option value="height"><?php echo $text['HEIGHT']; ?></option> <option value="stamina"><?php echo $text['STAMINA']; ?></option> <option value="strength"><?php echo $text['STRENGTH']; ?></option> <option value="breakthroughs"><?php echo $text['BREAKTHROUGHS']; ?></option> <option value="tackling"><?php echo $text['TACKLING']; ?></option> <option value="handling"><?php echo $text['HANDLING']; ?></option> <option value="speed"><?php echo $text['SPEED']; ?></option> <option value="kicking"><?php echo $text['KICKING']; ?></option> </select> </td> </tr> <tbody> <?php for($i=0; $i<count($arr_players); $i++) { ?> <tr><td><?php echo $arr_players[$i][1]; ?></td></tr> <?php } ?> </tbody> </table> But it doesn't work. What is wrong?
I would highly recommend an off-the-shelf solution like the jQuery plugin http://www.datatables.net/
The [1]'s from the original version of the line below needs to be [0] (as shown). Arrays in javascript are zero-based, the first element is 0, not 1. There is only one cell in the table rows so I think you want the first (only) one. The 2nd one (for getting the element from the player array) I am guessing you also want to use the first element (the name). tbl[linie].getElementsByTagName('td')[0].innerHTML = arr_players[i][0]; This error was easily found when I put this (as much as possible) in a fiddle here: http://jsfiddle.net/TeAGw/5/ Did you try to debug this at all? If you had simply looked at the error message reported by the browser when it "did not work" you should have been able to instantly determine the cause of this error. All three major web browsers now have integrated debugging tools, I recommend using them.