0

I'm trying to add some objects to an array if a checkbox is checked. But I can't seem to make it work. What I would like is to add an object depending on the values of the checked checkboxes. I hope you guys can understand it. Let me show you in code :

This is the code to check if a checkbox is checked :

var filter_options=[];
        $('input:checkbox').click(function()
        {
          var name=$(this).val().trim();
          if(this.checked)
          {
            filter_options.push(name);
            console.log('Add: ' + name);
        }
        else
        {
            var index=filter_options.indexOf(name);
            if(index > -1)
            {
              filter_options.splice(index, 1);
              console.log('Remove: ' + name + ' at index: ' + index);
          }
      }
      $('#result').html(filter_options.join('; '));
      console.log(filter_options);
  });

Let's these are the object:

var human = new Human();
var dog = new Dog();
var cat = new Cat();

var options = []; //push the objects here depending on the checkboxes value.

And this is my html :

<div class="option">
  <input type="checkbox" value="human">
  <input type="checkbox" value="dog">
  <input type="checkbox" value="cat">
</div>

How can I add these objects to the array depending on the checkbox value? Any help would be highly appreciated.

4 Answers 4

1

function Human() {
    this.id = 1; 
    this.firstName = "Human";
    this.lastName = "Last Name";
    this.age = 5;
    this.eyeColor = "color";
}

function Dog() {
    this.id = 2;
    this.firstName = "Dog";
    this.lastName = "Last Name";
    this.age = 5;
    this.eyeColor = "color";
}

function Cat() {
    this.id = 3;
    this.firstName = "Cat";
    this.lastName = "Last Name";
    this.age = 5;
    this.eyeColor = "color";
}
var human = new Human();
var dog = new Dog();
var cat = new Cat();
var filter_options=[];
        $('input:checkbox').click(function()
        {
          var id = $(this).attr("data-id");
          var name=$(this).val().trim();
          if(this.checked)
          {
            if(id==1){
              filter_options.push(human);
            }
            else if(id==2){
                filter_options.push(dog);
            }
            else if(id==3){
                filter_options.push(cat);
            }
        }
        else
        {
            var index=filter_options.indexOf(name);
            if(index > -1)
            {
              filter_options.splice(index, 1);
              console.log('Remove: ' + name + ' at index: ' + index);
            }
            for(var i = 0; i < filter_options.length; i++) {
              if(filter_options[i].id == id) {
                  filter_options.splice(i, 1);
                  break;
              }
          }
      }
      $('#result').html(filter_options.join('; '));
      console.log(filter_options);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="option">
  <input type="checkbox" value="human" data-id="1">
  <input type="checkbox" value="dog" data-id="2">
  <input type="checkbox" value="cat" data-id="3">
</div>

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

2 Comments

Ok, this will work fine. Is there any way I can make this dynamic? I mean let's say I have multiple objects and later on I add a few other objects as well. I would not like to change the code again since I would need to lets say: if(id==7){ filter_options.push(horse); } do this. How can I make this dynamic?? Thanks :)
To make it dynamic, you need to have a predefined array of all the animal objects data like human,dog, horse etc. Then you can do it by data-id.
0

Try this:

var filter_options=[];
$(".option").change(function()
{
    $(".option").each(function()
    {
        if( $(this).is(':checked') )
        {
            var name=$(this).val().trim();
            filter_options.push(name);
            console.log('Add: ' + name);
        } else {
            var index=filter_options.indexOf(name);
            if(index > -1)
            {
              filter_options.splice(index, 1);
              console.log('Remove: ' + name + ' at index: ' + index);
          }
        }
    });
     $('#result').html(filter_options.join(': '));
      console.log(filter_options);
});

1 Comment

This will not work since the array filter-options is always empty.
0

First of all there needs to some modification on the HTML to allow the end user to view properly using div and label.

Next, you just need the logic for addition and deletion based on the :checked condition.

$(function() {
  clickHandler();
});

function clickHandler() {
  var options = [];
  var human = new Human();
  var dog = new Dog();
  var cat = new Cat();

  $('input:checkbox').on('change', function() {
    var name = $(this).attr('name');
    if ($(this).is(':checked')) {
      options.push(name);
    } else {
      options.splice(options.indexOf(name), 1);
    }
    console.log('List = ', options)
  });
}

function Human() {}

function Dog() {}

function Cat() {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="option">
  <div>
    <label for="human">
      <input type="checkbox" value="human" name="human" />
      Human
    </label>
  </div>
  <div>
    <label for="human">
      <input type="checkbox" value="dog" name="dog"/>
      Dog
    </label>
  </div>
  <div>
    <label for="human">
      <input type="checkbox" value="cat" name="cat"/>
      Cat
    </label>
  </div>
</div>

1 Comment

I didn't want to add the "cat" (cat as string) in the array but the cat as an object.I solved anyway thank you for your time :)
0

function submitForm(frm) {
    frm.createSpinner();
    return new Promise((submitResolve, submitReject) => {
        frm.objectify().then((formData) => {
            post(frm.ga("action"), formData).then((res) => {
                submitResolve(res);
                frm.removeSpinner();
            });
        });
    });
}

Bu ile sarmalamayı deneyebilirsiniz.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.