'change a bootstrap radio button value in a loop with jquery

I am trying to change a radio button's position based on a value I get back from a mysql query. This loop runs multiple times and creates a row with each iteration. I have tried:

    $("#far_table tbody").sortable("disable");
    $("#far_table > tbody").empty();
    $.getJSON("gsffar.ajax.php", {
        function: 'update_far_table',
        Engnum: engnum,
        Type: type_toggle,
        Travid: travid
    })
    .done(function(data) {
        $(data).each(function()
        {
            $("#far_table").append('<tr> \
                                <td class="priority">' + this.priority + '</td> \
                                <td>' + this.attribute + '</td>\
                                <td>' + this.responsible + '</td> \
                                <td><div class="btn-group" id="pass_fail_group" data-toggle="buttons">\
                                    <label class="btn btn-primary active">\
                                        <input class="pass_fail" type="radio" name="options" id="pass" value="pass"> Pass\
                                    </label>\
                                    <label class="btn btn-primary" active>\
                                        <input class="pass_fail" type="radio" name="options" id="fail" value="fail" checked> Fail\
                                    </label>\
                                </div></td>\
                                <td><div class="input-group">\
                                <div class="custom-file">\
                                <input type="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">\
                                </div>\
                                </div></td>\
                                </tr>');

            if (this.pass_fail === "pass"){
                $('input:radio[name="options"][value="pass"]').click();
            }else{
                $('input:radio[name="options"][value="fail"]').click();
            }
            
        });
    });
}

and

function update_far_table_input(engnum, type_toggle, travid){
    $("#far_table tbody").sortable("disable");
    $("#far_table > tbody").empty();
    $.getJSON("gsffar.ajax.php", {
        function: 'update_far_table',
        Engnum: engnum,
        Type: type_toggle,
        Travid: travid
    })
    .done(function(data) {
        $(data).each(function()
        {
            var pass="";
            var fail="";
            if (this.pass_fail === "pass"){
                pass="checked";
            }else{
                fail="checked";
            }

            $("#far_table").append('<tr> \
                                <td class="priority">' + this.priority + '</td> \
                                <td>' + this.attribute + '</td>\
                                <td>' + this.responsible + '</td> \
                                <td><div class="btn-group" id="pass_fail_group" data-toggle="buttons">\
                                    <label class="btn btn-primary active">\
                                        <input class="pass_fail" type="radio" name="options" id="pass" value="pass" autocomplete="off" '+pass+'> Pass\
                                    </label>\
                                    <label class="btn btn-primary">\
                                        <input class="pass_fail" type="radio" name="options" id="fail" value="fail" autocomplete="off" '+fail+'> Fail\
                                    </label>\
                                </div></td>\
                                <td><div class="input-group">\
                                <div class="custom-file">\
                                <input type="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">\
                                </div>\
                                </div></td>\
                                </tr>');
        });
    });
}

Neither approach seems to work. I would also like to add a third position in the future so being able to specify position by id or value would be ideal.



Solution 1:[1]

I find it easier to break out the building of the labels.

In this snippet I'm appending the new row and then once it's added to the table the containing div is "jQueryable".

I'm taking some liberties with your data but you should be able to get the gist of it.

Be aware, Html element id's should be unique.

Using this function with rows containing duplicate id's for the placeholder element is going to be a problem.

$("#far_table").append('<tr>\
  <td class="priority">' + this.priority + '</td> \
  <td>' + this.attribute + '</td>\
  <td>' + this.responsible + '</td> \
  <td>\
    <div class="btn-group" id="pass_fail_group" data-toggle="buttons">\
    </div>\
  </td>\
  <td>\
    <div class="input-group">\
      <div class="custom-file">\
        <input type="file" class="custom-file-input" \
        id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">\
      </div>\
    </div>\
  </td>\
</tr>');

buildRadios(document.getElementById('pass_fail_group'), 'options', ['pass', 'fail'], "pass")

function buildRadios(placeholderElem, groupname, valueArray, data_pf) {
  valueArray.forEach((e, i) => {
    let active = e === data_pf;

    const lbl = document.createElement('label');
    lbl.classList.add("btn", "btn-primary")
    if (active) {
      lbl.classList.add('active');
    }
    const radio = document.createElement('input');
    radio.id = e;
    radio.type = 'radio';
    radio.value = e;
    if (active) {
      radio.setAttribute("checked", "");
    }
    radio.name = groupname;
    radio.classList.add("pass_fail");

    lbl.appendChild(radio);
    let properCase = `${e.charAt(0).toUpperCase()}${e.slice(1).toLowerCase()}`
    lbl.appendChild(document.createTextNode(properCase));

    placeholderElem.appendChild(lbl)
  });
}
label.btn {
  white-space: nowrap !important;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="far_table" class="w-100"></table>

Solution 2:[2]

This is the most concise solution, though I am not sure it is the most efficiant:

List<Integer> commonItems = new ArrayList<>(Arrays.asList(a));
commonItems.retainAll(Arrays.asList(b));
commonItems.retainAll(Arrays.asList(c));

JDK doc of List.retainAll:

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

Solution 3:[3]

You can use a Set for each array to store elements so that they can be accessed in O(1) time and then iterate over elements in any set and check if it's present in other two sets as well since set of common elements is guaranteed to be a subset of all the three sets.

    int a[] = {1,3,7,6};
    int b[] = {2,5,0,4};
    int c[] = {11,23,71,6};
    Set<Integer> set1 = new HashSet<>();
    Set<Integer> set2 = new HashSet<>();
    Set<Integer> set3 = new HashSet<>();
    for(int x: a)
        set1.add(x);
    for(int x: b)
        set2.add(x);
    for(int x: c)
        set3.add(x);
    List<Integer> res = new ArrayList<>();
    Iterator<Integer> itr = set1.iterator();
    while(itr.hasNext()){
        int ele = itr.next();
        if(set2.contains(ele) && set3.contains(ele)){
            res.add(ele);
        }
    }
    return res;

This approach should also work in cases where an element is repeated in an array and thus can increase frequency of count if single hashmap based approach is used.

Solution 4:[4]

Assuming the arrays are having unique elements in themself (no duplicates in an array)

You can use some data structure like HashMap to push all elements of the arrays as keys, and values as their count of occurrences to find common elements if the value is 3 :

private ArrayList<Integer> commonElements() {
        int a[] = {1,3,7,6};
        int b[] = {2,5,0,4};
        int c[] = {11,23,71,6};
        
        HashMap<Integer, Integer> elementCunt = new HashMap<>();
        
        for(int element: a) {
            if(elementCunt.containsKey(element)) {
                elementCunt.put(element, elementCunt.get(element) + 1);
            } else {
                elementCunt.put(element, 1);
            }
        }
        
        for(int element: b) {
            if(elementCunt.containsKey(element)) {
                elementCunt.put(element, elementCunt.get(element) + 1);
            } else {
                elementCunt.put(element, 1);
            }
        }
        
        for(int element: c) {
            if(elementCunt.containsKey(element)) {
                elementCunt.put(element, elementCunt.get(element) + 1);
            } else {
                elementCunt.put(element, 1);
            }
        }
        
        Iterator<Integer> itr = elementCunt.keySet().iterator();
        
        ArrayList<Integer> commonElements = new ArrayList<>();
        
        while(itr.hasNext()) {
            int key = itr.next();
            if(elementCunt.get(key) == 3) {
                commonElements.add(key);
            }
        }
        
        return commonElements;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Siddharth
Solution 4