mardi 27 juin 2017

Unchecked the Checkbox while looping threw array in for loop

I have the Check box of all the week days.

HTML code is here:

<div class="col-lg-10">

    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="monday" name="working_days[]" value="1" checked>
        <label for="monday"> Monday </label>
    </div>

    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="tuesday" name="working_days[]" value="2" checked>
        <label for="tuesday"> Tuesday  </label>
    </div>

    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="wednesday" name="working_days[]" value="3" checked>
        <label for="wednesday"> Wednesday  </label>
    </div>

    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="thursday" name="working_days[]" value="4" checked>
        <label for="thursday"> Thursday </label>
    </div>
    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="friday" name="working_days[]" value="5" checked>
        <label for="friday"> Friday  </label>
    </div>
    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="saturday" name="working_days[]" value="6" checked>
        <label for="saturday"> Saturday  </label>
    </div>
    <div class="checkbox checkbox-custom checkbox-inline">
        <input type="checkbox" id="sunday" name="working_days[]" value="7" checked>
        <label for="sunday"> Sunday  </label>
    </div>

</div>

User Simply uncheck the day which he/she don't want to check. I save the days in comma separated string in the database as:

1,2,4,5

Now I am Fetching it using Ajax. I get the string back in the ajax response.

The Problem

I am not able to uncheck the days which user uncheck before. Or I say I want to display only the checked days as checked and want to uncheck the days which is not checked by use.

What is have tried so far?

I have created an array from the string by using split.

var working_day_string = response.working_days;   // response.working_days = 1,2,4,5
var working_day_array = working_day_string.split(',');

After getting an array I use For loop to uncheck the checkbox but it did not working.

for (i=0;i<working_day_array.length;i++){ 
   working_day_array[i] != '1' ? $('#monday').prop('checked', false) : '';         
}

But I My Monday checkbox is getting uncheck.




Aucun commentaire:

Enregistrer un commentaire