I'm using php to select data from my database. I'm displaying it in a HTML select option tag. I have 100+ options and I want to hide which is the same as my selected data. For example:
<select class="form-control" id="type" name="type" required>
<option selected value='<?php echo $type; ?>'><?php echo $type; ?></option> // for example $type == "c"
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
For example the $type variable is "c". So it displays the option "c" twice. How can I easily hide always the one that I need if I have 100+ option values?
Manually remove all duplicate option tags with JavaScript and jQuery
let values = []
$("option").each((index, item) => {
let { value } = item //item.value is the value of our current option in the loop
// check if value is already in values array
if(values.includes(value)) {
// delete duplicate from the DOM
item.remove()
} else {
// push value to values array so that duplicates can be detected later on
values.push(value)
}
})
console.log(values)
<select class="form-control" id="type" name="type" required>
<option selected value="c">c</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Alternative solution
If your given options a, b, c, d are always the same you could setup a „blacklist“ in your PHP code and only echo out the html option element if it‘s not in this blacklist. Is this a possible solution for you?
Related
I need to map to an array the selected options inside select element (multiple selection is enable).
Here is the html:
<select id="listado" size="5" multiple>
<option value="Leer" id="aficion-leer">Leer</option>
<option value="Programar" id="aficion-programar">Programar</option>
<option value="Cine" id="aficion-cine">Cine</option>
<option value="Deporte" id="aficion-deporte">Deporte</option>
</select>
I tried this:
Array.from(document.querySelector("#listado")).map(elemento => elemento.value); which returns every option. According to this answer, adding option:checked to the query param should do the trick, but I get an empty list.
Any idea on what the reason might be?
You can use document.querySelectorAll and only select options that are checked, then map them.
let options=[...document.querySelectorAll("#listado option:checked")].map(elemento => elemento.value)
console.log(options)
<select id="listado" size="5" multiple>
<option value="Leer" id="aficion-leer">Leer</option>
<option value="Programar" id="aficion-programar" selected>Programar</option>
<option value="Cine" id="aficion-cine">Cine</option>
<option value="Deporte" id="aficion-deporte" selected>Deporte</option>
</select>
Have you tried this?
console.log(
Array.from(document.querySelector("#listado").childNodes).filter(elemento => elemento.selected).map(elemento => elemento.value) // this line
);
<select id="listado" size="5" multiple>
<option value="Leer" id="aficion-leer">Leer</option>
<option value="Programar" id="aficion-programar" selected>Programar</option> <!-- selected for demo -->
<option value="Cine" id="aficion-cine">Cine</option>
<option value="Deporte" id="aficion-deporte">Deporte</option>
</select>
Or through example, how can one retrieve "c" via JavaScript or jQuery no matter if the user changed it?
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
I tried the following, however, it returns the value of the currently selected menu. I suppose I can take a similar approach which runs upon page load and save the value, but expect there is a more "proper" way to do so.
$('#select-menu > option').each(function(i){
if(this.selected) {
console.log(this.value)
$("#submit").val(this.value);
return false;
}
})
Use jQuery .attr() to get initial value:
function get_initial(){
$('#select-menu > option').each(function(i){
if($(this).attr('selected')) {
console.log('initial: ' + this.value)
}
if(this.selected) {
console.log('current: ' + this.value)
}
})
}
$('.initial').on('click', get_initial);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
<button class="initial">check initial</button>
There is no better way. A select is meant to be user-modifiable.
If you want to retain the original value you could save it on load:
$(document).ready(function() {
var initialValue = $("#select-menu").val();
});
You could also write it in a hidden input:
<input type="hidden" name="initial-select-menu" value="c">
This way has the benefit that the value will be submitted along with the rest of the form. Might be preferable in some cases.
Or you could stuff that initial value in a data attribute:
<select id="select-menu" data-initial="c">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
You could save the value on an html5 data-* attribute:
<select id="select-menu" data-default="c">
And get it with
$("#select-menu").attr("data-default");
The following code exhibits various examples related to getting of values from select fields using JavaScript.
Working Snippet
const selectMenu = document.getElementById("select-menu");
var selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
/*Option 1*/
selectMenu.onchange = function() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}
/*Option 2*/
/*selectMenu.addEventListener("change", function(){
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
})*/
/*Option 3*/
/*function updateSelectedIndex() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}*/
document.writeln(selectedIndex);
<!-- Option 3 -->
<!-- <select id="select-menu" onchange="updateSelectedIndex"> -->
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
Try this for the appropriate cases:
let preselectedOption = $(targetDropDown).find('option[selected]');
let currentOption = $(targetDropDown).find('option:selected');
Need to retrieve selected item from the select element using javascript.
<select id="selected">
<option value="Default Request" selected disabled>Default Request Service</option>
<option value="1">Anti-Virus Support and Services</option>
<option value="2">CSB - Request and Report Forms</option>
<option value="3">Email Support and Services</option>
<option value="4">Hardware Support and Services</option>
</select>
<input id="selected_display" type="text" value="" name="subject">
solution for you is in next code. You got 2 functions. First is for get value or text of selected item. second is used for set value to input
you have to add listener on on select tag and wait for change of the selected option
Enjoy!
function getOption(selector) {
return {
val: $(selector + ' option:selected').attr('value'),
text: $(selector + ' option:selected').text()
}
};
function setItem(toSelector, value) {
jQuery(toSelector).val(value);
}
var output;
jQuery('#selected').on('change', function(){
output = getOption('#selected');
setItem('#selected_display', output.val); //change to output.text to show text of selected output
});
https://jsfiddle.net/v4fwxeeu/3/
Maybe you want to try it with PHP:
<form Name="xxxx" class="xxxx" method="post" Action="xxxx">
<select id="selected" Name="selected>
<option value="Default Request" selected disabled>Default Request Service</option>
<option value="1">Anti-Virus Support and Services</option>
<option value="2">CSB - Request and Report Forms</option>
<option value="3">Email Support and Services</option>
<option value="4">Hardware Support and Services</option>
</select>
</form>
With PHP you can get the value of "selected" with:
<?php
$selected = $_POST['selected'];
echo $selected;
?>
In my html form i have 9 drop down values which if user action is Edit then it will fetch the values from database and return in the jsonencode format.as below,
JSON DATA
[{"ed_gender":"Male","ed_blood_group":"A-","ed_marital_status":"Single","ed_branch_id":"11","ed_desig_id":"1","ed_job_type":"Permanent","ed_pay_mode":"Cheque"}]
HTML
<select name="ed_gender" class="form-control">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select name="ed_marital_status" class="form-control">
<option value="">Select</option>
<option value="Single">Single</option>
<option value="Married">Married</option>
</select>
I tried few lines of code using php its actually works but i am trying using javascript.
PHP
<select name="ed_marital_status" class="form-control">
<option value="">Select</option>
<option <?php if($ed_marital_status=="Single") echo 'selected="selected"'; ?> value="Single">Single</option>
<option <?php if($ed_marital_status=="Married") echo 'selected="selected"'; ?> value="Married">Married</option>
</select>
So here Behave i have to extract the json values and make dropdown values has "Selected" on page loads.
EDITED :
JSON DATA
[{"ed_branch_id":"11","ed_desig_id":"1"}]
HTML
<select name="ed_job_location" class="form-control">
<option value="">Select</option>
<?php
foreach($get_branches as $branches){
$branches_id = $branches->b_id;
$branches_name = $branches->b_name;
$branches_code = $branches->b_code;
echo "<option value='$branches_id||$branches_name||$branches_code'>$branches_name</option>";
}?>
</select>
<select name="ed_desig_id" class="form-control">
<option value="">Select</option>
<?php
foreach($get_designation as $designations){
$designations_id = $designations->d_id;
$designations_name = $designations->d_designation;
$designations_code = $designations->d_code;
echo "<option value='$designations_id||$designations_code'>$designations_name</option>";
}?>
</select>
Here from above json, i am getting only branch id and desig id, But here i have value with || symbol in the select option, so i need to find particular id and show it in the drop down.
Iterate through the array of json objects and fill each element value by selecting it through its name:
var json = [{"ed_gender":"Male","ed_blood_group":"A-","ed_marital_status":"Single","ed_branch_id":"11","ed_desig_id":"1","ed_job_type":"Permanent","ed_pay_mode":"Cheque"}];
$(document).ready(function(){
$.each(json[0], function(index, element) {
$("[name="+index + "]").val(element);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="ed_gender" class="form-control">
<option value="">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select name="ed_marital_status" class="form-control">
<option value="">Select</option>
<option value="Single">Single</option>
<option value="Married">Married</option>
</select>
EDIT:
You can explicitly set the values to cover the special case of branch values concatenation with || outside the loop, as long as the values are within the json data returned :
$(document).ready(function(){
$("[name=ed_job_location]").val(json[0].branches_id + "||" + json[0].branches_name + "||" + json[0].branches_code);
});
When change value my page is refresh because i have to send value to query data
but my selector doesn't show value when selected
<form name='active' action='' method='GET'>
<select class="form-control" id="section" name="section" onchange="list()" >
<option value="0"> - - Select All - - </option>
<?php
$section = $db->fetch();
foreach ($section as $key => $v) {
$section_name = $v['section'];
echo "<option value='".$section_name."'>",$section_name,"</option>";
}
?>
<script type="text/javascript">
function list(){
document.active.submit();
}
</script>
For an option in a dropdown other than the first one to be selected on page load, you have to add the selected="selected" attribute to one of the <option> elements like so :
<select class="form-control" id="section" name="section" onchange="list()" >
<option value="0"> - - Select All - - </option>
<option value="1" selected="selected"> I'm selected </option>
<option value="2"> I'm not selected </option>
</select>
In your case, it implies checking either the GET variable or the database value in your foreach loop to set the attribute accordingly.