0

I'm trying to accomplish when an option is selected/unselected on a multiple select the onChange event will call a function to add or remove the dynamic field that is selected/unselected.

I've been trying for a few hours to think of the best logical approach to get this to work.

$('.multi-select').on('change', function() {
  $.each($(this).val(), function() {
   /* [ Some logic to check if a dynamic input should be removed or added. ]*/
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="multi-select" multiple>
  <option value="0" selected>Col 0</option>
  <option value="1">Col 2</option>
  <option value="2" selected>Col 2</option>
  ...
</select>

<div class="dynamic-fields">
  <input type="text" name="option[0]" value="asc">
  <input type="text" name="option[2]" value="desc">
</div>

I just need some guidance with the best approach that I should take.

1 Answer 1

1

According to your question, every time the user select one or more elements from the selectbox a function must do:

  1. if element is selected and already present in the div area: do nothing
  2. if the element is selected and not present in the div area: insert
  3. if the element is not selected --> remove the element from the div area

The difficulty here is to select an element by name where the name attribute contains a square bracket.

$(function () {
  $('.multi-select').on('change', function(e) {
    var cacheEle = $('.dynamic-fields');
    $(this).find('option').each(function(index, element) {
      if (element.selected) {
        if (cacheEle.find('input[name="option\\[' + element.value + '\\]"]').length == 0) {
          cacheEle.append('<input type="text" name="option[' + element.value + ']" value="' + element.text + '">')
        }
      }  else {
        cacheEle.find('input[name="option\\[' + element.value + '\\]"]').remove();
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="multi-select" multiple>
    <option value="0" selected>Col 0</option>
    <option value="1">Col 1</option>
    <option value="2" selected>Col 2</option>
</select>

<div class="dynamic-fields">
    <input type="text" name="option[0]" value="asc">
    <input type="text" name="option[2]" value="desc">
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect. Looking at that now it all makes sense :) The way I was thinking was just over complicated! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.