HTML form send unchecked checkboxes - html

I need to send a very long form with lots of checkboxes. They're grouped by areas, like this:
<fieldset>
<legend>Whatever1</legend>
<div class="checkbox-list">
<label class="checkbox inline"><input type="checkbox" name="Hobbies" value="Arts"> Arts</label>
<label class="checkbox inline"><input type="checkbox" name="Hobbies" value="Bars"> Bars</label>
<label class="checkbox inline"><input type="checkbox" name="Hobbies" value="Books"> Books</label>
(more items)
</div>
</fieldset>
<fieldset>
<legend>Whatever2</legend>
<div class="checkbox-list">
<label class="checkbox inline"><input type="checkbox" name="Interests" value="Architecture"> Architecture</label>
<label class="checkbox inline"><input type="checkbox" name="Interests" value="Audio"> Audio/vídeo</label>
<label class="checkbox inline"><input type="checkbox" name="Interests" value="Business"> Business</label>
(more items)
</div>
</fieldset>
The form is much longer, but you get the idea.
Using name="Hobbies" value="Arts" my django backend receives all the checkboxes grouped in a Hobbies array, which is very convenient, but I need to know the unchecked checkboxes, too. I know about the hidden input trick, but it's not useful to me, because I use the value field as part of the checkbox grouping.
Any idea about what can I do?

Well, as I guess you already know, there is fundamentally no way of asking the browser which boxes were left unticked. Blame the inventors of HTML forms...
Here are a few simple approaches which don't break your grouping logic:
Re-generate the list of checkboxes which you displayed on your server side. This is preferable in a lot of cases anyway, since it means you're not trusting the data coming back to be exactly what you displayed. (Consider what happens if I use a debugging tool like Firebug to delete one of your checkboxes, or add a new one...)
Include hidden inputs with a corresponding name for each checkbox - "Interests_All", "Hobbies_All", etc - so that you have two arrays of data, one including just the checked items, one including everything displayed.
Use radio buttons instead of check-boxes. Yes, they display differently, but they can have the functionality you want of submitting a Yes/No value, rather than just adding to the array or not.

How about setting a default false value for each checkbox in the backend. If a value has been passed by the browser, you can then change the value to true.

You could add a hidden input field, and on form submit, use jQuery to populate the value of the hidden input with an array containing the values of the unchecked checkboxes:
$("form").on("submit", function(e) {
e.preventDefault();
// Create an array of unchecked Hobbies
var uncheckedValues = [];
$(this).find("input[name='Hobbies']:not(:checked)").each(function() {
uncheckedValues.push(this.value);
});
// Set the uncheckedValues array as hidden input value
$("#your-hidden-input").val(uncheckedValues);
alert($("#your-hidden-input").val());
// Handle the form submission
handleFormSubmit();
});
See DEMO.

I've solved it. The idea was in IMSoP's answer. Here's my solution, maybe it can help someone:
<fieldset>
<legend>Whatever1</legend>
<div class="checkbox-list">
<input type="hidden" name="Hobbies_Arts">
<label class="checkbox inline"><input type="checkbox" name="Hobbies" value="Arts"> Arts</label>
<input type="hidden" name="Hobbies_Bars">
<label class="checkbox inline"><input type="checkbox" name="Hobbies" value="Bars"> Bars</label>
<input type="hidden" name="Hobbies_Books">
<label class="checkbox inline"><input type="checkbox" name="Hobbies" value="Books"> Books</label>
(more items)
</div>
</fieldset>
With that, is very easy to handle the lists in the django side.

Related

Why do we use "for" attribute inside label tag?

I've been learning about the "for" attribute in HTML and what it does but I've stumbled upon a weird example that I've yet to understand
Code1
<input id="indoor" type="radio" name="indoor-outdoor">
<label for="indoor">Indoor</label>
Code2
<label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label>
<br>
<label><input type="checkbox" name="personality"> Loving</label>
I understand why "for" is used in the first block of code but I don't understand why the second code used "for" and "id" implicitly when it could've just worked fine without them.
Any help?
It is correct, that it works without it. But it is useful to connect the label with the input field. That is also important for the accessibility (e.g. for blind people, the text is read).
The browsers also allow you to click the labels and automatically focus the input fields.
For checkboxes this can be useful as well. But for these, you could also surround the checkbox-input like this:
<label>
<input type="checkbox"> I agree with the answer above.
</label>
In this case, the checkbox is automatically checked when you click on the text.
The surrounding of the inputs with a label works with every input field. But the text, that describes the input field, should always be inside it. That what for is for: When your HTML disallows the label-surrounding, you can use the for-attribute.
The the both following examples:
Simple stuctured:
<label>
Your Name:<br>
<input type="text"/>
</label>
Complex structure around input fields:
<div class="row">
<div class="col">
<label for="name">Your Name:</label>
</div>
<div class="col">
<input type="text" id="name" />
</div>
</div>
It could be used without "for" attribute, and it will be fine, according to docs.
This is just one option how to use "for" to omit confusing developers.
Anyway, in case of placing checkbox inside label, you can skip "for" and it will be fine.
<!-- labelable form-relation still works -->
<label><input type="checkbox" name="personality"> Loving</label>
"for" approach much preferable if you want to style it, f.e. using Bootstrap
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">
Default checkbox
</label>
</div>
To be able to use the label with the check box.
E.g., when rendered, click the label and it will toggle the check box ticked state.
Edit: Further to this, it allows putting the label anywhere on the page.

Post the checkboxes in an array that are unchecked

I want to get all values from a set of checkboxes via POST - also the ones that return false. For a single checkbox there is a solution here. It's hacky but it does at least not require Javascript. But how about this
<input name="link[]" type="checkbox"/>
<input name="link[]" type="checkbox"/>
...
A similiar solution as the one suggested in the other post would not work, because it keeps iterating:
<input name="link[]" type="hidden"/> <!-- 0 -->
<input name="link[]" type="checkbox"/> <!-- 1 -->
<input name="link[]" type="hidden"/> <!-- 2 -->
<input name="link[]" type="checkbox"/> <!-- 3 -->
...
The one other way I can think of is explicitly giving them indexes
<input name="link[0]" type="hidden"/>
<input name="link[0]" type="checkbox"/>
<input name="link[1]" type="hidden"/>
<input name="link[1]" type="checkbox"/>
<input name="link[2]" type="hidden"/>
<input name="link[2]" type="checkbox"/>
Or you could do this, without using hidden inputs:
<input name="link[0]" type="checkbox"/>
<input name="link[1]" type="checkbox"/>
<input name="link[2]" type="checkbox"/>
Then check for missing array indexes server-side.
When a form is submitted, all the form elements that have a name attribute specified for them submit their name and their value. With most form elements, the value comes from what the user inputs.
When you submit a form that has radio buttons and/or checkboxes in it, only the name/value pairs form the checked checkbox or radio button is submitted. This way, your form processing code doesn't have to sort out which buttons/boxes were checked. A consequence of this however, is that both checkboxes and radio buttons must have a value set for their value attribute. This value is how you will know which button/box was selected (receiving a name/value pair of checkbox4=true doesn't really tell you much.)
In the following code, we will know which checkboxes were checked just by looking at the data submitted to the form's action which checkboxes were checked and what the meaning of those checks were:
<input type="checkbox" name="chkStudent1" value="Mary"> Mary
<input type="checkbox" name="chkStudent2" value="John"> John
<input type="checkbox" name="chkStudent3" value="Joe"> Joe
Now, when the form is submitted, and let's say you check the second checkbox, the name/value pair of chkStudent2=John will be submitted. Your form processing code will know exactly which element was checked and the corresponding data will be available to that code.

html/Thymeleaf - Implementation of radio input

I am working on this little project with an online order service for pizzas.
(using Spring Web MVC, Thymeleaf, ...)
Yesterday, someone helped me out adding inputs for selecting an specific amount and size.
<div>
<form th:action="#{/saveOrderAndReload(name=${pizza.name})}" method="post">
<div class="input-group">
<span class="input-group-addon">Bestellmenge (min. 1, max. 10):</span>
<input type="number" name="amount" class="form-control" min="1" max="10" placeholder="1"/>
</div>
<div class="input-group">
<input type="radio" name="size" value="1"> Klein</input>
<input type="radio" name="size" value="2"> Mittel</input>
<input type="radio" name="size" value="3"> Gross</input>
</div>
<div class="form-group">
<div class="form-group">
<input type="submit" class="btn btn-primary btn-success" value="zur Bestellung hinzufuegen"/>
</div>
</div>
</form>
The "amount" field protects the application itself from false input because it only allows integers from 1-10, otherwise the User gets a notification asking for an numeric input.
The radio input where you can select between 3 sizes has 2 problems:
1) The buttons arent among themselfes, they are next to each other.
2) I dont know how to prevent the user from doing no input.
I looked around for quite some time finding the standart html version for this:
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
And something like this:
<ul>
<li th:each="ty : ${allTypes}">
<input type="radio" th:field="*{type}" th:value="${ty}" />
<label th:for="${#ids.prev('type')}" th:text="#{${'seedstarter.type.' + ty}}">Wireframe</label>
</li>
</ul>
We didnt learn anything about the second one so I decided to use the standart html. But I does not want to work like that example: It gets errors that this "checked" expression is not allowed, " tag is not closed" and whatnot.
So my questions are:
1) What can I do to make the input look better?
2) How can I set like a placeholder or standart value so the application always gets this input and does not crash?
As you might have realized I am a complete beginner with this type of stuff so be lenient ;)
Answer 1
If you want the change the way the radio buttons are looking, this might help: http://code.stephenmorley.org/html-and-css/styling-checkboxes-and-radio-buttons/.
Some notes and Answer 2
It gets errors that this "checked" expression is not allowed, " tag is
not closed" and whatnot.
Thymeleaf dies not allow attribute minimization. That means that you need to provide a value for each attribute. You just have to use checked="checked" instead of checked.
<form method="post">
<!-- Make sure to always set a value for attributes when using thymeleaf (use checked="checked" instead of checked) -->
<div><input type="radio" name="gender" value="male" checked="checked" />Male</div>
<div><input type="radio" name="gender" value="female" />Female</div>
<div><input type="radio" name="gender" value="other" />Other</div>
</form>
This is actually wrong:
The "amount" field protects the application itself from false input
because it only allows integers from 1-10, otherwise the User gets a
notification asking for an numeric input.
You are only validating on the client side. Clientside validation is okay if you want to give your users feedback even before they submit your form but it is not enough to protect yourself from bad input.
Nathan Long does explain why client side validation is not enough pretty well (JavaScript: client-side vs. server-side validation):
It is very dangerous to trust your UI. Not only can they abuse your
UI, but they may not be using your UI at all, or even a browser. What
if the user manually edits the URL, or runs their own Javascript, or
tweaks their HTTP requests with another tool? What if they send custom
HTTP requests from curl or from a script, for example?
As you are using spring-mvc you should take adventage of it and take a look at the following tutorial: https://spring.io/guides/gs/validating-form-input/.
To provide default values when working with spring-mvc you can just give the field a value:
public class PersonForm {
// this field will have a default value (foo)
// NotNull will ensure that a value is set for this field when validated by spring (however it can be an empty string... take a look at hibernates #NotBlank annotation if you want to prevent empty string or use a regex)
#NotNull
private String gender = "foo";
}
However default values often dont make sense for input[type="text"]. If you want to prodive a placeholder for any input you could just use the html attribute placeholder="the placeholder":
<input type="text" name="name" value="" placeholder="Enter your name" />

What does the value attribute mean for checkboxes in HTML?

Suppose this checkbox snippet:
<input type="checkbox" value="1">Is it worth?</input>
Is there any reason to statically define the value attribute of checkboxes in HTML? What does it mean?
I hope I understand your question right.
The value attribute defines a value which is sent by a POST request (i.e. You have an HTML form submitted to a server).
Now the server gets the name (if defined) and the value.
<form method="post" action="urlofserver">
<input type="checkbox" name="mycheckbox" value="1">Is it worth?</input>
</form>
The server would receive mycheckbox with the value of 1.
in PHP, this POST variable is stored in an array as $_POST['mycheckbox'] which contains 1.
I just wanted to make a comment on Adriano Silva's comment.
In order to get what he describes to work you have to add "[]" at the end of the name attribute, so if we take his example the correct syntax should be:
<input type = "checkbox" name="BrandID[]" value="1">Ford</input>
<input type = "checkbox" name="BrandID[]" value="2">GM</input>
<input type="checkbox" name="BrandId[]" value="3">Volkswagen</input>
Then you use something like: $test = $_POST['BrandID']; (Mind no need for [] after BrandID in the php code).
Which will give you an array of values, the values in the array are the checkboxes that are ticked's values.
Hope this helps! :)
One reason is to use the ease of working with values ​​in the system.
<input type="checkbox" name="BrandId" value="1">Ford</input>
<input type="checkbox" name="BrandId" value="2">GM</input>
<input type="checkbox" name="BrandId" value="3">Volkswagen</input>
When the form is submitted, the data in the value attribute is used as the value of the form input if the checkbox is checked. The default value is "on".
$('form').on('change', update).trigger('change')
function update() {
var form = $(this)
form.find('output').text('→ ' + form.serialize())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="foo">
<output></output>
</form>
<form>
<input type="checkbox" name="foo" checked>
<output></output>
</form>
<form>
<input type="checkbox" name="foo" value="1" checked>
<output></output>
</form>
<form>
<input type="checkbox" name="foo" value="bananas" checked>
<output></output>
</form>
For the sake of a quick glance answer, from MDN
when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute
It can be confusing because seeing something like
<input type='checkbox' name='activated' value='1'> might lead one to believe that the 1 means true and it will be treated as though it is checked, which is false. The checked attribute itself also only determines if the checkbox should be checked by default on page load, not whether it is currently checked and thus going to be submitted.

Web part checkboxes does not work as it should

I am working on a Sharpoint site. I have created a Form Web Part, which is connected to a status column in a List. The web part is used to filter the list. In the web part, I have 7 checkboxes to filter the list. When I select one of the checkbox, the list gets filtered, as expected, but it checks all other 6 checkboxes. This is really annoying behavior. Can someone help?
Here is the HTML source I used for webpart:
------>
<div onkeydown="javascript:if (event.keyCode == 13) _SFSUBMIT_">
<input type="checkbox" name="Status" value="Approved" checked="checked">Approved<br>
<input type="checkbox" name="Status" value="Beta-Test" >Beta-Test<br>
<input type="checkbox" name="Status" value="Under-Development" >Under-Development<br>
<input type="checkbox" name="Status" value="Created" >Created<br>
<input type="checkbox" name="Status" value="Rejected" >Rejected<br>
<input type="checkbox" name="Status" value="Estimated" >Estimated<br>
<input type="checkbox" name="Status" value="Deployed" >Deployed<br>
<input type="button" value="Go" onclick="javascript:_SFSUBMIT_"/>
</div>
<------
Select one of the status.
Click on GO.
Filter operations on the list suceeds, but all the checkboxes are selected :(.
Thanks in advance.
Madhu
I'm not good in javascript but i can say that you have it works if u get one value. But as u want to store multiple value need to have an array. That is name="status[]" . This may work