具有动态输入字段的Jquery可排序Div

时间:2016-02-23 20:08:58

标签: javascript jquery jquery-ui jquery-ui-sortable

我正在尝试对这些动态输入字段进行排序,我希望能够单独拖动它们以便重新排序。现在,当我运行此代码时,它不是将整行视为div而是div的每个元素。我错过了什么?

<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style type="text/css">
<!--
#main {
    max-width: 800px;
    margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
  <h1>Add or Remove text boxes with jQuery</h1>
  <div class="my-form">
    <form role="form" method="post">
      <div class="text-box" id="text-box">
        <label for="box1">Box <span class="box-number">1</span></label>
        <input type="text" name="boxes[]" value="" id="box1" />
        <a class="add-box" href="#">Add More</a>
      </div>
      <p>
        <input type="submit" value="Submit" />
      </p>
    </form>
  </div>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
  $('.my-form .add-box').click(function() {
    var n = $('.text-box').length + 1;
    if (5 < n) {
      alert('Stop it!');
      return false;
    }
    var box_html = $('<div id="text-box" class="text-box" id="text-box"><label for="box' + n + '">Box <span class="box-number">' + n + '</span></label> <input type="text" name="boxes[]" value="" id="box' + n + '" /> <a href="#" class="remove-box">Remove</a></div>');
    box_html.hide();
    $('.my-form .text-box:last').after(box_html);
    box_html.fadeIn('slow');
    return false;
  });

  $('.my-form').on('click', '.remove-box', function() {
    $(this).parent().css('background-color', '#FF6C6C');
    $(this).parent().fadeOut("slow", function() {
      $(this).remove();
      $('.box-number').each(function(index) {
        $(this).text(index + 1);
      });
    });
    return false;
  });

  $('.my-form').on('click', '.text-box:last', function() {
    var n = $('.text-box').length + 1;
    if (5 < n) {
      alert('Stop it!');
      return false;
    }
    var box_html = $('<div id="text-box" class="text-box" id="text-box"><label for="box' + n + '">Box <span class="box-number">' + n + '</span></label> <input type="text" name="boxes[]" value="" id="box' + n + '" /> <a href="#" class="remove-box">Remove</a></div>');
    box_html.hide();
    $('.my-form .text-box:last').after(box_html);
    box_html.fadeIn('slow');
    return false;
  });

  $(function() {
    $("#text-box").sortable({
      placeholder: "ui-state-highlight",
      helper: 'clone'
    });
    $("#text-box").disableSelection();
  });
});
</script>
</body>
</html>

0 个答案:

没有答案