Related
I'm having a problem in Chrome with the following:
var items = $("option", obj);
items.each(function(){
$(this).click(function(){
// alert("test");
process($(this).html());
return false;
});
});
The click event doesn't seem to fire in Chrome, but works in Firefox.
I wanna be able to click on a option element from a combo, if I do instead another kind of element, lets say <li> it works fine. Any ideas? Thanks.
I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:
$("select#yourSelect").change(function(){
process($(this).children(":selected").html());
});
We can achieve this other way despite of directly calling event with <select>.
JS part:
$("#sort").change(function(){
alert('Selected value: ' + $(this).val());
});
HTML part:
<select id="sort">
<option value="1">View All</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
<option value="4">Last Modified</option>
<option value="5">Ranking</option>
<option value="6">Reviewed</option>
</select>
The easy way to change the select, and update it is this.
// BY id
$('#select_element_selector').val('value').change();
another example:
//By tag
$('[name=selectxD]').val('value').change();
another example:
$("#select_element_selector").val('value').trigger('chosen:updated');
I've had simmilar issue. change event was not good for me because i've needed to refresh some data when user clicks on option. After few trials i've got this solution:
$('select').on('click',function(ev){
if(ev.offsetY < 0){
//user click on option
}else{
//dropdown is shown
}
});
I agree that this is very ugly and you should stick with change event where you can, but this solved my problem.
I found that the following worked for me - instead on using on click, use on change e.g.:
jQuery('#element select').on('change', (function() {
//your code here
}));
<select id="myselect">
<option value="0">sometext</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
</select>
$('#myselect').change(function() {
if($('#myselect option:selected').val() == 0) {
...
}
else {
...
}
});
Looking for this on 2018.
Click event on option tag, inside a select tag, is not fired on Chrome.
Use change event, and capture the selected option:
$(document).delegate("select", "change", function() {
//capture the option
var $target = $("option:selected",$(this));
});
Be aware that $target may be a collection of objects if the select tag is multiple.
I use a two part solution
Part 1 - Register my click events on the options like I usually would
Part 2 - Detect that the selected item changed, and call the click
handler of the new selected item.
HTML
<select id="sneaky-select">
<option id="select-item-1">Hello</option>
<option id="select-item-2">World</option>
</select>
JS
$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });
$("#sneaky-select").change(function ()
{
$("#sneaky-select option:selected").click();
});
What usually works for me is to first change the value of the dropdown, e.g.
$('#selectorForOption').attr('selected','selected')
and then trigger the a change
$('#selectorForOption').changed()
This way, any javascript that is wired to
Maybe one of the new jquery versions supports the click event on options. It worked for me:
$(document).on("click","select option",function() {
console.log("nice to meet you, console ;-)");
});
UPDATE: A possible usecase could be the following: A user sends a html form and the values are inserted into a database. However one or more values are set by default and you flag this automated entries. You also show the user that his entry is generated automatically, but if he confirm the entry by clicking on the already selected option you change the flag in the database. A rare sue case, but possible...
I know that this code snippet works for recognizing an option click (at least in Chrome and FF). Furthermore, it works if the element wasn't there on DOM load. I usually use this when I input sections of inputs into a single select element and I don't want the section title to be clicked.
$(document).on('click', 'option[value="disableme"]', function(){
$('option[value="disableme"]').prop("selected", false);
});
Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use
$('#yourSelect option:selected').html();
You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.
$ ('#yourSelect' ).change(() => {
process($('#yourSelect option:selected').html());
});
If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()
Workaround:
$('#select_id').on('change', (function() {
$(this).children(':selected').trigger('click');
}));
I have several select boxes on a page, and basically anytime an onchange event occurs with any of those boxes I want to use the same piece of code instead of making a separate script for each select box's id. The reason is that I could be ending up with dozens of these select boxes on a page and all that repeated code just gets messy.
<select name="drop_list_menu_1" id="drop_list_menu_1">
<option value="letter:a">A</option>
<option value="letter:b">B</option>
<option value="letter:c">C</option>
</select>
<select name="drop_list_menu_2" id="drop_list_menu_2">
<option value="letter:a">A</option>
<option value="letter:b">B</option>
<option value="letter:c">C</option>
</select>
<select name="drop_list_menu_3" id="drop_list_menu_3">
<option value="letter:a">A</option>
<option value="letter:b">B</option>
<option value="letter:c">C</option>
</select>
My code to handle the onchange event:
<script type="text/javascript">
$(document).ready(function () {
// if user chooses an option from the select box...
$("#drop_list_menu_1").change(function () {
//doin some stuff
});
</script>
So, how can I get this:
$("#drop_list_menu_1").change(function () {
//doin some stuff
});
to catch any of the select boxes on the page being used? Something incorporating a regex?
Give the elements a common class (you can keep the id attributes if you want) and then use delegation:
$(document).on("change", "your-select-class", function() {
var changedElement = this;
// ...
});
You just need that one call to set up the event handler, and it'll work for as many copies as you need on the page.
You could use jQuery's attribute starts-with selector to select all drop-downs whose name begins with "drop_list_menu_":
$("select[name^='drop_list_menu_']").change(function(){
//doin some stuff
});
Assign same class to each Select and call it as below.
$(".ClassName").change(function (e) {
var SelectId = e.target.id
});
simple as that
$("select").change(function () {
alert('a');
});
Is it possible to auto submit a select menu when the selection changes without using a button to submit the form. I have four of these on my page and using a button for each uses up too much space. By Select Menu, I mean:
<select name="something" class="something" title="something something">
<option selected="selected">Option One</option>
<option >Option Two</option>
</select>
I would also like to add a confirm popup for the on change event. The following is what I use for buttons but it does not work for the select menu.
onclick="return confirm('do you haz teh codz?');"
Any link to articles tutorials or examples would be greatly appreciated!
Thanks
This is more appropriately tagged 'javascript' since it's javascript that you'll use to do it.
Add an 'onchange' event to the select. In the example below, 'form' should be substituted for your favourite method of targeting the form node.
<select name="something" class="something" title="something something" onchange="form.submit()">
<option selected="selected">Option One</option>
<option >Option Two</option>
</select>
You need a JavaScript solution, not a PHP solution. PHP can only handle form data after it's been sent to the server; i.e., when the form has been submitted.
You can use JavaScript to:
Add an event listener to the <select> to trigger when it changes (onchange).
When the <select> changes, get its current value.
Based on the value, redirect the user (change window.location) to the page you want them to go to.
Edit: I re-read your question and if you are just looking to submit the form when the user changes the <select>, then mwotton's answer is probably the way to go. (Of course, move the JavaScript away from the HTML; it doesn't belong there.)
For your confirmation, you can do something like this:
document.getElementById('my-select').onchange = function(){
return confirm('do you haz teh codz?');
});
(It's always a good idea to keep your JavaScript away from your HTML. So just give your <select> an ID like id="my-select" and you can access it from the JavaScript. You can also use a JavaScript library like jQuery to greatly ease your JavaScript programming.)
Well, you need to know the form name/id or something. Assuming <form id="selectform"> and <select id="selectelement">,
window.onload=function() {
document.getElementById('selectelement').change = function() {
if(confirm('do you haz teh codz?'))
document.getElementById('selectform').submit();
else
return false;
return true;
}
}
The return false/true will determine whether or not to revert the select back to the original option.
Here's a test: http://jsfiddle.net/yrqcj/2/
You can implement the onchange event for select object and inside the function make a reference to the form.submit();
I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,
<select onChange="javascript:doSomething();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Now, doSomething() only gets triggered when the selection changes.
I want to trigger doSomething() when the user selects any option, possibly the same one again.
I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.
So, is there a way to trigger a function on every select by the user?
Update:
The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!
I needed something exactly the same. This is what worked for me:
<select onchange="doSomething();" onfocus="this.selectedIndex = -1;">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Supports this:
when the user selects any option, possibly the same one again
Here is the simplest way:
<select name="ab" onchange="if (this.selectedIndex) doSomething();">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
Works both with mouse selection and keyboard Up/Down keys whes select is focused.
I had the same problem when I was creating a design a few months back. The solution I found was to use .live("change", function()) in combination with .blur() on the element you are using.
If you wish to have it do something when the user simply clicks, instead of changing, just replace change with click.
I assigned my dropdown an ID, selected, and used the following:
$(function () {
$("#selected").live("change", function () {
// do whatever you need to do
// you want the element to lose focus immediately
// this is key to get this working.
$('#selected').blur();
});
});
I saw this one didn't have a selected answer, so I figured I'd give my input. This worked excellently for me, so hopefully someone else can use this code when they get stuck.
http://api.jquery.com/live/
Edit: Use the on selector as opposed to .live. See jQuery .on()
Just an idea, but is it possible to put an onclick on each of the <option> elements?
<select>
<option onclick="doSomething(this);">A</option>
<option onclick="doSomething(this);">B</option>
<option onclick="doSomething(this);">C</option>
</select>
Another option could be to use onblur on the select. This will fire anytime the user clicks away from the select. At this point you could determine what option was selected. To have this even trigger at the correct time, the onclick of the option's could blur the field (make something else active or just .blur() in jQuery).
If you really need this to work like this, I would do this (to ensure it works by keyboard and mouse)
Add an onfocus event handler to the select to set the "current" value
Add an onclick event handler to the select to handle mouse changes
Add an onkeypress event handler to the select to handle keyboard changes
Unfortunately the onclick will run multiple times (e.g. on onpening the select... and on selection/close) and the onkeypress may fire when nothing changes...
<script>
function setInitial(obj){
obj._initValue = obj.value;
}
function doSomething(obj){
//if you want to verify a change took place...
if(obj._initValue == obj.value){
//do nothing, no actual change occurred...
//or in your case if you want to make a minor update
doMinorUpdate();
} else {
//change happened
getNewData(obj.value);
}
}
</script>
<select onfocus="setInitial(this);" onclick="doSomething();" onkeypress="doSomething();">
...
</select>
The onclick approach is not entirely bad but as said, it will not be triggered when the value isn't changed by a mouse-click.
It is however possible to trigger the onclick event in the onchange event.
<select onchange="{doSomething(...);if(this.options[this.selectedIndex].onclick != null){this.options[this.selectedIndex].onclick(this);}}">
<option onclick="doSomethingElse(...);" value="A">A</option>
<option onclick="doSomethingElse(..);" value="B">B</option>
<option onclick="doSomethingElse(..);" value="Foo">C</option>
</select>
I know this question is very old now, but for anyone still running into this problem, I have achieved this with my own website by adding an onInput event to my option tag, then in that called function, retrieving the value of that option input.
<select id='dropdown' onInput='myFunction()'>
<option value='1'>1</option>
<option value='2'>2</option>
</select>
<p>Output: </p>
<span id='output'></span>
<script type='text/javascript'>
function myFunction() {
var optionValue = document.getElementById("dropdown").value;
document.getElementById("output").innerHTML = optionValue;
}
</script>
Going to expand on jitbit's answer. I found it weird when you clicked the drop down and then clicked off the drop down without selecting anything. Ended up with something along the lines of:
var lastSelectedOption = null;
DDChange = function(Dd) {
//Blur after change so that clicking again without
//losing focus re-triggers onfocus.
Dd.blur();
//The rest is whatever you want in the change.
var tcs = $("span.on_change_times");
tcs.html(+tcs.html() + 1);
$("span.selected_index").html(Dd.prop("selectedIndex"));
return false;
};
DDFocus = function(Dd) {
lastSelectedOption = Dd.prop("selectedIndex");
Dd.prop("selectedIndex", -1);
$("span.selected_index").html(Dd.prop("selectedIndex"));
return false;
};
//On blur, set it back to the value before they clicked
//away without selecting an option.
//
//This is what is typically weird for the user since they
//might click on the dropdown to look at other options,
//realize they didn't what to change anything, and
//click off the dropdown.
DDBlur = function(Dd) {
if (Dd.prop("selectedIndex") === -1)
Dd.prop("selectedIndex", lastSelectedOption);
$("span.selected_index").html(Dd.prop("selectedIndex"));
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Dd" onchange="DDChange($(this));" onfocus="DDFocus($(this));" onblur="DDBlur($(this));">
<option>1</option>
<option>2</option>
</select>
<br/>
<br/>Selected index: <span class="selected_index"></span>
<br/>Times onchange triggered: <span class="on_change_times">0</span>
This makes a little more sense for the user and allows JavaScript to run every time they select any option including an earlier option.
The downside to this approach is that it breaks the ability to tab onto a drop down and use the arrow keys to select the value. This was acceptable for me since all the users click everything all the time until the end of eternity.
To properly fire an event every time the user selects something(even the same option), you just need to trick the select box.
Like others have said, specify a negative selectedIndex on focus to force the change event. While this does allow you to trick the select box, it won't work after that as long as it still has focus. The simple fix is to force the select box to blur, shown below.
Standard JS/HTML:
<select onchange="myCallback();" onfocus="this.selectedIndex=-1;this.blur();">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
jQuery Plugin:
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script type="text/javascript">
$.fn.alwaysChange = function(callback) {
return this.each(function(){
var elem = this;
var $this = $(this);
$this.change(function(){
if(callback) callback($this.val());
}).focus(function(){
elem.selectedIndex = -1;
elem.blur();
});
});
}
$('select').alwaysChange(function(val){
// Optional change event callback,
// shorthand for $('select').alwaysChange().change(function(){});
});
</script>
You can see a working demo here.
first of all u use onChange as an event handler and then use flag variable to make it do the function u want every time u make a change
<select
var list = document.getElementById("list");
var flag = true ;
list.onchange = function () {
if(flag){
document.bgColor ="red";
flag = false;
}else{
document.bgColor ="green";
flag = true;
}
}
<select id="list">
<option>op1</option>
<option>op2</option>
<option>op3</option>
</select>
This may not directly answer your question, but this problem could be solved by simple design level adjustments. I understand this may not be 100% applicable to all use-cases, but I strongly urge you to consider re-thinking your user flow of your application and if the following design suggestion can be implemented.
I decided to do something simple than hacking alternatives for onChange() using other events that were not really meant for this purpose (blur, click, etc.)
The way I solved it:
Simply pre-pend a placeholder option tag such as select that has no value to it.
So, instead of just using the following structure, which requires hack-y alternatives:
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
Consider using this:
<select>
<option selected="selected">Select...</option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
So, this way, your code is a LOT more simplified and the onChange will work as expected, every time the user decides to select something other than the default value. You could even add the disabled attribute to the first option if you don't want them to select it again and force them to select something from the options, thus triggering an onChange() fire.
At the time of this answer, I'm writing a complex Vue application and I found that this design choice has simplified my code a lot. I spent hours on this problem before I settled down with this solution and I didn't have to re-write a lot of my code. However, if I went with the hacky alternatives, I would have needed to account for the edge cases, to prevent double firing of ajax requests, etc. This also doesn't mess up the default browser behaviour as a nice bonus (tested on mobile browsers as well).
Sometimes, you just need to take a step back and think about the big picture for the simplest solution.
Add an extra option as the first, like the header of a column, which will be the default value of the dropdown button before click it and reset at the end of doSomething(), so when choose A/B/C, the onchange event always trigs, when the selection is State, do nothing and return. onclick is very unstable as many people mentioned before. So all we need to do is to make an initial button label which is different as your true options so the onchange will work on any option.
<select id="btnState" onchange="doSomething(this)">
<option value="State" selected="selected">State</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
function doSomething(obj)
{
var btnValue = obj.options[obj.selectedIndex].value;
if (btnValue == "State")
{
//do nothing
return;
}
// Do your thing here
// reset
obj.selectedIndex = 0;
}
Actually, the onclick events will NOT fire when the user uses the keyboard to change the selection in the select control. You might have to use a combination of onChange and onClick to get the behavior you're looking for.
The wonderful thing about the select tag (in this scenario) is that it will grab its value from the option tags.
Try:
<select onChange="javascript:doSomething(this.value);">
<option value="A">A</option>
<option value="B">B</option>
<option value="Foo">C</option>
</select>
Worked decent for me.
2022 VANILLA JAVASCRIPT
...because this is a top hit on Google.
Original Poster did NOT ask for a JQuery solution, yet all answers ONLY demonstrate JQuery or inline SELECT tag event.
Use an event listener with the 'change' event.
const selectDropdown = document.querySelector('select');
selectDropdown.addEventListener('change', function (e) { /* your code */ });
... or call a seperate function:
function yourFunc(e) { /* your code here */ }
const selectDropdown = document.querySelector('select');
selectDropdown.addEventListener('change', yourFunc);
What I did when faced with a similar Problem is I added an 'onFocus' to the select box which appends a new generic option ('select an option'or something similar) and default it as the selected option.
So my goal was to be able to select the same value multiple times which essentially overwrites the the onchange() function and turn it into a useful onclick() method.
Based on the suggestions above I came up with this which works for me.
<select name="ab" id="hi" onchange="if (typeof(this.selectedIndex) != undefined) {alert($('#hi').val()); this.blur();}" onfocus="this.selectedIndex = -1;">
<option value="-1">--</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
http://jsfiddle.net/dR9tH/19/
Kindly note that Event Handlers are not supported for the OPTION tag on IE, with a quick thinking..I came up with this solution, try it and give me your feedback:
<script>
var flag = true;
function resetIndex(selObj) {
if(flag) selObj.selectedIndex = -1;
flag = true;
}
function doSomething(selObj) {
alert(selObj.value)
flag = false;
}
</script>
<select onchange="doSomething(this)" onclick="resetIndex(this)">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
What I'm doing here actually is resetting the select index so that the onchange event will be triggered always, true that you we lose the selected item when you click and it maybe annoying if your list is long, but it may help you in someway..
use jquery:
<select class="target">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<script>
$('.target').change(function() { doSomething(); });
</script>
Here's my solution, completely different to any else on here. It uses the mouse position to figure out if an option was clicked as oppose to clicking on the select box to open the dropdown. It makes use of the event.screenY position as this is the only reliable cross browser variable. A hover event has to be attached first so it can figure out the controls position relative to the screen before the click event.
var select = $("select");
var screenDif = 0;
select.bind("hover", function (e) {
screenDif = e.screenY - e.clientY;
});
select.bind("click", function (e) {
var element = $(e.target);
var eventHorizon = screenDif + element.offset().top + element.height() - $(window).scrollTop();
if (e.screenY > eventHorizon)
alert("option clicked");
});
Here is my jsFiddle
http://jsfiddle.net/sU7EV/4/
you should try using option:selected
$("select option:selected").click(doSomething);
What works for me:
<select id='myID' onchange='doSomething();'>
<option value='0' selected> Select Option </option>
<option value='1' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > A </option>
<option value='2' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > B </option>
</select>
In that way, onchange calls 'doSomething()' when the option changes, and
onclick calls 'doSomething()' when onchange event is false, in other words, when you select the same option
Try this (event triggered exactly when you select option, without option changing):
$("select").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
alert('selected');
}
$(this).data("isopen", !open);
});
http://jsbin.com/dowoloka/4
The one True answer is to not use the select field (if you need to do something when you re-select same answer.)
Create a dropdown menu with conventional div, button, show/hide menu. Link: https://www.w3schools.com/howto/howto_js_dropdown.asp
Could have been avoided had one been able to add event listeners to options. If there had been an onSelect listener for select element. And if clicking on the select field didn't aggravatingly fire off mousedown, mouseup, and click all at the same time on mousedown.
<script>
function abc(selectedguy) {
alert(selectedguy);
}
</script>
<select onchange="abc(this.selectedIndex);">
<option>option one</option>
<option>option two</option>
</select>
Here you have the index returned, and in the js code you can use this return with one switch or anything you want.
Try this:
<select id="nameSelect" onfocus="javascript:document.getElementById('nameSelect').selectedIndex=-1;" onchange="doSomething(this);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
A long while ago now but in reply to the original question, would this help ?
Just put onClick into the SELECT line.
Then put what you want each OPTION to do in the OPTION lines.
ie:
<SELECT name="your name" onClick>
<option value ="Kilometres" onClick="YourFunction()">Kilometres
-------
-------
</SELECT>
<select name="test[]"
onchange="if(this.selectedIndex < 1){this.options[this.selectedIndex].selected = !1}">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
I had faced a similar need and ended up writing a angularjs directive for the same -
guthub link - angular select
Used element[0].blur(); to remove the focus off the select tag. Logic is to trigger this blur on second click of the dropdown.
as-select gets triggered even when user selects the same value in the dropdown.
DEMO - link
There are a few things you want to do here to make sure it remembers older values and triggers an onchange event even if the same option is selected again.
The first thing you want is a regular onChange event:
$("#selectbox").on("change", function(){
console.log($(this).val());
doSomething();
});
To have the onChange event trigger even when the same option is selected again, you can unset selected option when the dropdown receives focus by setting it to an invalid value. But you also want to store the previously selected value to restore it in case the user does not select any new option:
prev_select_option = ""; //some kind of global var
$("#selectbox").on("focus", function(){
prev_select_option = $(this).val(); //store currently selected value
$(this).val("unknown"); //set to an invalid value
});
The above code will allow you to trigger onchange even if the same value is selected. However, if the user clicks outside the select box, you want to restore the previous value. We do it on onBlur:
$("#selectbox").on("blur", function(){
if ($(this).val() == null) {
//because we previously set an invalid value
//and user did not select any option
$(this).val(prev_select_option);
}
});
According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled.
The only problem is that disabled HTML form inputs don't get included in the POST / GET data.
What's the best way to emulate the readonly attribute for a select tag, and still get the POST data?
You should keep the select element disabled but also add another hidden input with the same name and value.
If you reenable your SELECT, you should copy its value to the hidden input in an onchange event and disable (or remove) the hidden input.
Here is a demo:
$('#mainform').submit(function() {
$('#formdata_container').show();
$('#formdata').html($(this).serialize());
return false;
});
$('#enableselect').click(function() {
$('#mainform input[name=animal]')
.attr("disabled", true);
$('#animal-select')
.attr('disabled', false)
.attr('name', 'animal');
$('#enableselect').hide();
return false;
});
#formdata_container {
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<form id="mainform">
<select id="animal-select" disabled="true">
<option value="cat" selected>Cat</option>
<option value="dog">Dog</option>
<option value="hamster">Hamster</option>
</select>
<input type="hidden" name="animal" value="cat"/>
<button id="enableselect">Enable</button>
<select name="color">
<option value="blue" selected>Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>
<input type="submit"/>
</form>
</div>
<div id="formdata_container" style="display:none">
<div>Submitted data:</div>
<div id="formdata">
</div>
</div>
We could also disable all except the selected option.
This way the dropdown still works (and submits its value) but the user can not select another value.
Demo
<select>
<option disabled>1</option>
<option selected>2</option>
<option disabled>3</option>
</select>
You can re-enable the select object on submit.
EDIT: i.e., normally disabling the select tag (with the disabled attribute) and then re-enabling it automatically just before submiting the form:
Example with jQuery:
To disable it:
$('#yourSelect').prop('disabled', true);
To re-enable it before submission so that GET / POST data is included:
$('#yourForm').on('submit', function() {
$('#yourSelect').prop('disabled', false);
});
In addition, you could re-enable every disabled input or select:
$('#yourForm').on('submit', function() {
$('input, select').prop('disabled', false);
});
another way of doing a readOnly attribute to a select element is by using css
you could do like :
$('#selection').css('pointer-events','none');
DEMO
Simple jQuery solution
Use this if your selects have the readonly class
jQuery('select.readonly option:not(:selected)').attr('disabled',true);
Or this if your selects have the readonly="readonly" attribute
$('select[readonly="readonly"] option:not(:selected)').attr('disabled',true);
<select id="countries" onfocus="this.defaultIndex=this.selectedIndex;" onchange="this.selectedIndex=this.defaultIndex;">
<option value="1">Country1</option>
<option value="2">Country2</option>
<option value="3">Country3</option>
<option value="4">Country4</option>
<option value="5">Country5</option>
<option value="6">Country6</option>
<option value="7" selected="selected">Country7</option>
<option value="8">Country8</option>
<option value="9">Country9</option>
</select>
Tested and working in IE 6, 7 & 8b2, Firefox 2 & 3, Opera 9.62, Safari 3.2.1 for Windows and Google Chrome.
I know that it is far too late, but it can be done with simple CSS:
select[readonly] option, select[readonly] optgroup {
display: none;
}
The style hides all the options and the groups when the select is in readonly state, so the user can not change his selection.
No JavaScript hacks are needed.
Simple CSS solution:
select[readonly]{
background: #eee;
cursor:no-drop;
}
select[readonly] option{
display:none;
}
This results in Select to be gray with nice "disable" cursor on hover
and on select the list of options is "empty" so you can not change its value.
Easier still:
add the style attribute to your select tag:
style="pointer-events: none;"
Yet another more contemporary option (no pun intended) is to disable all the options of the select element other then the selected one.
note however that this is an HTML 4.0 feature
and ie 6,7,8 beta 1 seem to not respect this.
http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/OptionDisabledSupport.html
This is the best solution I have found:
$("#YourSELECTIdHere option:not(:selected)").prop("disabled", true);
The code above disables all other options not selected while keeping the selected option enabled. Doing so the selected option will make it into the post-back data.
A bit late to the party. But this seems to work flawlessly for me
select[readonly] {
pointer-events:none;
}
[SIMPLEST SOLUTION]
Since the OP specifically asked that he does not want to disable the select element, here is what i use to make a select readonly
In html
<select style="pointer-events: none;" onclick="return false;" onkeydown="return false;" ></select>
THAT's IT
Explanation
setting pointer-events to none disables the editing of the "select-element" with mouse/cursor events
setting the onclick & onkeydown functions to return false disables the editing of the "select-element" with keyboard
This way you don't have to create any extra element, or disable/re-enable the element with javascript or messing with form-submission logic, or use any third party library.
Plus you can easily add css-styling like setting backgrouns-color to grey or text color to grey to imply that element is readonly. I haven't added that to code, since that is pretty specific to your site-theme
Or if you want to do it via javascript
let isReadOnly = true ;
selectElement.onclick = function () {
return !isReadOnly ;
};
selectElement.onkeydown =function(){
return !isReadOnly ;
} ;
selectElement.style.pointerEvents = isReadOnly ? "none" : "all" ;
Set the select disabled when you plan for it to be read-only and then remove the disabled attribute just before submitting the form.
// global variable to store original event/handler for save button
var form_save_button_func = null;
// function to get jQuery object for save button
function get_form_button_by_id(button_id) {
return jQuery("input[type=button]#"+button_id);
}
// alter value of disabled element
function set_disabled_elem_value(elem_id, value) {
jQuery("#"+elem_id).removeAttr("disabled");
jQuery("#"+elem_id).val(value);
jQuery("#"+elem_id).attr('disabled','disabled');
}
function set_form_bottom_button_save_custom_code_generic(msg) {
// save original event/handler that was either declared
// through javascript or html onclick attribute
// in a global variable
form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.6
//form_save_button_func = get_form_button_by_id('BtnSave').prop('onclick'); // jQuery 1.7
// unbind original event/handler (can use any of following statements below)
get_form_button_by_value('BtnSave').unbind('click');
get_form_button_by_value('BtnSave').removeAttr('onclick');
// alternate save code which also calls original event/handler stored in global variable
get_form_button_by_value('BtnSave').click(function(event){
event.preventDefault();
var confirm_result = confirm(msg);
if (confirm_result) {
if (jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").length > 0) {
jQuery("form.anyForm").find('input[type=text], textarea, select').filter(".disabled-form-elem").removeAttr("disabled");
}
// disallow further editing of fields once save operation is underway
// by making them readonly
// you can also disallow form editing by showing a large transparent
// div over form such as loading animation with "Saving" message text
jQuery("form.anyForm").find('input[type=text], textarea, select').attr('ReadOnly','True');
// now execute original event/handler
form_save_button_func();
}
});
}
$(document).ready(function() {
// if you want to define save button code in javascript then define it now
// code below for record update
set_form_bottom_button_save_custom_code_generic("Do you really want to update this record?");
// code below for new record
//set_form_bottom_button_save_custom_code_generic("Do you really want to create this new record?");
// start disabling elements on form load by also adding a class to identify disabled elements
jQuery("input[type=text]#phone").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("input[type=text]#fax").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("select#country").addClass('disabled-form-elem').attr('disabled','disabled');
jQuery("textarea#address").addClass('disabled-form-elem').attr('disabled','disabled');
set_disabled_elem_value('phone', '123121231');
set_disabled_elem_value('fax', '123123123');
set_disabled_elem_value('country', 'Pakistan');
set_disabled_elem_value('address', 'address');
}); // end of $(document).ready function
In addition to disabling the options that should not be selectable i wanted to actually make them dissapear from the list, but still be able to enable them should i need to later:
$("select[readonly]").find("option:not(:selected)").hide().attr("disabled",true);
This finds all select elements with a readonly attribute, then finds all options inside those selects that are not selected, then it hides them and disables them.
It is important to separate the jquery query in 2 for performance reasons, because jquery reads them from right to left, the code:
$("select[readonly] option:not(:selected)")
will first find all unselected options in the document and then filter those that are inside selects with a readonly attribute.
This is the simplest and best solution.
You will set a readolny attr on your select, or anyother attr like data-readonly, and do the following
$("select[readonly]").live("focus mousedown mouseup click",function(e){
e.preventDefault();
e.stopPropagation();
});
Solution with tabindex. Works with select but also text inputs.
Simply use a .disabled class.
CSS:
.disabled {
pointer-events:none; /* No cursor */
background-color: #eee; /* Gray background */
}
JS:
$(".disabled").attr("tabindex", "-1");
HTML:
<select class="disabled">
<option value="0">0</option>
</select>
<input type="text" class="disabled" />
Edit: With Internet Explorer, you also need this JS:
$(document).on("mousedown", ".disabled", function (e) {
e.preventDefault();
});
If you disable a form field, this won't be sent when form is submitted.
So if you need a readonly that works like disabled but sending values do this :
After any change in readonly properties of an element.
$('select.readonly option:not(:selected)').attr('disabled',true);
$('select:not([readonly]) option').removeAttr('disabled');
One simple server-side approach is to remove all the options except the one that you want to be selected. Thus, in Zend Framework 1.12, if $element is a Zend_Form_Element_Select:
$value = $element->getValue();
$options = $element->getAttrib('options');
$sole_option = array($value => $options[$value]);
$element->setAttrib('options', $sole_option);
Following on from Grant Wagners suggestion; here is a jQuery snippet that does it with handler functions instead of direct onXXX attributes:
var readonlySelect = function(selector, makeReadonly) {
$(selector).filter("select").each(function(i){
var select = $(this);
//remove any existing readonly handler
if(this.readonlyFn) select.unbind("change", this.readonlyFn);
if(this.readonlyIndex) this.readonlyIndex = null;
if(makeReadonly) {
this.readonlyIndex = this.selectedIndex;
this.readonlyFn = function(){
this.selectedIndex = this.readonlyIndex;
};
select.bind("change", this.readonlyFn);
}
});
};
What I found works great, with plain javascript (ie: no JQuery library required), is to change the innerHTML of the <select> tag to the desired single remaining value.
Before:
<select name='day' id='day'>
<option>SUN</option>
<option>MON</option>
<option>TUE</option>
<option>WED</option>
<option>THU</option>
<option>FRI</option>
<option>SAT</option>
</select>
Sample Javascript:
document.getElementById('day').innerHTML = '<option>FRI</option>';
After:
<select name='day' id='day'>
<option>FRI</option>
</select>
This way, no visiual effect change, and this will POST/GET within the <FORM>.
input being your <select> element:
input.querySelectorAll(':not([selected])').forEach(option => {
option.disabled = true
})
This will keep the select in the data (as it's not disabled) and only the option that are not selected are disabled, therefore not selectable.
The result is a readable select that cannot be changed (=> read only).
Rather than the select itself, you could disable all of the options except for the currently selected option. This gives the appearance of a working drop-down, but only the option you want passed in is a valid selection.
If the select dropdown is read-only since birth and does not need to change at all, perhaps you should use another control instead? Like a simple <div> (plus hidden form field) or an <input type="text">?
Added: If the dropdown is not read-only all the time and JavaScript is used to enable/disable it, then this is still a solution - just modify the DOM on-the-fly.
I resolved it with jquery:
$("select.myselect").bind("focus", function(){
if($(this).hasClass('readonly'))
{
$(this).blur();
return;
}
});
html solution:
<select onfocus="this.blur();">
javascript ones:
selectElement.addEventListener("focus", selectElement.blur, true);
selectElement.attachEvent("focus", selectElement.blur); //thanks, IE
to remove:
selectElement.removeEventListener("focus", selectElement.blur, true);
selectElement.detachEvent("focus", selectElement.blur); //thanks, IE
edit: added remove methods
In IE I was able to defeat the onfocus=>onblur approach by double-clicking.
But remembering the value and then restoring it in the onchange event seems to handle that issue.
<select onfocus="this.oldvalue=this.value;this.blur();" onchange="this.value=this.oldvalue;">
....
</select>
You can do similar without expando properties by using a javascript variable.
If you are using jquery validate, you can do the following below, I used the disabled attribute without a problem:
$(function(){
$('#myform').validate({
submitHandler:function(form){
$('select').removeAttr('disabled');
form.submit();
}
});
});
<select id="case_reason" name="case_reason" disabled="disabled">
disabled="disabled" ->will get your value from database dan show it in the form.
readonly="readonly" ->you can change your value in selectbox, but your value couldn't save in your database.
What's the best way to emulate the readonly attribute for a select
tag, and still get the POST data?
Just make it an input/text field and add the 'readonly' attribute to it. If the select is effectively 'disabled', then you can't change the value anyway, so you don't need the select tag, and you can simply display the "selected" value as a readonly text input. For most UI purposes I think this should suffice.