简体   繁体   中英

Wrapping text within a multiple <select> list

I want to give the user the ability to select multiple elements (which happen to be about a paragraph each). The problem is that a standard select multiple in html is (as far as I can tell) a single line per choice. This is a problem as the layout gets very screwy if I let the line go long. Also, if I just truncate the line, the main gist of the text is lost. Is there a way to get around this with javascript? Is there an alternative that allows all of the text to be displayed and return the values back in a colon delimited list?

There are a lot of ways you could do this. The most straightforward would be to just put a checkbox next to each paragraph. The user can check the boxes next to the paragraphs of his choosing.

If you have a smoother interface in mind, you can extend that idea by hiding the checkboxes with CSS, then using JavaScript to make the checkboxes selected when the corresponding paragraph is clicked and highlight the paragraph (by applying a CSS class) to show it as selected. A framework like jQuery will streamline this process nicely.

Edit: Now that I think of it, as long as you put each paragraph in a <label> element you don't even need JavaScript to check/uncheck the hidden checkboxes; that will happen automatically as long as the label's for attribute is set correctly. All you need JavaScript for is to highlight/unhighlight the labels.

Here's a naive implementation using jQuery:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
  input.hidden-checkbox { display: none; }
  label.multi-select { display: block; cursor: pointer; }
  label.checked { background-color: #ddd; }
</style>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">  
  $(document).ready(function() {
    $('input.hidden-checkbox').bind('change', function(e) {
      var checkBox = $(e.target),
          label = $('label[for=' + checkBox.attr('id') + ']');

      if(label) {
        if(checkBox.attr('checked')) {
          label.addClass('checked');
        } else {
          label.removeClass('checked');
        }
      }
    });
  });
</script>
</head>
<body>

<form>
  <input  type="checkbox" value="1"
          name="paragraph[]" id="paragraph-1"
          class="hidden-checkbox"/>
  <label for="paragraph-1" class="multi-select">Text of paragraph 1.
    As long as you want. Lorem ipsum dolor sit amet...</label>

  <input  type="checkbox" value="2"
          name="paragraph[]" id="paragraph-2"
          class="hidden-checkbox" class="multi-select" />
  <label for="paragraph-2" class="multi-select">Paragraph 2's text.
    Lorem ipsum dolor sit amet...</label>

  <!-- ...etc... -->
</form>
</body>
</html>

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