-1

I have a webiste where users can find a discord server with their option,such as if server is NSFW, premium,member count and tags. I tried to do a dinamic filter using the request query from the form where users filter the servers,but I can't find a solution to send the value of the input checkbox to the form even if the input is unchecked.

<form method="get" action="/search/">
  <div class="setting">
    <input type="checkbox" 
            name="premium" 
             id="uppercase" 
          value="true" 
        onClick="if(this.value === 'false') {this.value = true} else {this.value =false}" 
        checked />
    <label for="uppercase">Premium</label>
  </div>
</form>

when the input is checked the value is sent to the url, like /search?premium=true, but when the checkbox is unchecked,nothing is sent to the url and this causing me trouble,cause I need those parameters in order to make the filter to work. Is there something that I can do to the send the value of the check input even if it's unchecked?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Bruno God
  • 79
  • 1
  • 9

1 Answers1

1

Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked. If it is, then the value of the checkbox's value attribute is reported as the input's value.

Input type checkbox

If you need false values for unchecked checkboxes you could use JS manually add them to the FormData and submit that instead of the default submit event.

const form = document.querySelector('form')

form.addEventListener('submit', (e) => {
  e.preventDefault()
  const data = new FormData(form);

  const premiumVal = data.get('premium')
  if (!premiumVal) {
    data.append('premium', false)
  }
  
  const queryString = new URLSearchParams(data).toString()
  const formAction = form.action + "?" + queryString
  
  console.log(formAction)

  //fetch(formAction, {
    //method: form.method
  //})
})
label {
  display: block
}
<form method="get" action="/search">
  <div class="setting">
    <label>Premium
      <input name="premium" type="checkbox" value="true" checked />
    </label>
    <label>Other
      <input name="other" value="other val" />
    </label>
  </div>
  <button>submit</button>
</form>
ksav
  • 20,015
  • 6
  • 46
  • 66