Good morning all, I'm currently learning Alpine JS...
# javascript
h
Good morning all, I'm currently learning Alpine JS. I have built a select list using Alpine and am now trying and make one of the options 'SELECTED' based on the value of an alpine variable. It almost works. The first x-if works showing the selected option but the second x-if never shows the rest of the options.
Copy code
<div class="travFormInput">
          <select x-model="p_person_to" name="p_person_to" required>
            <option value="">Choose one</option>
          <template x-for="u in acctUsers" :key="u['USERID']">
            <template x-if="p_person_to == u['USERID']">
            <option :value="u['USERID']" x-text="u['FULLNAME']" SELECTED></option>
            </template>
            <template x-if="p_person_to != u['USERID']">
              <option :value="u['USERID']" x-text="u['FULLNAME']"></option>
            </template>
          </template>
          </select>
        </div>
any ideas or better ways to do this?
1
ah, i think the reason the second x-if doesn't work is because a template (specifically, the template with x-for) must only have one child element. Still don't know how to solve this.
m
Hemi, I'd reach out to Ray Camden on Twitter or Mastadon. He's been playing a lot with Alpine.
h
yeah, he's the one that inspired me to learn it after watching his session
You happen to know if Ray is on Slack? I don't use Elon's Twitter or Mastadon?
ah, I see the user list and he's in it... i'll try tagging @raymondcamden
Here's how I got it to work. I ran a filter on the data that populates all the list options and added a column called 'selected' and set it to true if the userid matches the list option:
Copy code
this.acctUsers.filter((row, index) => {
            if(row['USERID'] == this.p_person_to) row['SELECTED'] = true;
            else row['SELECTED'] = false;
            return true;
          });
then changed the template as follows:
Copy code
<select id="p_person_to" id="p_person_to" name="p_person_to" required>
            <option value="">Choose one</option>
          <template x-for="u in acctUsers" :key="u['USERID']">
            <option :value="u['USERID']" x-text="u['FULLNAME']" :selected="u['SELECTED']"></option>
          </template>
          </select>