Struts 1 and JQuery: how to dinamically change width to an option select according to the length of the text

24 Views Asked by At

I am working to an old website using Java 1.6 and Struts 1. There is a plenty of jsp page (53 pages) with an input form; inside each form, there is an input select defined according to the Struts 1 syntax

<html:select property="sapplication" styleId="selectSmallFont" onchange="changeComboboxValue()">
    <html:option value="-" />
     <logic:present name="<%=SessionAttributes.LIST_APPLICATION_OBJECT%>">
        <html:options collection="<%=SessionAttributes.LIST_APPLICATION_OBJECT%>"
            property="value" labelProperty="label" />
     </logic:present>
</html:select>

only 2 select have styleId and onchange attributes; the remaining 51 does not have such these attributes, but all 53 have sapplication property.

The SessionAttributes.LIST_APPLICATION_OBJECT is a collection of strings having max 100 characters, extracted from a MySQL table; the problem is that, when the combobox with sapplication property is opened, I see long width items truncated as follows

0008 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, s...

instead of

0008 - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut

Searching for some solution on Stack Overflow, I found the following (I replaced the original id with sapplication)

...
<head>
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>

$(document).ready(function() {
  $('#sapplication').css("width", "200px");
  $('#sapplication').change(function(){
    if ($("#sapplication")[0].selectedIndex <= 0) {
      $('#sapplication').css("width", "200px");
    } else {
      $('#sapplication').css("width", "auto"); 
    }
  });
});

</script>
<style>
#sapplication select { 
  width:200px; 
}

#sapplication select:focus {
  width:auto; 
}
</style>
</head>
...

on the browser (due to old-dated website, it works well only in IE compatibility), looking at HTML source, each select with sapplication property, is coded with

<select name="sapplication">
 <option value="-">-</option>
 ....
</select>

in the JQuery script, I replaced

$('#sapplication')

with

$('select[name ="sapplication"]')

and, in the css script

#sapplication select

has been replaced with

select[name="sapplication"]

according to the Stack Overflow solution, on loading a jsp page with this combobox, the default option appears to be 200px wide, and, on change, it dinamically extends to the full text length of the selected option...I tried the code on a static page and it works perfectly, but in my website it doesn't: I still see long width option select truncated! I put my code inside the main jsp page that contains all of the 53 pages.

I wouldn't work on each of the 53 jsp pages to handle this issue.

How can I solve this?

Thanks to everybody

0

There are 0 best solutions below