Question

When a button is clicked a new category is added to the database and also displayed on the same page as well.But my problem is that when I click multiple times on button it adds multiple checkboxes for same checkbox value. I made it to insert into database only if it is not already present. My issue is that when i click on button it should add the category if it not present in database. I have two function

  1. add_cat(); javascript function which calls ajax for adding the new category to the database.
  2. is php function which is used for creating new page.

I did that when displaying checkboxes on page i used name= cats[] like array for all checkboxes like

<input type="checkbox" name="cats[]" id="<?php echo $row{'term_id'};?>" value="<?php echo $row{'name'};?>"> <?php echo $row{'name'}; ?> `

In add_cat() function i am using this code

var val = document.getElementById('cat_name').value;
var checkboxes = document.getElementsByName('cats');
var flag = 0;
for (var i = 0, n = checkboxes.length; i < n; i++) {
    if (checkboxes[i] == val) {
        flag = 1;
    }
    alert(flag);
} //check the duplicates
if (flag == 1) {
    alert(flag);
    document.getElementById('error').innerHTML = "Already exists";
    setTimeout(function() { // to show the Error
        $('#error').fadeIn("fast").delay(500).fadeOut("slow");
    }, 1500);
    flag = 0;
} else {
    var div = document.getElementById('divContainer');
    div.innerHTML = div.innerHTML + "<input id='chk_" + idCounter + "' type='checkbox' checked value='" + val + "' /><label for='chk_" + idCounter + "'>" + val + "</label>";
    idCounter++;
    cat_2_db(val); // call ajax to insert  category in database
}

But problem is that flag never get turned into 1 and checkboxes variable is not returning checkbox values

Was it helpful?

Solution

you missed to find the value:

if (checkboxes[i].value === val) {

Refactoring your for loop

for(var i = 0, i < checkboxes.length; i++) {
    if (checkboxes[i].value === val) {
        flag = 1;
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top