How can I prevent a user from selecting multiple checkboxes in HTML? - html

How can I prevent a user from selecting multiple checkboxes in HTML?

you should change it to radio button instead of check box!
<input type="radio" name="group1" id="item1" value="Milk">
<label for="item1">Milk</label>
<br/>
<input type="radio" name="group1" id="item2" value="Butter" checked>
<label for="item2">Butter</label>
<br/>
<input type="radio" name="group1" id="item3" value="Cheese">
<label for="item13">Cheese</label>

I had a use case where I needed use checkboxes--which, unlike radio buttons, allows a user to UNcheck... Here's an example of something I pieced together from another stackoverflow user:
<head>
<meta charset=utf-8 />
<title>and-or checkboxes</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
<label for="checkbox1"><input type="checkbox" id="checkbox1" name="checkbox1" value="and" </label><span id="span_and">checkbox1</span><br>
<label for="checkbox2"> <input type="checkbox" id="checkbox2" name="checkbox2" value="or" </label><span id="span_or">checkbox2</span>
<script>
$(document).ready(function(){
$('#checkbox1').click(function() {
var checkedBox = $(this).attr("checked");
if (checkedBox === true) {
$("#checkbox2").attr('checked', false);
} else {
$("#checkbox2").removeAttr('checked');
}
});
});
$(document).ready(function(){
$('#checkbox2').click(function() {
var checkedBox = $(this).attr("checked");
if (checkedBox === true) {
$("#checkbox1").attr('checked', false);
} else {
$("#checkbox1").removeAttr('checked');
}
});
});
</script>
</body>
With a little work, you can combine the either/or two scripts into a single script. You probably don't need this now but I wanted to post it because it was very useful to me.

If you want that only one checkbox get selected at a time then its better to use radiobutton instead.

If you mean that you don't want multiple checkboxes from a same "logical group" to be checked at one time, you should use radio buttons instead of checkboxes.
<form>
<input type="radio" name="aGroup" value="choice1" /> Choice #1<br />
<input type="radio" name="aGroup" value="choice2" /> Choice #2
</form>
By using this, only 1 option can be checked at one time

Use Radio, and they must have the same name="".

Related

How to make specific radio button in HTML5 with automatically selecting Specify while manually adding data

I am working on a web interface for taking inputs in such a way that imagine there are three radio buttons with specific functions,and one of radio input function also has number input along with it. Take a look at example:
<h2>How many cars you own?</h2>
<form>
<input type="radio" name="car" checked>One<br>
<input type="radio" name="car">Two<br>
<input type="radio" name="car">Specify
<input type="number" name="car"><br>
</form>
Actually this works, but I want my website to be a little more smart and dynamic, so the main problem is the moment I select a number from Choose, it should automatically mark the Specify radio button, but it doesn't.And if I am choosing One or Two as my choice, it should disable the number input with a blank interface.
I think you want something like this
var cars = document.getElementsByName("car");
cars[3].addEventListener("input", function(e) {
if (e.target.value < 1) {
e.target.value = 1;
}
if (e.target.value === 1) {
cars[2].checked = true;
} else {
cars[e.target.value - 1].checked = true;
}
});
<h2>How many cars you own?</h2>
<form>
<input type="radio" name="car" checked>One<br>
<input type="radio" name="car">Two<br>
<input type="radio" name="car">Specify
<input type="number" name="car" value="1"><br>
</form>

one radio group depends on another for its outcome

first post.. graphics person becoming a coder here. (Coding is more fun, but harder!)
2 radio groups each with 2 buttons. I have got it working where if either #client or #agent is selected from Radio 1, and #companyClient is selected from radio 2, the result is the text fields beneath the radio groups stay Readonly except #companyName. I also have it working where if #agent is selected from Radio 1, and #individualClient is selected from radio 2, the result is the text fields beneath the radio groups become editable to collect input except #companyName which stays Readonly.
What I need though is if #client is selected from Radio 1, and #individualClient is selected from radio 2, the text fields beneath the radio groups (except #companyName) stay Readonly; currently they are editable which I don't want. And I need to copy the text field values from #firstnameContact, #lastnameContact, and titleContact to them (ie to firstnameClient, lastnameClient and titleClient).
Thanks
JS
$(function(){
$("#companyClient, #individualClient").change(function(){
$("#firstnameClient, #lastnameClient, #titleClient, #companyName").val("").attr("readonly",true);
if($("#individualClient").is(":checked")){
$("#firstnameClient, #lastnameClient, #titleClient").removeAttr("readonly");
$("#companyName").attr("readonly");
$("#firstnameClient").focus();
}
else if($("#companyClient").is(":checked")){
$("#companyName").removeAttr("readonly");
$("#companyName").focus();
}
});
});
HTML
<label for="firstnameContact">First Name</label>
<input type="text" name="firstnameContact" id="firstnameContact" />
<label for="lastnameContact">Last Name</label>
<input type="text" name="lastnameContact" id="lastnameContact" />
<label for="titleContact">Title</label></div>
<input type="text" name="titleContact" id="titleContact" />
<!--Radio 1 -->
<label>Your Status</label>
<input type="radio" name="yourStatus" id="client" value="client" checked />
<label for="client">I am the Client</label>
<input type="radio" name="yourStatus" id="agent" value="agent" />
<label for="agent">I am an Agent</label></div>
<!--Radio 2 -->
<label>select one:</label>
<input type="radio" name="clientType" id="companyClient" value="companyClient" />
<label for="companyClient">Company</label>
<input type="radio" name="clientType" id="individualClient" value="individualClient" />
<label for="individualClient">Individual</label>
<label for="companyName">Company Name</label>
<input type="text" name="companyName" id="companyName" readonly />
<label for="firstnameClient">First Name</label></div>
<input type="text" name="firstnameClient" id="firstnameClient" readonly />
<label for="lastnameClient">Last Name</label>
<input type="text" name="lastnameClient" id="lastnameClient" readonly />
<label for="titleClient">Title</label></div>
<input type="text" name="titleClient" id="titleClient" readonly />
Just added a form around all elements and made the change on it, seems to works.
See this fiddle
$(function(){
$("form").change(function(){
$("#firstnameClient, #lastnameClient, #titleClient, #companyName").val("").attr("readonly",true);
if($("#individualClient").is(":checked")){
$("#firstnameClient, #lastnameClient, #titleClient").removeAttr("readonly");
$("#companyName").attr("readonly");
$("#firstnameClient").focus();
}
else if($("#companyClient").is(":checked")){
$("#companyName").removeAttr("readonly");
$("#companyName").focus();
}
});
});
EDIT
Or you can use disabled to make it more clear for users.
See this fiddle
$(function(){
$("form").change(function(){
$("#firstnameClient, #lastnameClient, #titleClient, #companyName").val("").prop("disabled",true);
if($("#individualClient").is(":checked")){
$("#firstnameClient, #lastnameClient, #titleClient").removeProp("disabled");
$("#companyName").prop("disabled",true);
$("#firstnameClient").focus();
}
else if($("#companyClient").is(":checked")){
$("#companyName").removeProp("disabled");
$("#companyName").focus();
}
});
});
Of course, you can add a PHP validation and test of all fields to make it safier and better.

How to add values in HTML forms?

How would i add the "value" that are selected from radio boxes in html forms? So when someone selects an option it would add the other "values" onto it and total that it at the bottom of the page. And does anyone know if it could add "names" total "values" onto it as well? thanks
My code looks like this:
<h3><u>Title</u></h3><br>
<form action="">
<input type="radio" name="num" value="0">Text<br>
<input type="radio" name="num" value="2">Text<br>
<input type="radio" name="num" value="80">Text<br>
<input type="radio" name="num" value="110">Text<br>
<input type="radio" name="num" value="85">Text<br>
<input type="radio" name="num" value="120">Text<br>
</form>
You cannot. By definition, a set of radio buttons with the same name attribute contributes at most one value to the data set, the one corresponding to the selected button.
If you want something else, you should handle that server side, or use other types of controls, or redesign the entire approach.
Working example :
(using a Javascript library, jQuery, but could be done in plain JavaScript)
You mainly have to change your inputs to type="checkbox" in the HTML
What code does : when a checkbox's state is modified, all checked checkboxes' value are summed up in the last input field I've added
The checkboxes are targetted by looking for "num" in their name, if you remove that the checkbox won't be taken into account by the script.
$(function() {
$("input[name*='num']").on("change", function() {
var total = 0;
$("input[type='checkbox']:checked").each(function() {
total += Number($(this).val());
});
$("#total").val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>
<u>Title</u>
</h3>
<br>
<form action="">
<input type="checkbox" name="num0" value="0">Add 0<br>
<input type="checkbox" name="num2" value="2">Add 2<br>
<input type="checkbox" name="num80" value="80">Add 80<br>
<input type="checkbox" name="num110" value="110">Add 110<br>
<input type="checkbox" name="num85" value="85">Add 85<br>
<input type="checkbox" name="numwhateveryoulike" value="120">Add 120<br>
Total <input type="text" value="0" id="total">
</form>

Radio buttons group - setCustomValidity and required option in conflict?

I'm trying to come up with a form comprised of radio buttons group where a user must select one of the options and if he doesn't there's a custom validity message.
So the logic will be:
A user forgets to select an option and the validity message shows up.
He goes back and selects any option to go proceed.
The problem is, the way things are it only goes ahead if the selected option is the one with the onclick event as shown below. If it isn't then the message will keep showing up.
I have tried to juggle around with the required, oninvalid and onclick thingies but to no avail. Any ideas?
Thanks!
<form>
<input type="radio" name="test" value="0" required oninvalid="this.setCustomValidity('Click me')" onclick="setCustomValidity('')">Zero<br>
<input type="radio" name="test" value="1" class="wrapper">One<br>
<input type="radio" name="test" value="2" class="wrapper">Two<br>
<input type="submit">
</form>
<form>
<input type="radio" id="test" name="test" value="0" oninvalid="this.setCustomValidity('Click me')" onclick="clearValidity();" required >Zero<br>
<input type="radio" name="test" value="1" onclick="clearValidity()" class="wrapper">One<br>
<input type="radio" name="test" value="2" onclick="clearValidity()" class="wrapper">Two<br>
<input type="submit">
</form>
<script>
function clearValidity()
{
document.getElementById('test').setCustomValidity('');
}
</script>
This can be written as a function to make it work on any type of <input>:
document.querySelectorAll('form *[data-custom-validity]').forEach(el => {
const firstInput = el.querySelector('input:first-of-type')
// set custom validity if first input is invalid
firstInput.addEventListener('invalid', () => firstInput.setCustomValidity(el.dataset.customValidity))
// listen on all inputs for a change
el.querySelectorAll('input').forEach(input =>
input.addEventListener('change', () => firstInput.setCustomValidity('')))
})
<form>
<div data-custom-validity="Click me.">
<input type="radio">
<input type="radio">
</div>
</form>
This worked for me, I'm leaving it here in case it helps anyone.
<div class="genero">
<input type="radio" name="radiogroup" oninvalid="setCustomValidity('Mensaje')" onchange="try{setCustomValidity('')}catch(e){}" value="M">Masculino
<input type="radio" name="radiogroup" oninvalid="setCustomValidity('Mensaje')" onchange="try{setCustomValidity('')}catch(e){}" value="F">Femenino
</div>

Error updating CSS using JQuery .change() with multiple radio inputs

I am having an error where my JQuery works initially upon radio click, but after toggling the radio buttons a few times, it breaks.
What is the proper way to update page text in CSS with 2+ radio questions using JQuery? The toggling of the multiple radio buttons (upon user click) should work indefinitely as it's a simple, basic if condition.
Code:
var q1 = $("input[name=q1]:radio");
var q2 = $("input[name=q2]:radio");
var q3 = $("input[name=q3]:radio");
var a1 = "foo";
var a2 = "bar";
var aa = "bas";
q1.change(function () {
$("input:checked").each(
function () {
if ($(this).val() == "Yes") {
$("#a1").text(a1);
} else {
$("#a1").text("");
};
}
);
})
q2.change(function () {
$("input:checked").each(
function () {
if ($(this).val() == "Yes") {
$("#a2").text(a2);
} else {
$("#a2").text("");
};
}
);
})
.change();
HTML
Question 1 Here?<br />
<input type="radio" name="q1" id="q1-y" value="Yes" />Yes
<input type="radio" name="q1" id="q1-n" value="No" />No
<br />
Question 2 Here?<br />
<input type="radio" name="q2" id="q2-y" value="Yes" />Yes
<input type="radio" name="q2" id="q2-n" value="No" />No
<br />
Question 3 Here?<br />
<input type="radio" name="q3" id="q3-y" value="Yes" />Yes
<input type="radio" name="q3" id="q3-n" value="No" />No
<div id="a1"></div>
<div id="a2"></div>
<div id="a3"></div>
<div id="aa"></div>
I'd like to insert text into the Divs based on what is checked in the radio buttons. As mentioned above, the JQuery appears to work initially, but after 3+ clicks, the if statements don't work.
Thanks
The problem lies in these lines:
$("input:checked").each(
This means the condition of every checked input is being used to determine what should be displayed, when it should only be one set of radio buttons informing the decision. The problem doesn't appear until multiple radio button sets have been checked. A quick fix is to say:
q1.change(function () {
$("input[name=q1]:checked").each(
and similarly for each change handler.
DEMO