Limiting the options in a combobox, based on the selected one - javascript

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);
}
});

Related

How to select an option of a slim select with jquery

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.

creating a dynamic select field upon selecting another select field

This is my main page where I select a option field.
opt1.php:
<html>
<div>
<select id="mn" onchange = "show(this.id)" >
<option value="3">hello</option>
<option value="4">hiii</option>
<option value="5">byee</option>
</select>
</div>
<?php include 'OPT2.php'?>
</html>
This is my javascript where I get the value from above select and pass to opt2.php
function show(s1){
var s1 = document.getElementById(s1);
var ch = s1.value;
$.post('OPT2.php', {variable: ch});
}
This is my opt2.php page to display the sub select.
<?php
$con = #$_POST['ch'];
echo "SELECT MODEL:<select id=sb name=sb >";
echo "<option name=$con>$con</option>";
echo "</select>";
?>
Actually this is not generating the intended result.
Is there any logical or processing mistake?
you need to make ajax call to opt2.php to get that data
so your opt1.php should look like
<html>
<div>
<select id="s1" onchange = "show(this.id)" >
<option value="3">hello</option>
<option value="4">hiii</option>
<option value="5">byee</option>
</select>
<select id="s2">
<option>--</option>
</select>
</div>
<?php include 'OPT2.php'?>
</html>
and your javascript
<script type="text/javascript">
$("#s1").change(function(){
$('#s2').find('option').remove().end(); //clear the city ddl
var block_no = $(this).find("option:selected").text();
var s1 = document.getElementById(s1);
var ch = s1.value;
//do the ajax call
$.ajax({
url:'OPT2.php',
type:'GET',
data:{variable:s1},
dataType:'json',
cache:false,
success:function(data)
{
//data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('s2');
for(var c=0;c<data.length;c++)
{
var option = document.createElement('option');
option.value = data[c];
option.text = data[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert("Pls Reload the page");
}
});
});

How to get the correct selected value in Select HTML from javascript?

I get users from mysql query. I show this users into table and add a HTML into php file to all users to change a value:
...
do {
echo "<td > <a>".$row["username"]."</a> </td> \n";
echo "<td > <a>".$row["name"]."</a> </td> \n";
echo "<td > <select id='sel'> <option value='admin'>Admin</option> <option value='user'>User</option> </select> </td> \n";
} while ($row = mysql_fetch_array($result));
echo "</tbody></table> \n";
...
How can I get the option selected??
I'm trying get this in javascript but always get the same first value, independet value selected.
function myFunction() {
var e = document.getElementById("sel");
var strUser = e.options[e.selectedIndex].value;
}
Thanks!
Use the jquery .change function.
Fiddle :- https://jsfiddle.net/a2abaL44/1/
<script type="text/javascript">
$("#sel").change(function(){
var selectVal = $(this).val();
})
</script>
https://api.jquery.com/change/
Because your loop will be executed multiple times (once for each user in the database), you will have many <select> elements with the same ID. You cannot have the same ID given to many different elements, and this is why your JavaScript is only returning the value of the first <select>.
If you tell me what you are needing the selected value for, I can update the answer further.
Your code is fine, Change your select to <select id="sel" onchange="myFunction();">
<script type="text/javascript">
function myFunction() {
var e = document.getElementById("sel");
var strUser = e.options[e.selectedIndex].value;
alert(strUser);
}
</script>

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.

How do I programmatically set the value of a select box element using JavaScript?

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

Categories

Resources