What is the correct and most safe way to check if HTML form checkboxes and such have been POST-set? - html

This has confused me since the early days. Maybe it's just in my head, but it seems to me as if this has varied over time, between browsers, and possibly even depending on the local language/locale.
Basically, whenever I need to check if a HTML input of type "radio" or "checkbox" has been set, I always do:
if (isset($_POST['the_name']) && trim($_POST['the_name']))
// do stuff
This just makes sure that the POST variable is sent whatsoever (which in itself doesn't mean that it was actually checked/selected, as far as I can tell, since its "value" can be an empty string) and that it's something other than '' (empty string). It seems like this has worked for a long time, but I have two problems with it:
It's ugly. I need to abstract it into a function, but then I want to know if it's a good idea in the first place, or wrong somehow.
It makes the assumption that any non-empty string value means "checked" or "selected", whereas the standard may say a specific string value such as "on", or maybe any number of such strings depending on the language/locale.
Are there cases where my above code falls apart? Do browsers ever submit POST forms where they include names which have no user input/selection in the HTTP request? Or does the existence of a name in the POST blob mean that that "field" has been actively changed/set/checked/selected?

The idea behind checkboxes is that the value is sent over to the server only if the checkbox was checked when submitting the form. The value can be anything, even an empty string. As long as the field is part of the transmitted form it means the box was ticked.
The value attribute is one which all <input>s share; however, it serves a special purpose for inputs of type checkbox: 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. If the value is not otherwise specified, it is the string on by default.
This means you could have a form like this:
<form action="" method="get">
<input type="checkbox" name="c1" value="">
<input type="submit" value="Send">
</form>
If the checkbox is not checked when submitting then $_GET will be an empty array.
If the checkbox is checked then the value of $_GET will be:
array('c1' => '');
To check whether the box was ticked when sending the form you only need isset()
if (isset($_POST['c1']) {
// The box was checked!
}
Sometimes you would like to assign a value attribute to your checkbox. In such situations you can use the shorthand operator for isset() function ??.
// Create a variable from the checkbox value or assign an empty string if the box was not checked
$nyCheckbox = $_POST['c1'] ?? '';

Related

Best accessible way to show a default for a form field

What's the best/recommended way to indicate a form field will have a particular default value if you don't fill it out? I'm especially thinking about fields that are dynamic based on other fields, and wanting it to be correctly accessible.
Think a URL slug. When creating an account, if you fill the field out then that's fine. If you don't, a value will be generated based on your username. But it won't be the same as your username, just generated from it.
Actually setting the form field seems bad because it makes it less obvious you can change it yourself.
I'm not sure if placeholder text works here, but I assume not. I could do an aria-labelledby pointing to something that says "Default value: xyz" but I'm not sure if that will work, or how well it will be understood by screen readers - especially if it's changing automatically.
Cheers
The best way to do this is to populate the input and expose the fact that it was automatically filled in via the label as an extra bit of information.
Labels on inputs are read once you focus the related input.
For this reason we can generate labels "on the fly" to contain whatever we want.
As such the best option here would be to generate the label on blur of the first input that the second input depends on.
Within the label we add the instructions that explain why this input is already filled in.
We then auto populate the second input based on the input of the first.
In the below example I have appended "URL" to the first input value in order to simulate some sort of transformation from username to URL.
I also remove the explanation in parenthesis if the user has changed the second input value.
$('#iUsername, #iUserURL').on('blur', function(){
var ElUserName = $('#iUsername');
var ElUserURL = $('#iUserURL');
if(ElUserURL.val() == ""){
ElUserURL.val(ElUserName.val() + "URL");
$('label[for="iUserURL"]').text("user url (you can change this if you want, we have set it as " + $('#iUsername').val() + "URL)");
}else if(ElUserURL.val() != ElUserName.val() + "URL"){
$('label[for="iUserURL"]').text("user url");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="iUsername">User Name</label><br/>
<input id="iUsername" /><br/>
<hr/>
<label for="iUserURL">User URL</label><br/>
<input id="iUserURL" /><br/>
<hr/>
<label for="itest">I have added this third input just so you have something to tab too, it does not add anything to the fiddle</label><br/>
<input id="itest" />

HTML checkbox default

I have an HTML checkbox:
<input name="foo" id="foo" type="checkbox" value="1" 𝙨𝙩𝙖𝙩𝙪𝙨/>
In my application, the checkbox should retain its checked status between form submits (method=GET), so my server-side code simply inserts the checked status flag if foo is found in the GET-data.
if "foo" in GET:
𝙨𝙩𝙖𝙩𝙪𝙨 = ' checked'
else:
𝙨𝙩𝙖𝙩𝙪𝙨 = ''
This is fine, and it works. However, the logic breaks down when I want the checkbox checked by default, because, from the server side, I am unable to differentiate between:
the checkbox being unchecked by the user ("foo" not in GET) – in which case I should leave the checkbox unchecked.
the user having visited the form for the first time and having not yet specified a value (also "foo" not in GET) – in which case I should check the checkbox by default.
I have considered using a hidden input that tells me whether this is a user-submit or not, but this messes up the URL since the data is passed in GET. I feel there should be a better way.
Assuming the server knows:
All the (checkbox)inputs
Which of these inputs are default checked
You can reverse the test:
Test all known server-side fields (loop server-side data to...)
See if they exist in the received data (... test client-data (every time))
If the are checked by default, and not in the data, you know the user unchecked it

How does MVC decide which value to bind when there are multiple inputs with the same name?

I have an edit page where several fields are conditionally disabled, based on the user's role. When the fields are disabled, their values are not posted to the server (as expected), which causes the ModelState to be invalid, as the values are required.
To get around this, I want to add Html.HiddenFor() for the fields; so that a value will still get posted (and so that it will retain those values if the View is returned). However, in the case that those fields are not disabled, I will then have both a TextBoxFor and a HiddenFor going to the same model property.
I have run a couple tests, and it appears that when this happens, the value of the first element on the form will be binded to the model, while the next one just gets ignored. If this is the case, then I should be able to just put the HiddenFor after the TextBoxFor, in which case the value of the hidden input will only be posted when the regular input is disabled.
#Html.TextBoxFor(m => m.FirstName)
#Html.HiddenFor(m => m.FirstName) #*Only gets binded to the model if the above text box is disabled*#
(There is some JavaScript that conditionally disabled the visible TextBox).
So two questions: 1) Is it documented that MVC binding will always work this way; can I safely have both of these fields?
And, 2) Is there a better approach to accomplishing this? I know that I can but the HiddenFor inside an #If statement so that it will only get created if the TextBox is disabled; but that is a lot of extra logic in the View that I'd like to avoid.
The DefaultModelBinder reads the values from the request in order and binds the first matching name/value pair and ignores subsequent matches (unless the property is IEnumerable). This is how the CheckBoxFor() method ensures a true or false value is always submitted to the controller (the method generates a checkbox with value="True" and a hidden input with value="False"), so you can safely add the hidden input after the textbox.
One option you might consider rather than a disabled textbox, is to make it readonly, which means it will always submit a value, therefore you only need one input (and you can always style it to look disabled if that is what you want).

Why does the value of an input with type="number" remain 'NaN' after I delete the contents?

Very easy question but too much confused about whats the scope of input type='number' field.
Actually working on forms found error during validation of the form.
<input type="number" placeholder="Demo Number Field" class="form-control" [(ngModel)]="demoNumber">
{{demoNumber}}
<input type="text" placeholder="Demo Text Field" class="form-control" [(ngModel)]="demoText">
{{demoText}}
When I load the page for the first time these input fields have values of null but whenever I fill those fields once and then delete all contents from both fields, the value of Textfield is null but the value of numberfield remains NAN instead of null. Why is this so? Due to this, the form is valid even if number field is empty (after removing content) which is wrong. How can I fix this?
One more thing - why does numberfield accept some characters like e but not all characters like d,f,r, etc.?
here is plnkr which i have used for demo purpose
Plunker code
PS :- Is there any way to restrict user not to allow e or something else in the number field ?
Edit:: chrome accepts e, firefox also accepts e. because e can exist in the form of 1.1e+10.
However firefox does't allow e if its in invalid formats like, e or 1e etc. Firefox allows if its in valid format like 1.1e+10.
Original answer:
After the edit and making the text box empty, scope of text field is set to empty string, not null.
Same way, scope of number field is set to empty string. When you try to render it, you will get NaN.
For your second question, I have tried in firefox and it is not accepting any characters like e, f, r etc. They are being shown in red color.

Putting HTML in a hidden form field in Django

I'm having a problem with a template: I'm trying to display a form for changing a value, in which the user enters the current value in a textarea and the old value is kept inside a hidden field for auditing purposes. This value is generally some HTML, and when I render the page this HTML in the hidden field seems to get partially rendered: the value attribute of my hidden field gets closed by the first quotation marks inside the entered HTML, and the rest of the HTML spews out onto my page. I've tried using the escape decorator but that hasn't changed anything.
Firstly, a better solution might be to keep the audit value in a separate model field defined with editable=False. You can still perform checks against the value in a form's clean method:
def clean(self):
cleaned_data = super(SomeForm, self).clean()
if instance.the_audit_field == cleaned_data['the_editable_field']:
...raise a validation error?
You can also modify the value of the audit field from within the model's save method.
Secondly, assuming you must do it the way you are now, let me address the non-escaped value in your template. I assume you're using something like the following:
<textarea value="{{ form.the_audit_field.value }}"></textarea>
You should instead use the following:
<textarea>{{ form.the_audit_field.value }}</textarea>
Note, the value goes inside the textarea, instead of in the value attribute of it.
An even better way to do it is to simply allow Django to render the field for you like the following:
{{ form.the_audit_field }}