Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use the svelte-forms-lib with multiple select or radio buttons #141

Closed
ntegral opened this issue Nov 3, 2021 · 1 comment
Closed
Labels
enhancement New feature or request

Comments

@ntegral
Copy link

ntegral commented Nov 3, 2021

I have read through the initial documentation that you have posted for this library. Do you have any documentation on how to use this library with group radio buttons or multiple selections

Thanks

@ntegral ntegral added the enhancement New feature or request label Nov 3, 2021
@larrybotha
Copy link
Collaborator

@ntegral something like the following: https://codesandbox.io/s/heuristic-boyd-7vsw7

<script>
  import { createForm } from "svelte-forms-lib";

  const { form, handleChange, handleSubmit, updateField } = createForm({
    initialValues: {
      multiSelect: "",
      radioSelect: "",
    },
    onSubmit: values => {
      alert(JSON.stringify(values));
    }
  });

  const selectOptions = ['one', 'two', 'three']

  function handleSelectChange(event) {
    const value = [...event.target.selectedOptions].map(
      option =>  option.value
    )
    
    updateField("multiSelect", value)
  }
</script>

  <form on:submit|preventDefault={handleSubmit}>
    <div>
      <div>
        <label for="radioSelect">radio select</label>
      </div>
      {#each selectOptions as o}
      <div>
        <input 
          type="radio"
          name="radioSelect"
          id={`radio-${o}`}
          value={o}
          on:change={handleChange}
          checked={$form.radioSelect == o}
        >
        <label for={`radio-${o}`}>{o}</label>
      </div>
      {/each}
    </div>

    <br />
    <div>
      <div>
        <label for="multiSelect">multi select</label>
      </div>
      <select 
        name="multiSelect"
        id="multiSelect"
        on:input={handleSelectChange}
        multiple
        size={selectOptions.length}
      >
          {#each selectOptions as o}
          <option value={o}>{o}</option>
          {/each}
      </select>
    </div>

    <button type="submit">Submit</button>
  </form>

Note you'd need to manually handle the multiple select, as the value attribute doesn't contain all the selected values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants