Set an input's default value - html

I have this input:
<input name="giftwrap" type="checkbox"/>
However, when the form is submitted and the checkbox has not been checked, I get a null rather than a false. I want a false to be submitted.
I'm feeling if I give the input a default value of unchecked it'll return false rather than null as if I tick and then untick the input I get false.
So how do I set the input as checked, and how do I set the input as unchecked?

$(function() {
$('input[name=giftwrap]').on('change', function() {
$(this).next().text(this.value = this.checked);//<-- note its assignment
}).trigger('change');//<-- trigger on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="giftwrap" type="checkbox" /><span></span>

You can add a checked attribute:
<input name="giftwrap" type="checkbox" checked/>
Or maybe you want something like this:
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
Details: Post the checkboxes that are unchecked
(Read the comments as well.)

Related

Multiple values in radio input within form with vanilla HTML

I am aiming to create a form to handle disabled JavaScript experience for a small component on my website. Currently I have the following form:
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="radio" id="uid1" name="someParam" value="fruity" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" />
<label for="uid2">Vegetable</label>
...other radio options
<input type="submit" value="Submit" />
</form>
Clicking on either of the radio options and then on the submit button will result in:
option 1: https://mywebsite.com/somedirectory/?someParam=fruity
option 2: https://mywebsite.com/somedirectory/?someParam=veggie
How can I add another value for each of the radio options? Say I would like to pass someOtherParam which is unique for each option and I would like to get this as output for my options:
option 1: https://mywebsite.com/somedirectory/?someParam=fruity&someOtherParam=apple
option 2: https://mywebsite.com/somedirectory/?someParam=veggie&someOtherParam=pepper
What I have tried is:
<input type="radio" id="uid1" name="someParam" value="fruity&someOtherParam=apple" />
<input type="radio" id="uid2" name="someParam" value="veggie&someOtherParam=pepper" />
However, the & symbol is converted to %26 inside the link and feels too hacky. Is there a better way to achieve this? Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?
P.S. I am aiming for pure HTML experience with no Javascript involved. Is that possible?
I'm pretty sure this is not posible in modern browsers without the use of JS. Maybe on old browsers you could do some tricks with CSS and display:none because it used to not send fields with display:none, but nowdays that is not an option.
If you can allow Javascript, you can add a data attribute to each radio option and use it to populate an extra hidden input on change.
document.querySelectorAll('input[type=radio][name="someParam"]')
.forEach(radio => radio.addEventListener('change', (event) =>
document.getElementById('someOtherParam').value = event.target.dataset.extraValue
));
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="radio" id="uid1" name="someParam" value="fruity" data-extra-value="apple" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" data-extra-value="pepper" />
<label for="uid2">Vegetable</label>
<input type="hidden" id="someOtherParam" name="someOtherParam">
<input type="submit" value="Submit" />
</form>
To add another radio group independent from others, use a distinct name property. For example, to add a second parameter called someOtherParam to the request, create a radio group with name="someOtherParam":
<input type="radio" id="uid3" name="someOtherParam" value="apple" />
<input type="radio" id="uid4" name="someOtherParam" value="pepper" />
And add their correspondent labels.
Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?
You can add the required attribute to prevent the browser to send the form before all the inputs have a value.
Without javascript, what you're describing cannot be done.
What you could do, as other posters have suggested is:
Create radio buttons for the list of options that are possible for each category (fruits / vegetables etc)
<input type="radio" id="uid3" name="someOtherParam" value="apple" />
<input type="radio" id="uid4" name="someOtherParam" value="pepper" />
When processing the input on your server side code, check if you have received a value or not. If not, you can choose a default option (apple or whatever). On your page you can mention what the default option would be in case they don't make a selection.
You could make some of the input required as suggested, but you would still have to make check on the server side that the input has been received, since the required attribute is just a suggestion to users browsers - it won't stop a malicious persons from making a request without that parameter by running a script etc.
To submit extra information to the server, you can use a hidden input type and change value as per your needs using javascript.
HTML code
<form method="GET" action="">
<input type="radio" id="uid1" name="someParam" value="fruity" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" />
<label for="uid2">Vegetable</label>
<input type="hidden" id="uid3" name="someOtherParam" value="" readonly required />
<input type="submit" value="Submit" onclick="onSubmit()" />
</form>
Javascript code
function onSubmit () {
let fruityRadio = document.getElementById( 'uid1' );
let veggieRadio = document.getElementById( 'uid2' );
if ( fruityRadio.checked ) {
document.getElementById( 'uid3' ).value = 'apple';
} else if ( veggieRadio.checked ) {
document.getElementById( 'uid3' ).value = 'pepper';
}
}
Easy, double up the value with a deliminator between every extra value:
HTML
<div>
<label for="uid1">
<input id="uid1" name="fruit1" type="radio" value="apple:orange" />
Fruit, Apple + Orange
</label>
</div>
<div>
<label for="uid2">
<input id="uid2" name="fruit1" type="radio" value="apple:cherry:lime" />
Fruit, Apple + Cherry + Lime
</label>
</div>
node.js
I'm not sure how node.js handles what PHP refers simply as $_POST['name_attribute_value_here'] though I do know you simply want to use .split(':') to get the two or more values from that single form. If you want more options per radio button just append a deliminator (it doesn't have to be :) between each value.
Both of those radio options have the name "fruit1" so the user can't choose both.
No JavaScript is necessary.
A minor adaptation on the server.
Extra values will obviously not appear to the server if the user doesn't select that radio form field.
Arrays
If you want to set your own key/values then just add a second deliminator:
<input name="fruit1" value="fruit:apple,fruit:lime,color:purple,planet:Earth" />
Then at the server use [whatever].split(',') to get the pairs and iterate in a loop to get each key/value. You could create an entire crazy multi-dimensional array if you really wanted to.
I hope this helps, feel free to comment if you need any further clarification.
Generate form:
const data = [
{ name: 'apple', type:"fruity" },
{ name: 'pepper', type:"veggie"}
]
const form = document.querySelector('form');
const uid = document.querySelector('#uid')
createOptions(data);
function createOptions(data){
data.forEach((e, index) => {
const f = document.createDocumentFragment();
const l = document.createElement('label');
const i = document.createElement('input');
l.setAttribute('for', `uid${index+1}`);
l.textContent=e.name;
i.setAttribute('type', `radio`);
i.setAttribute('for', `uid${index+1}`);
i.setAttribute('name', 'someOtherParam');
i.setAttribute('value', e.name);
i.dataset.otype = e.type;
f.appendChild(l);
f.appendChild(i);
form.insertBefore(f, uid);
i.addEventListener('change', onselectChange, false);
})
}
function onselectChange(event) {
uid.value = event.target.dataset.otype;
}
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="text" id="uid" name="someParam"
style="width:0; visibility: hidden;">
<input type="submit" value="Submit" />
</form>
I can't think another way of doing this using less code, the following achieves your desired result:
<form name="form" method="GET" action="">
<input type="radio" id="uid1" name="someParam" required value="fruity" onchange="document.form.someOtherParam.value = 'apple'" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" required value="veggie" onchange="document.form.someOtherParam.value = 'pepper'" />
<label for="uid2">Vegetable</label>
<input type="hidden" name="someOtherParam" value=""/>
<input type="submit" value="Submit"/>
</form>
There's only 3 changes to your example:
Add a name to the form, then add inline attributes required and onchange to each radio, finally add an input[type=hidden] to include the extra param. The first change is meant so you'll not need document.getElementById later, the second so the form won't be empty submitted and also update the hidden desired value.

I want to check my radio button with the data from back while I'm using ng-model and ng-value already

I have {{policy.isActiveInPolicyGroup}} which is Boolean, I want the radio input be checked if it was true.
<div ng-repeat="policy in item.policies">
<input type="radio" ng-model="item.selectedPolicy" id="policy_{{$index}}"
name="test" ng-value="policy.id">
<label class="custom-control-label" for="test">
{{item.name}}
</label>
</div>
The first thing you should know it's about value of inputs with radio type:
Recommended
the radio inputs can't define by Boolean, if inputs are more than 2 we can't define value as Boolean so we should set a different value for each of them.
Ex: <input type="radio" name="test" ng-value="1">, <input type="radio" name="test" ng-value="2"> , <input type="radio" name="test" ng-value="3">
Not Recommended
Note: Except when input number is 2: in this case we can set value false or true
Ex: <input type="radio" name="test" ng-value="true">, <input type="radio" name="test" ng-value="false">
radio input Note:
all radio inputs in one group should have same name
checkbox input:
inputs with checkbox type by default define with Boolean value because we can set different name for each of them, and result is checked [true] or not [false]
ng-model and ng-value
Radio input should have two attributes ng-model and ng-value that because in angularjs logic ng-model should equal ng-value and can't do it by one attribute.
Only set ng-model value like following:-
$scope.item.selectedPolicy = $scope.policy.id;
It will be checked if its ng-true value matched with its ng-model value.
DEMO of Radio Buttons that Use Boolean Values1
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app>
<fieldset>
<input type="radio" name="radio"
ng-model="model" ng-value="false">false<br>
<input type="radio" name="radio"
ng-model="model" ng-value="true">true<br>
</fieldset>
<fieldset>
<input type="checkbox" ng-model="model">check<br>
</fieldset>
model={{model}}
</body>
For more information, see
AngularJS <input type="radio" Directive API Reference
AngularJS <input type="checkbox" Directive API Reference

HTML "readonly" input value can be edit when checked a check box

I have a input <input type="text" value="1" readonly id='aaa'/>.
I would like to give it a function when user check the box then can edit the value of id=aaa.
Sample:
<input type="text" value="1" readonly/> <input type="checkbox" /> Checked this if you want to edit the value.
Thank you.
Add an onchange event to the checkbox that changes to readOnly attribute of its previous sibling (the textfield)
<input type="text" value="1" readonly id="aaa" />
<input type="checkbox" onchange="getElementById('aaa').readOnly = !this.checked" />
Checked this if you want to edit the value.
You want to use JavaScript to change the readOnly property. Set it to the opposite of whether the checkbox is checked.
document.getElementById('checksome').addEventListener('click', function() {
var changeThis = document.getElementById('readsome');
changeThis.readOnly = !this.checked;
});
<input id="readsome" type="text" value="1" readonly>
<label><input id="checksome" type="checkbox"> Click this to edit</label>

Can't get value from checkbox Thymeleaf

<input id="isChecked" name="isChecked"
type="checkbox"></input><input name="_isChecked"
type="hidden" value="on"></input> <label for="isChecked">Checked</label>
I have this checkbox on the top of my *.html.
I want to use the value of "isChecked" input in a "form" like seting 1/0 (true/false) to a hidden input:
<form id="someForm" class="form xml-display form-inline"
th:action="#{/doSomething}" method="post">
.....
<input type="hidden" name="isChecked"
th:value="GET VALUE FROM THE GLOBAL CHECKBOX" />
.....
</form>
So can I do this without any JS?
Should I add an object in my java controller to the Model so I can set the value from the "isChecked" checkbox to it and then use the object in th:value="${objectFromJavaController}" for the hidden input ? I tried setting a th:object="${objectFromJavaController}" for the checkbox and then passing it to the hidden input but it didn't work (th:value = ${"objectFromJavaController"}) ?
So can someone help me ? Thanks in advance!
Surely somethin like this is simple enough?
<input id="newsletter" name="newsletter" type="checkbox" checked="yes" value="yes"/>
This brings back the same result. anything else would be no. (with PHP code telling them apart)

jQuery event.preventDefault confusion

I'm using jQuery.
On click the search button is used the flag to check if radiobutton is unchecked it will show alert("enter the field") otherwise do the task... and also I used event.preventDefault();
Here actually I'm using radiobutton in which I used gender label that contains two option male and female. Now the problem is when I checked male radio button or female. Still it's showing enter the field. I think there must be something wrong in this part if($('#gender').is(":not(:checked)"))
here is my code:
$('#searchbutton').click(function(event){
alert("ZZ");
var flag3=0;
if ($('#gender').is(":not(:checked)"))
{
flag3=1;
}
if( flag3==1)
alert("Select the field first");
event.preventDefault();
});
<input type="radio" name="gender" id="gender" value="male" /> Male<br />
<input type="radio" name="gender" id="gender" value="female" /> Female
<input type="submit" name="searchbutton" value="Search" id="searchbutton">
You have several problems in your code.
An ID can only be used once in a HTML document. You used #gender twice.
You don't need to use another flag variable, you can run the if simply.
In your second if you have not used {} brackets, thus preventDefault is always executing.
I suggest you do something like this:
<input type="radio" name="gender" value="male" /> Male<br />
<input type="radio" name="gender" value="female" /> Female
<input type="submit" name="searchbutton" value="Search" id="searchbutton">
and the jQuery:
$('#searchbutton').click(function(event){
if ($('input[name="gender"]:checked').length < 1) {
alert("Select the field first");
event.preventDefault();
}
});
Working Demo
Explanation: The attribute selector will match inputs whose name is gender, and the :checked selector only selects the ones that are checked. Then using length we can see how many elements were matched. If zero, that means that the use has not selected any of the options.
From what I understand, you are trying to make sure the user makes a selection on gender.
The immediate problem is that both <input type="radio">s have the same id. While it is proper to give them the same name, you never give two elements the same id.
Additionally, you should simply be checking if any of the radio buttons are checked. This is how I would write the above code:
$('#searchbutton').click(function (e) {
if ($(':radio:checked[name="gender"]').length == 0) {
alert("Select the field first");
e.preventDefault();
}
});