Jump to content

Can JavaScript manipulate <select> ?


solarisuser

Recommended Posts

Hi All,

 

Is there a way to use JS to limit the size of a <select> dropdown menu?

 

An example were I'd like to have the first <option> be display up to 10 characters, but of course the value should remain the entire length.

 

Thanks for any help!

 

<html>
<body>

<form action="">
<select name="cars">
  <option value="volvo  Extra Extra Long">Volvo Extra Extra Long</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>
</form>

</body>
</html>

Link to comment
Share on other sites

You could try something like this:

function shortenSelectOptions(x) {
  eles = document.getElementByTagName('option');
  for (i = 0; i < eles.length; i++) {
    if (eles[i].innerHTML.length > x) {
      newVal = eles[i].innerHTML.substring(0, x);
      eles[i].innerHTML = newVal;
    }
  }
}

 

That function could be called (passing in a value that is the length to which you wish to limit you options), and it should trim all the ones on the page to your specification.

 

Hope that helps.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.