How to make html <select> element look like

2020-02-09 06:01发布

When I'm disabling a

<select name="sel" disabled>
    <option>123</option>
</select>

element, it doesnt pass its variable.

What to do to look it like disabled, but be in "normal" state?

This is because I have a list of "selects", and sometimes some of them have single value, so user should understand that it has only one value without clicking it.

8条回答
贼婆χ
2楼-- · 2020-02-09 06:13

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.

$('#myForm').submit(function() {
    $('select').removeAttr('disabled');
});

Note that if you rely on this method, you'll want to disable it programmatically as well, because if JS is disabled or not supported, you'll be stuck with the disabled select.

$(document).ready(function() {
    $('select').attr('disabled', 'disabled');
});
查看更多
Luminary・发光体
3楼-- · 2020-02-09 06:14

Add a class .disabled and use this CSS:

​.disabled {border: 1px solid #999; color: #333; opacity: 0.5;}
.disabled option {color: #000; opacity: 1;}​

Demo: http://jsfiddle.net/ZCSRq/

查看更多
走好不送
4楼-- · 2020-02-09 06:18

If you can supply a default value for your selects, then you can use the same approach for unchecked check boxes which requires a hidden input before the actual element, as these don't post a value if left unchecked:

<input type="hidden" name="myfield" value="default" />
<select name="myfield">
    <option value="default" selected="selected">Default</option>
    <option value="othervalue">Other value</option>
    <!-- ... //-->
</select>

This will actually post the value "default" (without quotes, obviously) if the select is disabled by javascript (or jQuery) or even if your code writes the html disabling the element itself with the attribute: disabled="disabled".

查看更多
女痞
5楼-- · 2020-02-09 06:18

One could use an additional hidden input element with the same name and value as that of the disabled list. This will ensure that the value is passed in $_POST variables.

Eg:

<select name="sel" disabled><option>123</select>
<input type="hidden" name="sel" value=123>

查看更多
家丑人穷心不美
6楼-- · 2020-02-09 06:22
<select id="test" name="sel">
  <option disabled>1</option>
  <option disabled>2</option>
</select>   

or you can use jQuery

$("#test option:not(:selected)").prop("disabled", true);
查看更多
三岁会撩人
7楼-- · 2020-02-09 06:24

if you don't want add the attr disabled can do it programmatically

can disable the edition into the <select class="yourClass"> element with this code:

//bloqueo selects
  //block all selects
  jQuery(document).on("focusin", 'select.yourClass', function (event) {
    var $selectDiabled = jQuery(this).attr('disabled', 'disabled');
    setTimeout(function(){ $selectDiabled.removeAttr("disabled"); }, 30);
  });

if you want try it can see it here: https://jsfiddle.net/9kjqjLyq/

查看更多
登录 后发表回答