Home > Back-end >  Is the value= part of an HTML input checkbox required or can the value itself suffice
Is the value= part of an HTML input checkbox required or can the value itself suffice

Time:11-04

I notice then when I am writing HTML, e.g., in a svelte template, that the prettier formatter that I have configured for my editor always removes the value= part so that

<label>                                                                
<input                                                               
   type="checkbox"                                                    
   bind:group={foo.bar}                    
   name="bar"                                          
   value={value} <———                                                           
/>                                                                   
 {value}                                                              
</label>

gets turned into

<label>                                                                
<input                                                               
   type="checkbox"                                                    
   bind:group={foo.bar}                    
   name="bar"                                          
   {value} <——-                                                           
/>                                                                   
 {value}                                                              
</label>

and yet when I look up the input type=‘checkbox’ element reference docs on MDN, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox, it doesn’t say value= is optional. I am using the input in a form and I thought it was necessary to have value=. Of course, empirically I can test this, but I haven’t yet. I am curious to hear what you may share about this.

CodePudding user response:

The name of the attribute is required in HTML. The thing is that the code that you are sharing may look like HTML, but it is not. It is an HTML-looking JavaScript expression that will later be processed by Svelte and turned into actual HTML.

In the Svelte documentation they explain what you are seeing:

When the attribute name and value match (name={name}), they can be replaced with {name}.

<!-- These are equivalent -->
<button disabled={disabled}>...</button>
<button {disabled}>...</button>

That's the reason why your editor removes the value={value} and reduces it to just {value}: because the property and the variable with the value have the same name.

If you were using actual HTML, then you wouldn't be able to omit the property name and would need to write the whole thing value="value" (notice that it would be with quotes instead of curly braces.)

  • Related