简体   繁体   中英

How to disable a select box not inside a form?

I can't seem to be able to disable a select box when the select tag is not nested inside a form tag. Some things I tried are (using Firefox 3): (via Jquery)

$("#mySelect").attr("disabled", true);
$("#mySelect").attr("disabled", "disabled");

(also)

document.getElementById('mySelect').disabled = true;
document.getElementById('mySelect').disabled = true;

Here is the HTML:

<select id="mySelect" onchange="updateChoice();">
<option value="1">First</option>
<option value="2" selected="">Second</option>
</select>

Must I have this select box inside a form element?

Short answer: No, you don't need to have the select box within a form.

Where is your JavaScript currently included with respect to the body tag in your HTML? Remember that if you have inline JavaScript included in the head if your page, then it will fire as the page is loaded. At this point, the select box will not have been parsed and, thus, your code cannot access it in order to disable it.

I'm no fan of mixing JavaScript and markup together, but this demo should work for all intents and purposes.

<html>
 <head>
  <title>JavaScript Select Demo</title>
 </head>
 <body>
    <select id="mySelect" onchange="updateChoice();">
        <option value="1">First</option>
        <option value="2" selected="">Second</option>
    </select>
 </body>
 <script type="text/javascript">
     document.getElementById('mySelect').disabled = true;
 </script>
</html>

If, for whatever reason, you have to keep the script located in the page rather than an external file, you could setup an event handler to perform the same functionality after the page has loaded. Rather than keeping code at the bottom of the markup, you can include this in your head node:

 <head>
  <title>JavaScript Select Demo</title>
  <script type="text/javascript">
    window.onload = function() {
        document.getElementById('mySelect').disabled = true; ;
    }
 </script>
 </head>

Lastly, rather than incorporate an onchange handler in the attributes of your markup, you could alternatively setup an event handler in your JavaScript to perform the same behavior. jQuery makes this really easy .

When using the jQuery library, make sure the code you write is always enclosed in the $.ready function:

$(function () {
    //Type in your code here
});

This makes sure that the code you write will be executed once the page has finished loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM