Cho
Cho

Reputation: 21

input type checkbox to be true or false depended on the data

I'm trying to create a checkbox, which is depended on the database to show whether it should be initially checked or unchecked.

Played around the checkedbox and value with true/false, 0/1 and ""/blanks

$.each(customers, (index, customer) => {
$('#accordionAlarm').append(
`<tr>
<td class="card">

<input type="checkbox" name="checkBox[]" id="1${customer.customerId}" checked="${customer.alarmDateInitial === 'Y' ?  'true' : 'false' }"></input>
<input type="checkbox" name="checkBox[]" id="5${customer.customerId}" checked="${customer.alarmDateFifth === 'Y' ?  'true' : 'false' }"></input>
<input type="checkbox" name="checkBox[]" id="7${customer.customerId}" checked="${customer.alarmDateSeventh === 'Y' ?  'true' : 'false' }"></input>

</td>
</tr>`)
});

Expected:

Upvotes: 0

Views: 2751

Answers (2)

Felix Kling
Felix Kling

Reputation: 816364

checked is a boolean attribute, which means that its mere existence indicates that the element is checked.

You have to restructure your template literal so that checked is only included if the condition is true, e.g.

customer.alarmDateInitial === 'Y' ?  'checked' : ''

In context:

`<input type="checkbox" name="checkBox[]" id="1${customer.customerId}" ${customer.alarmDateInitial === 'Y' ?  'checked' : '' } ></input>`

Upvotes: 3

monkee
monkee

Reputation: 399

Have you tried checked="checked" instead of a truthy value? You could also just return checked instead of setting the attribute value.

Upvotes: 0

Related Questions