Wrapping text within a multiple <select> list

后端 未结 1 596
情深已故
情深已故 2021-01-15 01:43

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 f

相关标签:
1条回答
  • 2021-01-15 02:00

    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: #ffffd; }
    </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>
    
    0 讨论(0)
提交回复
热议问题