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
https://forums.phpfreaks.com/topic/50035-can-javascript-manipulate/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.