How to automatically set the size of a drop-down l

2019-07-09 14:07发布

问题:

I'm trying to write a script in Greasemonkey that will automatically set the size of Drop-down lists (there can be more than one...) on the number of selection options, but with my limited JavaScript knowledge I don't really know how to do this.

Example of subject:

<select name="z_pos_id">
<option value="2463">Option A</option>
<option value="2609">Option B</option>
<option value="3013">Option C</option>
</select>

<select name="z_pos_id">
<option value="140">Option AA</option>
<option value="3038">Option AB</option>
<option value="3519">Option AC</option>
<option value="2645">Option AD</option>
</select>

Example of desired Output:

<select size="3" name="z_pos_id">
<option value="2463">Option A</option>
<option value="2609">Option B</option>
<option value="3013">Option C</option>
</select>

<select size="4" name="z_pos_id">
<option value="140">Option AA</option>
<option value="3038">Option AB</option>
<option value="3519">Option AC</option>
<option value="2645">Option AD</option>
</select>


So, <select name="z_pos_id">should be replace with this:

<select size="*the number of options*" name="z_pos_id">

Thank you all for the help!

回答1:

Here's a complete script. It should be fairly self explanatory:

// ==UserScript==
// @name     _Auto-size select selects.
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    none
// ==/UserScript==

var posIdSelects = document.querySelectorAll ("select[name=z_pos_id]");
for (var J = posIdSelects.length - 1;  J >= 0;  --J) {
    var numOpts  = posIdSelects[J].getElementsByTagName ("option").length;
    posIdSelects[J].setAttribute ("size", numOpts);
}


回答2:

$(document).ready(function() {
    var ln = $("select[name=z_pos_id] option").length ;
    alert(ln); // you can delete this alert after your test
        $("select[name=z_pos_id]").attr('size', ln);
});