Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent a select from being changed? [closed]

I want to prevent a select from being changed when a specific condition is satisfied without disabling the select element.

like image 240
Saeed Avatar asked Dec 24 '12 09:12

Saeed


People also ask

How do you detect change in select?

There are two events that detect changes to input , textarea , and select elements: change and input . The change event feels like it would be the right one, but it only fires when focus leaves the field. To detect real-time changes, you want the input event.

How do you avoid changing select box value if you say no to confirm?

First of all onfocus is called. This event keeps the current value in a attribute "PrvSelectedValue". Secondly onchange is called, we set the previous value if user cancel the confirmation popup. return false is used to prevent the postback in ASP.NET.

How do you make a select box invisible?

The hidden attribute hides the <option> element. You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <option> element is not visible, but it maintains its position on the page.

Can you style options in select?

Styling the option partSeveral CSS properties can be used to change the appearance of an option, and some properties applied to the <select> element are inherited too. For example, it's possible to change the color and font of the <option> elements to match your website's appearance.


4 Answers

Try this: JSBin Demo

<select id="mySelect" data-value="" onfocus="this.setAttribute('data-value', this.value);" 
onchange="this.value = this.getAttribute('data-value');">
like image 90
Akhil Sekharan Avatar answered Sep 27 '22 02:09

Akhil Sekharan


You can hold last changed value of select and reassign it when you do not want use to change the select under your condition.

Live Demo

Html

<select id="select">
   <option>1</option>
   <option>2</option>
   <option>3</option>
</select>​

Javascript

preval = $('#select').val();
$('#select').change(function() {
    if ($(this).val() == "2") {  $(this).val(preval); return;}
    preval = ($(this).val();    
});​
like image 32
Adil Avatar answered Sep 25 '22 02:09

Adil


old_value = $('#select :selected').val();
$('#select').change(function() {
  if($(this).val() == 'option 3') {//your specific condition
     $('#select').val(old_value);
  } else {
    old_value = $('#select :selected').val();
  }
});

demo

like image 38
Vimalnath Avatar answered Sep 24 '22 02:09

Vimalnath


Example of what you want to do

var select = $('select'), option = $('whatyouwanttotest');
if (option.val() == 'value') {
  select.attr('disabled', 'disabled');
} else {
  select.removeAttr('disabled');
}
like image 21
Nadeem Khedr Avatar answered Sep 26 '22 02:09

Nadeem Khedr