Mark the first radio button generated with a loop in pug

2

I'm using pug to generate a list of radio buttons using a while loop:

- var n = 0;
while n < 11
  input(type="radio", name="cb", id="cb"+n, value=n)
  label(for="cb"+n) #{n++}

The problem is that in this way none is marked by default and I want the first one to be marked by default and I do not know how it would be done.

At the moment I have removed the first element from the list and I have put it out with a checked="" so that it appears marked by default:

input(type="radio", name="cb", checked="", id="cb0", value=0)
label(for="cb0") 0
- var n = 1;
while n < 11
  input(type="radio", name="cb", id="cb"+n, value=n)
  label(for="cb"+n) #{n++}

But, although it works, this seems inefficient because I'm repeating code and, if I want to make changes, I have to do it in two different places.

Is there any way to make the first radio button have that additional attribute without needing to get it out of the loop?

    
asked by Alvaro Montoro 17.07.2018 в 18:46
source

1 answer

1

You can add a conditional value for an attribute, just as I want the first one to be marked and the loop goes from 0 to 11, what you have to do is add a condition that checks if n is zero and assign it that value to the attribute checked .

That's how the code is at the end

- var n = 0;
while n < 11
  input(type="radio", name="cb", id="cb"+n, value=n, checked=(n == 0))
  label(for="cb"+n) #{n++}
    
answered by 20.07.2018 / 18:25
source