0

I'm trying to add a value of checked for specific elements.

function renderList() {
 $.getJSON("/search", function(response) {
  $.each(response, function(index, value) {
    $('ul').append($('<li>')
     .append(value.task)
     .append('<input type="checkbox"/>')
     .append('<span>x</span>'))
    })  
  });
}

I would like to add a conditional statement for the checkbox value of "checked"

When I add .attr('checked', true), it is added to the li and not the checkbox.

1
  • Under what condition would the checkbox be checked, or unchecked? Commented Mar 16, 2014 at 20:34

2 Answers 2

1

You can do something like this:

function renderList() {
 $.getJSON("/search", function(response) {
    $.each(response, function(index, value) {

    var checkedString = '';
    if( value == 'something'){
       checkedString = 'checked="checked"';
    }
    $('ul').append($('<li>')
    .append(value.task)
    .append('<input type="checkbox" ' + checkedString + '/>')
    .append('<span>x</span>'))
    })
 });  
Sign up to request clarification or add additional context in comments.

Comments

0

you can try

$.each(response, function(index, value) {
    var valueChecked = (value.checked)? ' checked ': '';
    $('ul').append($('<li>' + value.task +  
        '<input type="checkbox" '+ valueChecked +' />' +
        '</li>')

valueChecked get ' checked ' value if value.checked (the property choosed by you) is true;

there's no need to write .append('li') .... .append('

Hope this help you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.