Eisenbiegler
Eisenbiegler

Reputation: 57

How to display checkbox value (checked or unchecked )

I am working on a project and the project was created with ASP.Net mvc 5. I get the data from the database and I just want to display the data on the user interface. My problem is, I have all the data I want in the browser console, but the checkboxes are not shown checked. How can I do this?

"<input type='checkbox' value='" +item.IsActive+"'/>"

Here is my code:

    function success(data) {
        var rows;
        if (data != null) {
            $.each(data, function (i, item) {       
                rows += "<tr>"
                    + "<td>" +
                    "<label class='checkbox-container' id ='checkbox-container'>" +
                    item.Name+
                    "<input type='checkbox' value='" + item.IsActive+"'/>" +
                    "<span class='checkmark'>"+"</span>"+
                    "</label >"+
                    "</td>"     
            });
            $('#myTable tbody').append(rows);
        }
        else {
            alert("Something went wrong");
        }
    }

Upvotes: 0

Views: 835

Answers (2)

Cameron
Cameron

Reputation: 554

Maybe some js logic would help?

$.each(data, function (i, item) {       
    var checkbox_input = "<input type='checkbox' value='" + item.IsActive+"'/>";
    if(item.IsActive){
        var checkbox_input = "<input type='checkbox' value='" + item.IsActive+"' checked />";

    }
    rows += "<tr>"
        + "<td>" +
        "<label class='checkbox-container' id ='checkbox-container'>" +
        item.Name+
        checkbox_input +
        "<span class='checkmark'>"+"</span>"+
        "</label >"+
        "</td>"     
});

Or Shorthand with template literal js

$.each(data, function (i, item) {       
    rows += "<tr>"
        + "<td>" +
        "<label class='checkbox-container' id ='checkbox-container'>" +
        item.Name+
        `<input type='checkbox' value='${item.IsActive}' ${item.IsActive ? 'checked' : ''} />` +
        "<span class='checkmark'>"+"</span>"+
        "</label >"+
        "</td>"     
});

Upvotes: 1

omiguelgomes
omiguelgomes

Reputation: 165

If you want a checkbox to show checked, it should have the checked attribute. In this case it would be something like:

 <input type='checkbox' checked/>

Since you have a variable that tells you wether the checkbox is checked or not, you could try using:

"<input type='checkbox'" + item.isActive ? "checked" : "" + "/>"

This will render the checkbox as checked when item.isActive is true.

Upvotes: 0

Related Questions