user3728662
user3728662

Reputation: 67

Jquery checkbox not getting checked

I have a function called 'getData' that contains an ajax call that successfully returns my data ( a dynamically created list of fruits) via json. I have another function called 'AddFruit' that should check a checkbox when a user clicks a button that enters a text value into a textbox and that value does NOT match one of the values contained in my json data.

For example if the data returned from the ajax call is {'orange', 'apple', 'pear'} and the user clicks a button that adds 'banana' to a textbox, my checkbox should be checked.

Below is what I've tried so far:

  function AddFruit(data) {
                     var fruit = $("#Fruit").val(); //the value of input text box that gets populated when a user clicks '#ButtonAdd' button.

                     $("#ButtonAdd").click(function() {
                     $.each(data, function (item) {
                   if ($('fruit:contains(" + data[item] + ")'))
                        {
                          $("#Oldform").prop ("checked", false);
                        } else
                            {
                                $("#Oldform").prop ("checked", true);
                            }
                         });
                   });
              }

  getData().done(AddFruit); // when the ajax call is successfully completed, run the AddFruit function.

Upvotes: 1

Views: 339

Answers (2)

user3728662
user3728662

Reputation: 67

To search the data returned from the ajax call, a for loop with a break statement is needed. When an element in data is matched with the text input, the for loop exits.

var ajaxData = null;

  function AddFruit(data){
            ajaxData = data;
                $("#Button").click(function(){
                 for (var i = 0; i < data.length; i++){ 
                    if (data[i] == $("#Fruit").val())
                   {
                    //leave check box unchecked
                    break;
                    }
                    else{
                    //check check box
                    }
                 }
             });
          }

Upvotes: 0

ArnoHolo
ArnoHolo

Reputation: 317

You forgot the ; after calling prop().

Upvotes: 0

Related Questions