Only one checkbox selected - javascript

I have a checkbox Yes and No so i want to user only able to use one. So if user tick Yes then No will cleared if Yes then no will clear
<input type="checkbox" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "Yes" ? " checked" : "")/>Yes
<input type="checkbox" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" style="margin:1em 1em 5px 5px" #(ViewBag.Status == "No" ? " checked" : "")/>No
<script>
function selectOnlyThis(id) {
for (var i = 0; i <= 4; i++) {
document.getElementById("Check" + i).checked = false;
}
document.getElementById(id).checked = true;
}
</script>

The problem is that you are trying to access elements that do not exist
your loop goes from 0 to 4 but your elements are Check1 and Check2
So when it tries to set the checked property of Check0 (which does not exist) it throws an error and stops execution..
Use
function selectOnlyThis(id) {
console.log(id);
for (var i = 0; i <= 4; i++) {
var element = document.getElementById("Check" + i); // get element
if (element){ // if element was found only the set its checked property
document.getElementById("Check" + i).checked = false;
}
}
document.getElementById(id).checked = true;
}
Demo at http://jsfiddle.net/gaby/RHUVf/
or if your example html is the actual one you could just change your loop to
for (var i = 1; i <= 2; i++) {

As mentioned by others, you are describing the behavior of a radio button. However, it is possible to make a checkbox behave like this also.
jsFiddle demo
$('input:checkbox').click(function(){
$('input:checkbox').not($(this)).prop('checked',false);
});
The above code does the following:
$('input:checkbox') - selects all input elements of type checkbox
.not($(this)) - except this one
.prop('checked',false) - unchecks the checkbox
This code uses the jQuery javascript library, so you must reference this library (usually in the head tags of the document), thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

It would be a lot more helpful/easier to use HTML5 for this part
IF you choose HTML5 the following code WILL work but if you decide not to use it It wont help.
<input type="checkbox" name="<name>" value="<value"><*explanation*><br/><br/>
</form>
</div>
</div>
</body>

Related

Javascript: checkbox onchange/onclick function not working

I have this function for my computation that whenever the text fields are populated, it will add a stack to a variable and whenever a checkbox is checked on the text field, the text field wont add a value.
everything is working except the checkbox function, I already tried onchange and onclick but nothing happens. Can you check my codes?
Script:
function submission(){
x = 19;
ctr = 1;
ctr2 = 0;
days = ('<?php echo $query[0]->totaldays; ?>') - 1;
$('#payment').html('');
for(i = 1; i<=x ; i++){
if($('#guest'+i).val() != ""){
ctr++;
}
if(document.getElementById('kid'+i).checked){
ctr2++;
}
}
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseInt(ctr) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);
}
HTML:
<div class="row">
<div class="col-sm-10">
<label for="exampleInputtext1"><a style = "color:black; font-size: 10px;" ><input onchange="submission()" type="checkbox" name="kid1" id="kid1" > </a>Guest 1:</label>
<input type="text" class="form-control" onblur="submission()" name="guest1" id="guest1"/>
</div>
</div>
The onclick event handler will work for checkbox,you can try this code,
HTML:
<input onclick="submission(this)" type="checkbox" name="kid1" id="kid1" >
JS:
And you can check and see whether the checkbox is checked or not using the following code,
function submission(click){
....
var clicked=click.checked;
...
}
if it is true that means the checkbox has been checked and if it is false it has not been checked.
$("#guest1").change(function() {
if(this.checked) {
//Do this.
}
else{
// Do this.
}});
don't need to mention onclick function on html. just add this code in JS.
its calling auto based on id.
let me know if you need any help in understanding.
Ajay
thanks for your answers, it seems like I just messed up a little bit on my mathematical equation.
totalCount = 0;
totalCount = parseInt(ctr) - parseInt(ctr2);
totalCount = parseFloat(totalCount) * parseInt(days);
totalCount = parseFloat(totalCount) * 100;
$('#totalPayment').val(totalCount);
$('#payment').html(totalCount);

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

How to change the style of a radio button with javascript when clicked

I have an order form that has three sets of radio button options. Ultimately, I would like to have the text of the radio button in each group change to bold and red when it is clicked. However, I'm not having any luck just changing the color of even one group. Below is the loop I was using to try to change one group of radio buttons. My logic was to go through the group of radio buttons and if one of them were clicked it would change the style of the text. What am I doing wrong with this function?
function highlight() {
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
return document.getElementByName.style.color = 'red';
}
}
}
This is one group of radio buttons in my code. The other two groups are similar:
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/> Desktop Case ($500.00) </br>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/> Mini-Tower Case ($600.00) </br>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> Full-Tower Case ($700.00) </br>
Any help would be greatly appreciated.
If you amend your code, and wrap the text in a label element and, incidentally, you can't change the color or font-weight properties of text unless it's wrapped in an element, and that would have to be a separate element for each string of text you want to affect :
<input id="case1" type="radio" name="cases" value="500.00" onclick="highlight()"/><label for="case1">Desktop Case ($500.00)</label>
<input id="case2" type="radio" name="cases" value="600.00" onclick="highlight()"/><label for="case2">Mini-Tower Case ($600.00)</label>
<input id="case3" type="radio" name="cases" value="700.00" onclick="highlight()"/> <label for="case3">Full-Tower Case ($700.00)</label>
You can achieve this with just CSS:
input[type=radio]:checked + label {
color: red;
font-weight: bold;
}
JS Fiddle demo.
Incidentally, to use plain JavaScript I'd suggest:
function choiceHighlight(radio){
var groupName = radio.name,
group = document.getElementsByName(groupName);
for (var i = 0, len = group.length; i < len; i++){
group[i].nextSibling.className = group[i].checked ? 'chosen' : 'unchosen';
}
}
var radios = document.getElementsByName('cases');
for (var i = 0, len = radios.length; i < len; i++){
radios[i].addEventListener('change', function(){
choiceHighlight(this);
});
}
JS Fiddle demo.
Your return statement looks off:
return document.getElementByName.style.color = 'red';
Also note that you've attempted to give the radio inputs a color of red, but they cannot be styled in this way. The text that you have next to the inputs is not part of the input itself.
Here's a simplified script that gets you the input values onchange (not onselect). You should be able to use this as a better starting point: http://jsfiddle.net/rWp6E/
var radios = document.getElementsByName('cases');
for (var i = 0; i < radios.length; i++) {
radios[i].onchange = function () {
alert(this.value);
}
}
getElementByName isn't valid Javascript. A better way to do this would be to use the onCheckedChanged event to change your style:
<input id="case1" type="radio" name="cases" oncheckedchanged="highlight(this)" value="500.00"/>
<script type="text/javascript">
function highlight(e) {
if(e.checked == true)
{e.style.color = "red"}
else
{e.style.color = "some other color"}
}
Note that you will actually have to change the style of the label if you want to change the color of the text.
There is also a :checked selector in CSS3 (as someone else mentioned above), however it will not work in some older browsers, namely IE8 and earlier.

Uncheck a checkbox if another checked with javascript

I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
Would the best way to do this be by writing a function, or could I use onclick statements?
Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo: http://jsfiddle.net/5uUjj/
Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:
function cbChange(obj) {
var instate=(obj.checked);
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
if(instate)obj.checked = true;
}
tymeJV's function does not let you have both unticked - this does.
(yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)
Hope this helps:
function setFries(){
var hotdog= document.getElementById("hotdog");
var opt1= document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
if(hotdog.checked){
opt1.checked = false;
opt2.checked = false;
}else if(opt1.checked){
opt2.checked = false;
}else if(opt2.checked){
opt1.checked = false;
}
}
<input type="checkbox" name="fries" id="opt1" disabled="disabled" onclick="setFries(this);/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled" onclick="setFries(this);/>
<input type="radio" name="o1" id="hotdog" onclick="setFries(this);"/>
Note that I am using onclick event:
function setFries(obj){
var fries = document.getElementsByName('fries');
if(obj.id =='hotdog') //Or check for obj.type == 'radio'
{
for(var i=0; i<fries.length; i++)
fries[i].checked = true;
}
else{
for(var i=0; i<fries.length; i++){
if(fries[i].id != obj.id){
fries[i].checked = !obj.checked;
break;
}
}
}
}
The simplest way I found for this was to not use any sort of code at all. I triggered an actions in the check box properties.
1. mouse up to reset a form. I then unselected (for reset) all of my fields accept for my desired check boxes. I then did the same thing for my other check box to go the other way. You can basically turn the check boxes into toggles or have any sort of crazy pattern you want.

Getting the input tag(s) and setting them as unchecked

I want to write a java script function which will get the input tag(s) with type as "checkbox" from the td and mark them unchecked. Following is the jsp code:
<td id="uncheckedByDefault" align=center class=listTypeOne>
<% if (priv.getViewPrivilege() == 1) { %>
<input name="view" type="checkbox" value='<%= priv.getAttributeId() %>' checked>
<% } else { %>
<input name="view" type="checkbox" value='<%= priv.getAttributeId()%>'>
<% } %>
</td>
Now here the td has the id="uncheckedByDefault". I want to get all the input tag(s) and set them as unchecked. Can anybody tell how can I do that. Thanks in advance.
Try:
inputs = document.getElementById('uncheckedByDefault').getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
inputs[index].checked=false;
}
Here is the function you need, call it whenever you want:
function uncheckAll(){
var inputsContainer = document.getElementById('uncheckedByDefault');
var allInputs = inputsContainer.getElementsByTagName('input');
var len = allInputs.length;
for(var i=0; i<len; i++){
if(allInputs[i].type == 'checkbox'){
allInputs[i].checked = false;
}
}
}
I don't know if I understood your problem, but I will give it a try.
First of all, you can print elements into your web page with a <% ... %> (I will show how in my answer), so you don't have to set a condition into <% ... %>, print an element... etc. All in the same Java function.
Secondly, you can access to your Object properties without calling your getters. Aren't needed at all if you want to set his value into an specific field. (i.e.) <input type="text" name="clientName" value="${client.clientName}" />
Here is my proposal for your question:
<td id="uncheckedByDefault" align=center class=listTypeOne>
<%
if (priv.getViewPrivilege() == 1) {
out.println("<input name='view' type='checkbox' +
value=" + priv.getAttributeId() + " checked = 'checked'>");
} else {
out.println("<input name='view' type='checkbox' +
value=" + priv.getAttributeId() + ">");
}
%>
</td>
Report if it worked or it's not what you wanted.
UPDATE
If you want them all unchecked, because of your element id attribute suggests it. Why do you want to check your Object properties to set it checked or not? Just add your element and don't set it a checked property.
<input name='view' type='checkbox' value="${priv.attributeId}">
This should work
var allInputs = document.getElementById("uncheckedByDefault").getElementsByTagName("input");
for (i = 0; i < allInputs.length; i++) {
if (allInputs[i].getAttribute("type") == 'checkbox') {
allInputs[i].removeAttribute("checked");
}
}
You just need to get a list of all of the elements you're interested in, then you need to perform some action on them. I've added the forEachNode function, since the querySelectorAll function doesn't actually return an array - it returns a nodeList which has similar syntax and functionality as an array, but omits the forEach function.
Note: a checkbox is checked if it has the attribute checked. The actual value of the attribute is not used - it's just it's presence or lack thereof that dictates the check-state. As such, you could write anything rather than 0 to the checked attribute.
EDIT: The above note is incorrect. Both the 'checked' attribute as visible in the html and the 'checked' member variable control the state. I've updated the uncheck and check functions.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
}
/*
func to be called takes 3 variables. currentElement, currentIndex, nodeList the element belongs to.
*/
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
/*
function uncheck(elem)
{
elem.removeAttribute('checked');
}
function check(elem)
{
elem.setAttribute('checked',0);
}
*/
function uncheck(elem)
{
elem.checked = false;
elem.removeAttribute('checked');
}
function check(elem)
{
elem.checked = true;
elem.setAttribute('checked',0);
}
function checkAll()
{
var checkBoxElements = document.querySelectorAll('input[type=checkbox]');
forEachNode(checkBoxElements, check);
}
function uncheckAll()
{
var checkBoxElements = document.querySelectorAll('input[type=checkbox]');
forEachNode(checkBoxElements, uncheck);
}
</script>
<style>
</style>
</head>
<body>
<button onclick='uncheckAll()'>Uncheck all</button>
<button onclick='checkAll()'>Check all</button>
<br>
<input type='checkbox'/>CB 1
<br>
<input type='checkbox'/>CB 2
<br>
<input type='checkbox'/>CB 3
<br>
<input type='checkbox'/>CB 4
<br>
<input type='checkbox'/>CB 5
<br>
</body>
</html>

Categories

Resources