无法删除元素或重置选择

时间:2017-03-08 02:00:20

标签: javascript jquery html

我正在尝试消除由Javascript代码动态创建的重复select元素。

我有两种select元素。单击按钮添加元素时会出现第一个。这有两个下拉选项:“访问控制”和“CCTV”。

如果选择了CCTV,则会出现第二个select元素,并以“1”和“2”作为下拉选项。

然后,我还有另外两个按钮:删除元素全部删除

例如,如果我点击全部删除,则会删除所有元素,包括CCTV的第二个select元素。

问题:

当我再次点击添加元素并再次选择“CCTV”时,会出现另外两个select个元素而不是一个。

Here's the JSFiddle demo.

<html>

<head>
  <title>Create Elements Dynamically using jQuery</title>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js">
  </script>
  <style>
    body {
      font: 13px verdana;
      font-weight: normal;
    }
    
    div.box {
      margin-bottom: 10px;
      background-color: #f7f7f7;
      border: 1px solid #d7d7d7;
      border-radius: 3px;
      border-bottom: 1px solid rgb(169, 160, 165);
    }
  </style>
</head>

<body>
  <div id="main">
    <input type="button" id="btAdd" value="Add Element" class="bt" />
    <input type="button" id="btRemove" value="Remove Element" class="bt" />
    <input type="button" id="btRemoveAll" value="Remove All" class="bt" /><br />
  </div>
  <div id="tes">
  </div>
  <script>
    $(document).ready(function() {

      var iCnt = 0;
      // CREATE A "DIV" ELEMENT AND DESIGN IT USING jQuery ".css()" CLASS.
      var container = $(document.createElement('div')).css({
        padding: '5px',
        margin: '20px',
        width: '170px',
        border: '1px dashed',
        borderTopColor: '#999',
        borderBottomColor: '#999',
        borderLeftColor: '#999',
        borderRightColor: '#999'
      });

      $('#btAdd').click(function() {
        if (iCnt <= 2) {

          iCnt = iCnt + 1;

          // ADD TEXTBOX.
          $(container).append('<select class="input" id=tb' + iCnt + ' ' +
            '><option value="Access">Access Control</option><option value="CCTV">CCTV</option></select>');



          $(document).ready(function() {
            $(document).on('change', '#tb' + iCnt, function() {


              var method = $('option:selected').val();

              if (method == 'Access') {





              } else if (method == 'CCTV') {





                $('#tes').append('<select id="quantity-' + iCnt + '"><option value="1">1</option><option value="1">2</option></select>');

              }

            });
          });



          // SHOW SUBMIT BUTTON IF ATLEAST "1" ELEMENT HAS BEEN CREATED.
          if (iCnt == 1) {

            var divSubmit = $(document.createElement('div'));
            $(divSubmit).append('<input type=button class="bt"' +
              'onclick="GetTextValue()"' +
              'id=btSubmit value=Submit />');

          }

          // ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
          $('#main').after(container, divSubmit);
        }
        // AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
        // (20 IS THE LIMIT WE HAVE SET)
        else {
          $(container).append('<label>Reached the limit</label>');
          $('#btAdd').attr('class', 'bt-disable');
          $('#btAdd').attr('disabled', 'disabled');
        }
      });

      // REMOVE ONE ELEMENT PER CLICK.
      $('#btRemove').click(function() {
        if (iCnt != 0) {

          $('#tb' + iCnt).remove();
          $('#add' + iCnt).remove();


          $('#quantity-' + 1).val('').trigger('chosen:updated');


          iCnt = iCnt - 1;
          alert(iCnt);
          $('#quantity-' + 1).remove();

        }

        if (iCnt == 0) {
          $(container)
            .empty()
            .remove();

          $('#btSubmit').remove();
          $('#btAdd')
            .removeAttr('disabled')
            .attr('class', 'bt');
        }
      });

      // REMOVE ALL THE ELEMENTS IN THE CONTAINER.
      $('#btRemoveAll').click(function() {
        $(container)
          .empty()
          .remove();

        $('#btSubmit').remove();
        iCnt = 0;

        $('#btAdd')
          .removeAttr('disabled')
          .attr('class', 'bt');
      });
    });

    // PICK THE VALUES FROM EACH TEXTBOX WHEN "SUBMIT" BUTTON IS CLICKED.
    var divValue, values = '';

    function GetTextValue() {

      $(divValue)
        .empty()
        .remove();

      values = '';

      $('.input').each(function() {
        divValue = $(document.createElement('div')).css({
          padding: '5px',
          width: '200px'
        });
        values += this.value + '<br />'
      });

      $(divValue).append('<p><b>Your selected values</b></p>' + values);
      $('body').append(divValue);
    }
  </script>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

我不太明白你的问题,但我认为就是这样。您只想添加一次动态select(数量),因此您需要创建一个变量var CCTV = false;来进行控制。

我添加了一个函数getval来获取所选select的值。对于使用$('option: selected')时,您会在页面上获得包含所有选择的数组,从而导致您对错误的对象进行验证。

$(document).ready(function() {
    // CREATE A "DIV" ELEMENT AND DESIGN IT USING jQuery ".css()" CLASS.
    var container = $(document.createElement('div')).css({
        padding: '5px',
        margin: '20px',
        width: '170px',
        border: '1px dashed',
        borderTopColor: '#999',
        borderBottomColor: '#999',
        borderLeftColor: '#999',
        borderRightColor: '#999'
    });

    $('#btAdd').click(function() {
        if (iCnt <= 2) {

            iCnt = iCnt + 1;

            // ADD TEXTBOX.
            $(container).append('<select class="input" id=tb' + iCnt + ' ' +
                ' onchange="getval(this);"><option value="Access">Access Control</option><option value="CCTV">CCTV</option></select>');

            $(document).ready(function() {

                $(document).on('change', '#tb' + iCnt, function() {

                    var method = $('option:selected').val();
                    if (method == 'Access') {

                    } else if (method == 'CCTV') {
                    
                    }
                });
            });

            // SHOW SUBMIT BUTTON IF ATLEAST "1" ELEMENT HAS BEEN CREATED.
            if (iCnt == 1) {

                var divSubmit = $(document.createElement('div'));
                $(divSubmit).append('<input type=button class="bt"' +
                    'onclick="GetTextValue()"' +
                    'id=btSubmit value=Submit />');

            }

            // ADD BOTH THE DIV ELEMENTS TO THE "main" CONTAINER.
            $('#main').after(container, divSubmit);
        }
        // AFTER REACHING THE SPECIFIED LIMIT, DISABLE THE "ADD" BUTTON.
        // (20 IS THE LIMIT WE HAVE SET)
        else {
            $(container).append('<label>Reached the limit</label>');
            $('#btAdd').attr('class', 'bt-disable');
            $('#btAdd').attr('disabled', 'disabled');
        }
    });

    // REMOVE ONE ELEMENT PER CLICK.
    $('#btRemove').click(function() {    
        if (iCnt != 0) {
            $('#tb' + iCnt).remove();
            $('#add' + iCnt).remove();
            $('#quantity-' + iCnt).remove();
            iCnt = iCnt - 1;
        }
        if (iCnt == 0) {
            CCTV = false;
            $(container).empty().remove();
            $('#btSubmit').remove();
            $('#quantity').remove();
            $('#btAdd').removeAttr('disabled').attr('class', 'bt');
        }
    });

    // REMOVE ALL THE ELEMENTS IN THE CONTAINER.
    $('#btRemoveAll').click(function() {
        CCTV = false;
        $('#quantity').remove();
        $(container).empty().remove();
        $('#btSubmit').remove();
        iCnt = 0;
        $('#btAdd').removeAttr('disabled').attr('class', 'bt');
    });
});

// PICK THE VALUES FROM EACH TEXTBOX WHEN "SUBMIT" BUTTON IS CLICKED.
var divValue, values = '';
var CCTV = false;
var iCnt = 0;

function GetTextValue() {
    $(divValue).empty().remove();
    values = '';
    $('.input').each(function() {
        divValue = $(document.createElement('div')).css({
            padding: '5px',
            width: '200px'
        });
        values += this.value + '<br />'
    });
    $(divValue).append('<p><b>Your selected values</b></p>' + values);
    $('body').append(divValue);
}

function getval(sel)
{
  if (sel.value == 'CCTV') 
  {
      if (!CCTV) {
          $('#tes').append('<select id="quantity"><option value="1">1</option><option value="1">2</option></select>');
          CCTV = true;
      }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
    <div id="main">
        <input type="button" id="btAdd" value="Add Element" class="bt" />
        <input type="button" id="btRemove" value="Remove Element" class="bt" />
        <input type="button" id="btRemoveAll" value="Remove All" class="bt" /><br />
    </div>
    <div id="tes">
    </div>    </body>

答案 1 :(得分:0)

你只忘了一行很短的代码:

$('#tes').empty();

在你向$('#tes')附加内容并解决它之前,先把它放好。

Here, I forked your JSFiddle for the demo