Alpine.js x-bound: Shorthand Syntax

by rameel

HTML

<div class="form" x-data="{ 
  user: { 
    name: 'Guest', 
    feedback: '', 
    agree: false, 
    contact: 'email' 
  },
  methods: [
    { value: 'email', label: 'Email' },
    { value: 'phone', label: 'Phone' },
    { value: 'sms', label: 'SMS' },
    { value: 'none', label: 'No Contact' }
  ]}">
  <label>
    Name: 
    <input &value="user.name" />
  </label>  

  <label>
    Feedback:
    <textarea &value="user.feedback"></textarea>
  </label>

  <label>
    <input &checked="user.agree" type="checkbox" />
    I agree to the terms
  </label>

  <label>
    Contact Preference:
    <select &value="user.contact">
      <template x-for="m in methods" :key="m.value">
        <option :value="m.value" x-text="m.label"></option>
      </template>
    </select>
  </label>

  <pre x-format><code>{{ JSON.stringify(user, null, 2) }}</code></pre>
</div>


<script src="https://cdn.jsdelivr.net/npm/@ramstack/alpinegear-bound@1/alpinegear-bound.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@ramstack/alpinegear-format@1/alpinegear-format.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3/dist/cdn.min.js" defer></script>

CSS

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
  color: #0f172a;
}

h3 {
  margin: 0;
}

.form {
  display: flex;
  flex-direction: column;
  flex-basis: auto;
  background: #fff;
  padding: 1.5rem;
  width: 100%;
  min-width: 320px;
  max-width: 480px;
  border-radius: 4px;
  border: 1px solid rgba(15, 23, 42, 0.15);
  box-shadow: 0 6px 18px rgba(10, 15, 30, 0.06);
  gap: 1rem;
}

label {
  display: flex;
  flex-direction: column;
  gap: 0.5em;
  font-size: 0.9rem;
  font-weight: 600;
  user-select: none;
}

label:has(input[type="checkbox"]),
label:has(input[type="radio"]) {
  display: flex;
  align-items: center;
  flex-direction: row;
  gap: 0.4rem;
  font-weight: 400;
}

input,
textarea,
select {
  display: block;
  width: 100%;
  height: 2.5rem;
  padding: 0.5rem 0.75rem;
  font-size: 0.95rem;
  border: 1px solid rgba(15, 23, 42, 0.15);
  border-radius: 3px;
  background: #fff;
  outline: none;
  transition: border-color 0.1s, box-shadow 0.1s;
  line-height: 1.3;
}

textarea {
  height: auto;
  min-height: 100px;
  resize: vertical;
}

input:focus,
textarea:focus,
select:focus {
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}

input[type="checkbox"],
input[type="radio"] {
  width: 1.1rem;
  height: 1.1rem;
  margin: 0;
}

pre {
  background: #eee;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 13px;
  line-height: 1.4;
}