Home > Software engineering >  Svelte select issue where disabled value not binding on submit
Svelte select issue where disabled value not binding on submit

Time:12-15

A Svelte select control that receives a value to match in a list from a rest api:

<script>
export let data;
export let name;
export let required;
export let disabled;

let options = [];

onMount(async () => { 
  options = await buildOptionsList ();
});

async function buildOptionsList () {
  let rv = [];
  try {
    let req = await fetch (....)
    req.data.forEach (item => {
      list.push ({
        value: item.value,
        text: item.text
      });
    });
  } catch (e) {
    ...
  }
  return rv;
}
</script>

<select  {required} {disabled} name="{ name }" id="{ name }" 
    bind:value={data}>
    {#each options as option}
      <option value={option.value}>{ option.text }</option>
    {/each}
</select>

This all works ticketyboo, however, in certain cases (category of user) I need to make the select disabled.

In such cases, data appears correctly as the selected item in the list, and greyed out as the input is disabled; however on submit the relevant item in the form data is null.

How do I address this problem?

CodePudding user response:

disabled form fields are not sent. For input element that could be solved by using readonly instead, but select elements do not support this.

A common approach is to send a hidden field, something like:

{#if disabled}
  <input type=hidden {name} value={data} />
{/if}

(Though if the field is disabled, the intention is probably that it cannot be changed by the user, so if the server actually uses that value, that is probably an error. You cannot trust data from the client to follow your rules.)

  • Related