1

I have a script that increments a counter when an item is added to a dropdown list. This is working fine. However, I need a way to decrement the counter if the item is removed from the list.

I am struggling to find a way to do this with the code I have and would appreciate it if someone could help me code this. I am using jQuery chosen plugin to populate the list from a button click. I have posted the js but if you need the HTML i shall be happy to post. Just posting the js code to keep post to a minimum. Many thanks.

js

$(function() {
  $(document).on('click', '#add', function() {
    var boxvalue = $("#box_input").val();

    if (boxvalue ==''){
      $("#niinputmessage").fadeIn(3000).html('No blank entries').fadeOut(5000).css({ 'color': 'red', 'margin-left': '5px', 'margin-top': '5px' });
      return false;
    }

    var count = $("#box_ni :selected").length;
    $("#counter").html("Total selected boxes for intake: " + 
    '<span style="font-size: 14px; color: white;">' + 
    '( ' + count + ' )' + 
    '</span>').css('color:, black');

    if (count > 2) {
      $("#counter").html("No more than 3 items per intake");
      return false;
    } else {
      count++;
      $("#counter").html("Total selected boxes for intake: " + 
      '<span style="font-size: 14px; color: white;">' + '( ' + count + ' )' + 
      '</span>').css('color:, black');
    }

    $("#box_ni").attr("data-placeholder", "Select boxes for intake... ");
    $("#box_ni").append("<option selected>" + boxvalue + "</option>");
    $("#box_ni").trigger("chosen:updated");
    $("#box_input").val('');
    });
  });

html

<div class="form-group">
    <label for="box_input" class="labelStyle">Enter Your Box(es)</label><br />
    <input type="text" id="box_input" name="box_input" disabled />
    <input type="button" id="add" Value="Add" disabled />
    <div id="niinputmessage"></div>
        <div class="servicesHelp"><lead id="serviceHelp" class="form-text text-muted">Please select your boxes from the list. You can select a max of 3 boxes per submission. You can select multiple boxes by holding the left ctrl on your keyboard and making your selection</lead>
        </div>
        <div class="noBrtvBoxes" style="color:white;"></div>
  </div>
  <div id="counter" style="margin-left: 7px; font-size: 14px; color: #c5ba7a;">Total selected boxes for intake: 0</div><br />
  <div class="message">
    <div class="sucMsg">

    </div>
  </div>
user1532468
  • 1,723
  • 8
  • 41
  • 80

1 Answers1

1

You don't need to increment the counter, you can get the number of options by:

selectElement.options.length

To get the current selected option, then you can remove it via a button.

selectElement.options[selectElement.selectedIndex]

In my code below, I just remove it when you select it via 'change' event, I can not use 'click' event, cuz it will remove the current when you open the list, and I have to keep the useless option to make user can change the last one.

const addBtn = document.querySelector('.add')
  const inputEl = document.querySelector('.input-box')
  const list = document.querySelector('.list')
  const counter = document.querySelector('.counter')
  const mode = document.querySelector('.mode')
  const max = 3
  let num = 0
  addBtn.addEventListener('click', e => {
    if (addBtn.disabled) {
      return false
    }
    if (inputEl.value.trim().length === 0) {
      return
    }
    addItem()
    
    updateCounter()
    resetInput()
    num+=1
    if (num >= max) {
      inputEl.disabled = true
      addBtn.disabled = true
    }
    e.preventDefault()
  })

  function updateCounter () {
    counter.textContent = list.options.length - 1
  }

  function addItem () {
    const option = document.createElement('option')
    option.value = option.text = inputEl.value.trim()
    list.appendChild(option)
  }

  function resetInput () {
    inputEl.value = ''
  }
  const warn = document.querySelector('.warn')
  mode.addEventListener('click', e => {
    if (mode.checked) {
      warn.classList.add('active')
      list.classList.add('removing')
      list.selectedIndex = 0
      list.focus()
      
    } else {
      warn.classList.remove('active')
      list.classList.remove('removing')
    }
  })

  list.addEventListener('change', e => {
    if (!mode.checked) {
      return false
    }

    if (list.selectedIndex == 0) {
      return false
    }
    const selected = list.options[list.selectedIndex]
    selected.parentNode.removeChild(selected)
    updateCounter()
    e.preventDefault()
  })
select {
    outline: none;
  }
  .view {
    margin: 0 auto;
    width: 600px;
  }
  label {
    width: 100px;
    margin-right: 5px;
  }
  .form-control {
    margin: 15px 0 15px 0;
  }

  .removing {
    border: 1px solid red;
  }

  .warn {
    visibility: hidden;
    background: red;
    color: #FFF;
  }
  .warn.active {
    visibility: visible;
  }
<div class="view">
  <form>
      <div class="form-control">
        <label>new option</label>
        <input class="input-box" type="text" placeholder="new option here">
        <button class="add">Add to options</button>
      </div>
      <div class="form-control">
        <label>All options:</label>
        <select class="list">
          <option selected="selected">All options</option>
        </select>
        <input type="checkbox" class="mode">
        <label>Removing mode</label>
        <div class="warn">click dropdown option will remove it</div>
      </div>
  </form>
  <div class="output">
    counts: <span class="counter">0</span>
  </div>
</div>
sfy
  • 2,810
  • 1
  • 20
  • 22