How to get value of many selected radio buttons - javascript

I'm using JavaScript to get value from the radio boxes to insert it to the database as a string. What I need is that I have more than 2 radio boxes. How would I make use of Javascript to add the values to my database?
Here is my code:
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='Sentinel' checked="checked">
Sentinel GM
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardTrack'>
GuardTrack
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardingProduct'>
Guarding Product
</td>
if (!document.frmAdd_Visit.company_grp[0].checked && !document.frmAdd_Visit.company_grp[1].checked && !document.frmAdd_Visit.company_grp[2].checked) {
alert("Please Select the company group does this client belong's to!");
form.company_grp.focus();
return false;
}
It's very tricky but I don't get the correct value. When I select the 3rd radio, it doesn't add to the database but instead it reloads the page.

you can use jquery to get value form radio box
$(document).ready(function(){
$('input[name="company_grp"]:checked').val();
});

The jquery code below returns the value:
$('input[name=company_grp]:checked').val()

can use radio type checked as $(':radio:checked')
var selectedvalue;
if($(':radio:checked').length > 0){
$(':radio:checked').each(function (i) {
selectedvalue = $(this).val();
});
}
console.log(selectedvalue);

Here what I found and it working well for me.
function test_company_grp() {
var radios = document.getElementsByName("company_grp");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select the company group does this client belong's to!");
}
}

Related

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!!

Javascript Validating in a loop

I have two radio buttons on the top (YES/NO) If yes the javascript function showhideform shows another text box(certificate). This form is in a loop as you see with all my outputs.If yes is chosen and loop is 1 everything works fine onsubmit. If Yes and I submit when loop is 2 it only validates certificate textbox 2 and forgets about certificate textbox 1. I need it to validate both if yes is chosen twice.
Radio Buttons:
<input
type="radio"
value="No"
name="abc_<cfoutput>#BAdd#</cfoutput>"
id="noabc_<cfoutput>#BAdd#</cfoutput>"
onchange="showhideForm_<cfoutput>#BAdd#</cfoutput>(this.value);"/>
<label for="noabc_<cfoutput>#BAdd#</cfoutput>">No</label>
<input
type="radio"
value="Yes"
name="abc_<cfoutput>#BAdd#</cfoutput>"
id="abc_<cfoutput>#BAdd#</cfoutput>"
required="yes"
onchange="showhideForm_<cfoutput>#BAdd#</cfoutput>(this.value);"/>
<label for="abc_<cfoutput>#BAdd#</cfoutput>">Yes</label>
Show / Hide Radio Buttons:
function showhideForm_<cfoutput>#BAdd#</cfoutput>(abc_<cfoutput>#BAdd#</cfoutput>) {
if (abc_<cfoutput>#BAdd#</cfoutput> == "Yes") {
document.getElementById("div1_<cfoutput>#BAdd#</cfoutput>").style.display = 'block';
document.getElementById("div2_<cfoutput>#BAdd#</cfoutput>").style.display = 'none';
}
else if (abc_<cfoutput>#BAdd#</cfoutput> == "No") {
document.getElementById("div2_<cfoutput>#BAdd#</cfoutput>").style.display = 'block';
document.getElementById("div1_<cfoutput>#BAdd#</cfoutput>").style.display = 'none';
}
}
Validating through loop:
function doSubmit(n) {
var QnoText = ['abc_<cfoutput>#BAdd#</cfoutput>']; // add IDs here for questions with optional text input
var ids = '';
flag = true;
for (i=0; i<QnoText.length; i++) {
CkStatus = document.getElementById(QnoText[i]).checked;
ids = QnoText[i]+'Certificate_<cfoutput>#BAdd#</cfoutput>' + n;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' + n + '.');
document.getElementById(ids).focus();
flag = false;
}
}
return flag;
}
Certificate textbox:
<input
type="text"
name="abc_<cfoutput>#BAdd#</cfoutput>Certificate_<cfoutput>#BAdd#</cfoutput>"
validateat="onSubmit"
validate="maxlength"
id="abc_<cfoutput>#BAdd#</cfoutput>Certificate_<cfoutput>#BAdd#</cfoutput>"
size="54"
maxlength="120"
value="">
submit button:
//return doSubmit(1);
It looks like the n is just a numbering/index to the id of the input textbox it is validating.
Looking at your code, CKStatus seems to me is a checkbox. If it is checked, it will validate the certificate input text box according to the parameter n.
After days of working on it I have finally figured it out!! I just wanted to say thanks to everyone that has helped and this is the code for anyone who was interested!
<script type="text/javascript">
function doSubmit() {
var count =<cfoutput>#BAdd#</cfoutput>;
flag = true;
for (i=1; i<=count; i++){
var ids = 'abc_'+i +'Certificate_'+i;
var Radio = 'abc_'+i
CkStatus = document.getElementById(Radio).checked;
if (CkStatus && document.getElementById(ids).value == '') {
alert('Please enter certificate number ' +i);
document.getElementById(ids).focus();
flag = false;
}
}
return flag;
}
</script>

JS: uncheck box when another is checked but also uncheck itself if checked

I have three checkboxes. I am already using a piece of code I found here to uncheck the other two when one is checked.
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
I use this inside the checkbox to toggle the state: onchange="cbChange(this)".
However, I also need to provide for a situation where I don't want any of the boxes ticked. While I can do this by adding a separate button or checkbox, I wanted to know if the above code can be modified or another function added that will allow to untick the already ticked box by an onclick event.
I tried adding this function (again found here) but it won't work:
function cbUncheck(obj)
{
if (obj.checked == false)
{
document.getElementByClassName("cb").checked = false;
}
}
I use this in the checkbox code: onclick="cbUncheck(this);"
Suggestions welcome!
Thanks!
you need to check first checkbox checked or not..
if checkbox is not checked then dont need to do anything
otherwise uncheck other checkboxes
<input id="chk1" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk1" >1</label>
<input id="chk2" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk2" >1</label>
<input id="chk3" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk3" >1</label>
javascript
function cbChange(obj) {
if(obj.checked)
{
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
}
JS BIN JSBIN EXAMPLE
You can use radio buttons so that only one can be selected (no script required for that). Then if some other condition occurs, clear both (below uses a button as an example):
<form>
<input type="radio" name="foo" value="0">zero<br>
<input type="radio" name="foo" value="1">one<br>
<button type="button" onclick="clearRadios(this.form.foo)">Clear radios</button>
</form>
And the function:
function clearRadios(radioGroup) {
for (var i=0; i<radioGroup.length; i++) {
radioGroup[i].checked = false;
}
}
If you don't want users to check the radios at all, disable them.
This below code simply give solutions to what you need.
this.scan=function(index)
{
if( this.boxGroup[ index ].checked )
for(var i=0, g=this.boxGroup, len=g.length; i<len; i++)
if( i != index )
g[i].checked = false;
}
for working demo see jsfiddle

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.

How do I validate a group of textboxes using javascript?

I have group of check-boxes and corresponding text-boxes with them. I can get each checkbox one by one, but how do I get the group of textboxes so I can validate them?
Here is my javascript code below:
function validate_orderform(proform)
{
var flag=0;
for (var i = 0; i < proform.chk.length; i++) {
if (proform.chk[i].checked && proform.quant[i].value=="") {
flag=1;
}
}
if(flag==1){
return false;
}
return true;
}
and my html code:
<td><input type="checkbox" id="chk1" name="chk"></td>
<td><input type="text" size="10" id="quant1" name="quant1"></td>...and so on
If name of textboxes are different then you can access all textboxes by
var txtObjList = document.getElementsByTagName("input");
for(var i=0; i < txtObjList.length; i++){
if(txtObjList[i].getAttribute("type") == "text" && this.value != ""){
// success for i+1 textbox
}
}
Or you can give common class name to all textboxes and then can access by
var txtObjList = document.getElementsByClassName("classname");
for(var i=0; i < txtObjList.length; i++){
if(this.value != ""){
// success for i+1 textbox
}
}
Remember by using javascript library such as jquery, prototype your work will be simpler.
There are a couple of methods you could use, you could use document.getElementsByTagName to retrieve all of the input elements, check their type etc... It works but it's slow and potentially expensive depending on how complex your form is.
If you have a group of checkboxes and each one has it's own text box then you could group them, so add a common name to each type, e.g.
Entry 1:
<input type="checkbox" id="chk1" name="chk"/>
<input type="text" id="quant1" name="quant"/>
Entry 2:
<input type="checkbox" id="chk2" name="chk"/>
<input type="text" id="quant2" name="quant"/>
Then you can use the document.getElementsByName method, so in this instance the following would retrieve a collection of 2 objects for you're text boxes:
var myTextBoxes = document.getElementsByName("quant");

Categories

Resources