I have a script that checks and check all boxes in a form, my problem is that I only want it to affect only my checkboxes but it also affecting my radio buttons.
This is my JavaScript:
<script>
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
This is my html:
<form id ="frm1">
<input type="checkbox" name="chk1">
<input type="radio" name="chk1">
<input type="checkbox" name="chk2">
<input type='checkbox' name='checkall' onclick='checkedAll(frm1);'>
</form>
I was wondering whether there was a way to check only the checkboxes not the radio button?
for (var i =0; i < aa.elements.length; i++)
{
if (aa.elements[i].type == "checkbox") {
aa.elements[i].checked = checked;
}
}
You can loop through the form elements and check for the "type" property. Alternately, you can use a javascript library like jQuery, which makes it easier to select elements of certain type.
var elLength = document.MyForm.elements.length;
for (i=0; i<elLength; i++)
{
var type = MyForm.elements[i].type;
if (type=="checkbox" && MyForm.elements[i].checked){
alert("Form element in position " + i + " is of type checkbox and is checked.");
}
else if (type=="checkbox") {
alert("Form element in position " + i + " is of type checkbox and is not checked.");
}
else {
}
}
In jQuery it would be:
$("input[type='checkbox']).each(function(chk) {
chk.checked = !chk.checked;
});
You can use jquery. use the html code below in your editor. it works correctly!
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.js"> </script>
</head>
<form id="myform">
<input type="checkbox" />chk1
<input type="checkbox" />chk2<br/>
<input type="radio" />radio1<br/>
<a style="cursor:pointer" onclick="ch()">check/uncheck</a>
</form>
</body></html>
and this script:
<script>
function ch(){
$("form#myform input[type='checkbox']").each(function(chk) {
this.checked = !this.checked;
});
}
</script>
Related
In a part of my application where i check for duplicate radio input selection and revert if its already selected to early selection.
Here is my html code ..
<input type="radio" name="A" checked="checked" onclick="return check();" />
<input type="radio" name="A" onclick="return check();" />
<br />
<input type="radio" name="B" onclick="return check();" />
<input type="radio" name="B" checked="checked" onclick="return check();" />
Here is the javascript code
function check() {
//logic to check for duplicate selection
alert('Its already selected');
return false;
}
And here is the demo
The above code works fine. The issue is when the input isn't initially checked. In such condition the radio input selection doesn't revert to unchecked.
NOTE: when in checked state, returning false shows and alert and sets the check box to initial checked state. But when initially in non checked state this doesn't work.
In DOM ready, check if any radio button is checked or not. If any radio button is checked, increase the counter by one. In onclick of the radio button, check if the counter value is 1. if yes, return false, else increase counter by 1.
try this code,
html
<input type="radio" name="A" checked="checked" />
<input type="radio" name="A" />
<br />
<input type="radio" name="B" />
<input type="radio" name="B" />
JS
var counterA = 0;
var counterB = 0;
$(document).ready(function () {
if ($("input:radio[name=A]").is(":checked") == true) counterA++;
if ($("input:radio[name='B']").is(":checked") == true) counterB++;
});
$('input:radio[name=A]').click(function () {
if (counterA == 1) {
alert('already checked');
return false;
} else {
counterA++;
}
});
$('input:radio[name=B]').click(function () {
if (counterB == 1) {
alert('already checked');
return false;
} else {
counterB++;
}
});
SEE THIS DEMO
iJay wants to ask several questions and privides the same answers for each question. Each answer can only be choosen once. If a user clicks the same answer the second time a error-message should be shown.
// get all elements
var elements = document.querySelectorAll('input[type="radio"]');
/**
* check if radio with own name is already selected
* if so return false
*/
function check(){
var selected_name = this.name,
selected_value = this.value,
is_valid = true;
// compare with all other elements
for(var j = 0; j < len; j++) {
var el = elements[j];
// does the elemenet have the same name AND is already selected?
if(el.name != selected_name && el.value == selected_value && el.checked){
// if so, selection is not valid anymore
alert('Oups..! You can not select this answer a second time :( Choose another one!')
// check current group for previous selection
is_valid = false;
break;
}
};
return is_valid;
}
/**
* bind your elements to the check-routine
*/
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onmousedown = check;
}
Here is a DEMO
Use $yourRadio.prop('checked', false); to uncheck the specific radio.
Use like this:
function check() {
//logic to check for duplicate selection
var checked = true ? false : true;
$(this).prop('checked', checked);
return false;
}
1) add class attribute to same type of checkbox elements(which are having same name)
ex: class = "partyA"
2)
var sourceIdsArr = new Array();
function check() {
$('.partyA').each(function() {
var sourceId = $(this).val();
if(sourceIdsArr.indexOf(sourceId) != -1){
sourceIdsArr.push(sourceId );
}
else{
alert('Its already selected');
return false;
}
});
}
Here is your code..
function check() {
//logic to check for duplicate selection
var selectflag=0;
var radiovalue=document.getElementsByName("B");
for(var i=0;i<radiovalue.length;i++)
{
// alert(radiovalue[i].checked);
if(radiovalue[i].checked==true)
{
selectflag=1;
break;
}
}
if(selectflag==1)
{
alert('Its already selected');
return false;
}
return true;
}
Trigger your event on MouseDown. It will work fine.
I think this is something you are looking for :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<input type="radio" name="A" checked="checked" onclick="return check(this);"/>
<input type="radio" name="A" onclick="return check(this);"/>
<script>
$( document ).ready(function() {
this.currentradio = $("input[name='A']:checked")[0];
});
function check(t) {
var newradio= $("input[name='A']:checked")[0];
if (newradio===document.currentradio){
alert('already selected');
return false
}else{
document.currentradio = $("input[name='A']:checked")[0];
}
}
</script>
</body>
<html>
Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/
So im trying to show a div when one of the multiple checkboxes are clicked and it is working but when you unclick a checkbox it hides the div even when checkboxes are still clicked. I cant seem to figure out how to make it hide the div only when no checkboxes are left clicked.
<input type="checkbox" name="list[]" value="1" id="fldcheckbox" onclick="fnchecked(this.checked);">
<input type="checkbox" name="list[]" value="2" id="fldcheckbox" onclick="fnchecked(this.checked);">
<input type="checkbox" name="list[]" value="3" id="fldcheckbox" onclick="fnchecked(this.checked);">
<div id="ref_options" style="display:none;">
example
</div>
<script>
function fnchecked(blnchecked)
{
if(blnchecked)
{
document.getElementById("ref_options").style.display = "";
}else{
document.getElementById("ref_options").style.display = "none";
}
}
</script>
Use change event instead of click.
Actually you are hiding/displaying the div based on the checked value of each checkbox.
When just one checkbox is unchecked then you variable blnchecked become false, that makes div invisible.
You probably want this
function fnchecked(blnchecked) {
var checkboxs = document.getElementsByName("list[]");
var ischecked = false;
for (var i = 0, l = checkboxs.length; i < l; i++) {
if (checkboxs[i].checked) {
ischecked = true;
}
}
if (ischecked) {
document.getElementById("ref_options").style.display = "block";
} else {
document.getElementById("ref_options").style.display = "none";
}
Js Fiddle Demo
You can remove the function parameter as there is no use of it inside the function.
see this DEMO
html:
<input type="checkbox" name="list[]" value="1" id="fldcheckbox" onclick="fnchecked(this.checked?++c:--c);">
java script:
<script>
var c=0;
function fnchecked(c){
if(c>0){
document.getElementById("ref_options").style.display = "";
}else{
document.getElementById("ref_options").style.display = "none";
}
}
</script>
I want to stop the user to check another checkbox after a certain number of checkboxes have been checked already. i.e. After 3 checkboxes are checked, the user cannot check anymore and a message says 'You're not allowed to choose more than 3 boxes.'
I'm almost there but the last checkbox is still being checked and I don't want that, I want it to be unchecked with the message appearing.
How do I do that:
var productList = $('.prod-list'),
checkBox = productList.find('input[type="checkbox"]'),
compareList = $('.compare-list ul');
productList.delegate('input[type="checkbox"]', 'click', function () {
var thisElem = $(this),
thisData = thisElem.data('compare'),
thisImg = thisElem.closest('li').find('img'),
thisImgSrc = thisImg.attr('src'),
thisImgAlt = thisImg.attr('alt');
if (thisElem.is(':checked')) {
if ($('input:checked').length < 4) {
compareList.append('<li data-comparing="' + thisData + '"><img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /><li>');
} else {
$('input:checked').eq(2).attr('checked', false);
alert('You\'re not allowed to choose more than 3 boxes');
}
} else {
var compareListItem = compareList.find('li');
for (var i = 0, max = compareListItem.length; i < max; i++) {
var thisCompItem = $(compareListItem[i]),
comparingData = thisCompItem.data('comparing');
if (thisData === comparingData) {
thisCompItem.remove();
}
}
}
});
I might have misunderstood the question... see my comment.
Too prevent the selection, you can call event.preventDefault() and define the handler with the event parameter.
$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
DEMO
Alternatively, set this.checked to false. This will even prevent the browser from rendering the checkmark.
DEMO
one single jquery function for multiple forms
<form>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg" ><br>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg"><br>
</form>
<br><br><br><br><br>
<form>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1" ><br>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1"><br>
</form>
$('input[type="checkbox"]').click(function(event) {
if ($("input[name= "+ this.name +"]:checked").length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.