Return a string based on checkbox checked - javascript

I have a table with 2 checkboxes:
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
and I want to be able to identify which box is checked (by id), and be able to store a string as a variable, depending on the box. Here is my javascript:
var getCheck = function() {
if (document.getElementById('A').checked) {
return "A";
}
else if (document.getElementById('B').checked){
return "B";
}
else if ((document.getElementById('A').checked) && (document.getElementById('B').checked)) {
return "Both"
}
console.log(getCheck); // for debugging
};
So if I check 'A', I want getCheck to = 'A' as a string. Curious as to how to fix my Javascript to get it to work.

Here's an example of how you would do it with jQuery, it's just easier to do with it and since there's a jQuery tag...
Basically, you add a handler for elements that are checkboxes. Then you select only checked checkboxes with :checked and then you just access each element with the jQuery each function.
$(function(){
$('input[type=checkbox]').on('change', function(){
var checked = [];
$('input[type=checkbox]:checked').each(function(index, checkbox){
checked.push($(checkbox).attr('id'));
});
$('#result').text(JSON.stringify(checked, '/t'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
<pre id="result"></pre>

You need to check both first, since otherwise the function will return "A" and never reach the code that would return both. It is also possible to eliminate all the if-else complexity when returning from each if.
A helper function and some variables can reduce repetition and code length.
var isChecked = function(id){
var e = document.getElementById(id);
return (e && e.checked);
}
var getCheck = function() {
var A = isChecked("A");
var B = isChecked("B");
if (A && B) return "Both";
if (A) return "A";
if (B) return "B";
return "None";
}
For testing, you could add
window.onclick = function(){ console.log(getCheck()); }
demo via jsfiddle

fiddle example
The answer others provided is quite good for. And I want to make some addition:
If you want to get the value whenever user check the box, you can add a eventListen to the parent table as a delegation for the checkbox. Just as I show in the fiddle example
<table id="mytable">
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>

Related

Checkbox validtion not working

Hi i have checkboxes and submit button.And for validation i need atleast 1 checkbox should be checked while clicking on submit button.I tried few ways in jquery but now working.Thank you.
Here is my code:
dashboard.php
<table id="fahrzeuge" >
<tr>
<td>
<input type="checkbox" name="Anzahl_Fahrzeuge_ohne_Bilder" id="Anzahl_Fahrzeuge_ohne_Bilder" checked />
<label for="Anzahl_Fahrzeuge_ohne_Bilder">Anzahl Fahrzeuge ohne Bilder</label><br>
<input type="checkbox" name="Fahrzeuge_ohne_Preis" id="Fahrzeuge_ohne_Preis" value="Fahrzeuge_ohne_Preis" checked />
<label for="Fahrzeuge_ohne_Preis">Fahrzeuge_ohne_Preis</label><br>
<input type="checkbox" name="Fahrzeuge_mit_Fehlern" id="Fahrzeuge_mit_Fehlern" value="Fahrzeuge_mit_Fehlern" checked />
<label for="Fahrzeuge mit Fehlern">Fahrzeuge mit Fehlern</label><br>
<input type="checkbox" name="Herausforderungen" id="Herausforderungen" value="Herausforderungen" checked />
<label for="Herausforderungen">Herausforderungen</label><br><br>
</td>
</tr>
</table>
dashboard.js
function getFahrzeuge() {
var opts = [];
$("#fahrzeuge input[type='checkbox']").each(function () {
if ($(this).is(':checked'))
{
opts.push($(this).attr("id"));
}
});
return opts;
}
$('#fahrzeuge .butt-rahmen').on('click', function(){
if($(this).attr('id') == 'saveId')
{
var opts = getFahrzeuge();
saveFahrzeugeWidget(opts);
}
});
You can simply do the check using :checked selector:
if($("#fahrzeuge input:checked").length){
//atleast one checked
}

Checks if a value exists in an array input value by jquery

I want check if id in array value input:cheched 3, alert (true) else alert (false). I tried as following js code, but don't work for me.
How can fix it?
DEMO: http://jsfiddle.net/VAwHR/4/
HTML:
<input value="3" type="text" id="seeid">
<div class="paginate">
<input name="ch[]" type="checkbox" value="1" checked>
<input name="ch[]" type="checkbox" value="2">
<input name="ch[]" type="checkbox" value="3" checked>
<input name="ch[]" type="checkbox" value="4">
</div>
<input type="submit" class="sub">
JQUERY:
$('.sub').click(function(){
var seeid = $('#seeid').val();
var db = $('.paginate :checkbox:checked').map(function (i, n) {
return $(n).val();
}).get();
alert($.inArray(seeid, db))
})
Here is the problem in id place you are having #
<input value="3" type="text" id="#seeid">
use this
<input value="3" type="text" id="seeid">
You have two errors. The first:
<input value="3" type="text" id="#seeid"> // id should be "seed"
The second:
$.inArray(seeid, db) > 0
should be
$.inArray(seeid, db) > -1 // or ~$.inArray(seeid, db)
Your code will fail to detect value 1 for example, because indexOf will return 0 in this case.
$('.sub').click(function(){
var seeid = $('#seeid').val();
var db = $('.paginate :checkbox:checked').map(function (i, n) {
return $(n).val();
}).get();
var flag;
if(flag = $.inArray(seeid, db) > -1){
alert(flag);
}
else {
alert(flag);
}
})
paste this into fiddle - it should give you the correct true/false alerts

Jquery checkbox val array?

Html
<td>
<input type="checkbox" value="1" id="t1" checked="checked" class="filter" /><label
for="t1">T1</label>
</td>
<td>
<input type="checkbox" value="2" id="t2" checked="checked" class="filter" /><label
for="t2">T2</label>
</td>
<td>
<input type="checkbox" value="3" id="t3" checked="checked" class="filter" /><label
for="t3">T3</label>
</td>
<td>
<input type="checkbox" value="4" id="t4" checked="checked" class="filter" /><label
for="t4">Toplam</label>
</td>
Script:
$(document).ready(function () {
$(".filter").click(function () {
drawChart();
});
});
function drawChart()
{
// I want to get checkboxes value here.
var filters = {$("#t1").val(),$("#t2").val(),$("#t3").val(),$("#t4").val()};
var view = new google.visualization.DataView(new google.visualization.DataTable(evalledData, 0.5));
view.setColumns([0, 4]); //here you set the columns you want to display
}
I want to get checkboxes value like above but I dont know correct syntax? Or I would pass array to drawChart. Could you write correct syntax to create an array of checkboxes values?
Edit
I want to set view columns with view.setColumns([0, 4]); with using checkboxes. I mean I want to use view.setColumns([array]); instead of view.setColumns([0, 4]);
Thanks.
var myValues = $(".filter").map(function () {
return this.value;
}).get();
console.log(myValues.join(","));
If you want only the checked ones:
var myValues = $(".filter:checked").map(function () {
return this.value;
}).get();
console.log(myValues.join(","));
http://api.jquery.com/map/
I assume that by value, you actually mean whether the checkbox is checked or not. (A checkbox always has the same value, regardless of whether it's checked or not.)
To get an array of boolean values:
var filters = $('.filter').map(function(i, e){
return $(e).is(':checked');
}).get();

jquery: how to check if all radio buttons in a div are selected

my html looks like this
<div id="div1">
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
radio buttons are dynamically generated on my html so in that div i don't know how many radio buttons i have.
i want to make sure that the user will select a value for each one of them before he submits the form, how can i check that all radio buttons inside my div has a value checked?
Thank you
$(":radio").change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
alert("all answered");
}
}).change();
Demo: http://jsfiddle.net/yFaAj/15/
Restructure your HTML slightly - wrap each radio group in (say) a div. Then you can just do something like this to validate the form when the user submits it:
if ($('div:not(:has(:radio:checked))').length) {
alert("At least one group is blank");
}
Of course this can be tweaked in various ways to suit your HTML. The idea was from Find all radio groups which haven't been selected
Solution here http://jsfiddle.net/QxdnZ/1/
var checked = $("#div1 :radio:checked");
var groups = [];
$("#div1 :radio").each(function() {
if (groups.indexOf(this.name) < 0) {
groups.push(this.name);
}
});
if (groups.length == checked.length) {
alert('all are checked!');
}
else {
var total = groups.length - checked.length;
var a = total>1?' groups are ':' group is ';
alert(total + a + 'not selected');
}
Validate the form when the user submits it, using this validation code.
var blank = false;
$("input:radio").each(function() {
var val = $('input:radio[name=' + this.name + ']:checked').val();
if (val === undefined) {
blank = true;
return false;
}
});
alert(blank ? "At least one group is blank" : "All groups are checked");
First we get the names of all the radio button groups, then check that each one has a value. (Actually we're doing multiple checks, but that doesn't really matter.)
Looking for something along these lines? http://jsfiddle.net/gXsZp/3/
<div id="div1">
Q1
<input type="radio" name="r1" value="v1" />
<input type="radio" name="r1" value="v2" />
<input type="radio" name="r1" value="v3" />
<br/>Q2
<input type="radio" name="r2" value="v1" />
<input type="radio" name="r2" value="v2" />
<input type="radio" name="r2" value="v3" />
<br/>Q3
<input type="radio" name="r3" value="v1" />
<input type="radio" name="r3" value="v2" />
<input type="radio" name="r3" value="v3" />
</div>
<br/>
<input id="btn" type="submit" text="submit"/>
$('#btn').click(function(){
if ( $('#div1 input:radio:checked').size() == 3 )
return true;
return false;
});
Try this one:
$('input:radio', $('#div1')).each(function() {
if(name && name == $(this).attr('name'))
return true; // Skip when checking the same element name.
name = $(this).attr('name');
if(! $('input:radio[name="' + name + '"]:checked').length) {
alert('Oops, you missed some input there.. [' + name + ']');
return false;
}
});
It will loop through every radio button to check for checked radio & will break as soon it found non-checked radio group (first error found). But if you prefer to get all the errors (not only the first error found), just remove return false.
Try this:
function check(){
var allCheck = true;
if($("#div1 :radio:checked").length==0){
allCheck=false;
}
$("#div1 :radio").each(function(){
for(var i=0;i<$("#div1 :radio:checked").length;i++)
if($(this).attr("name")===$($("#div1 :radio:checked")[i]).attr("name"))
break;
else if(i==$("#div1 :radio:checked").length-1)
allCheck = false;
});
return allCheck;
}
This will work:
if($("#div1").children("input:radio:checked").size() == 3)
{
alert('three inputs were checked');
}

Making "Mark all" button

How can i make a "Mark all" link that, marks all checkboxes there is inside a td:
<td style="padding-right:4px;padding:4px;" class="alternating">
<input name="cbPick" type="checkbox" value="88156144" />
</td>
Don't know what language you write this in.. JavaScript?
It would be in Javascript.
You would be using the DOM API.
function markAll() {
var tds = document.getElementsByTagName('td');
for(var index in tds) {
var innerNode = tds[index].firstChild;
if(innerNode.tagName == 'input' && innerNode.attributes.type="checkbox")
innerNode.checked = true;
}
}
You'd then need to make sure that the onClicked handler for the mark all link references this function. This code also assumes that where the tickbox is inside the TD's, it is the first child - otherwise this code would be more complicated.
Reference info:
http://www.w3schools.com/jsref/dom_obj_checkbox.asp
Code:
function checkAll(value, arr) {
$(arr).each(function () {
if (value) {
$(this).attr('checked', 'checked');
}
else {
$(this).removeAttr('checked');
}
});
}
Usage:
<input type="checkbox" class="check' /><br />
<input type="checkbox" class="check' /><br />
<input type="checkbox" class="check' /><br />
Mark all
P.S.
Yes, it requires jQuery. OMG OMG!!
Yes, that would be javascript, something like:
<script type="text/javascript">
function selectAll(x) {
for(var i=0,l=x.form.length; i<l; i++){
if(x.form[i].type == 'checkbox' && x.form[i].name != 'selectAll'){
x.form[i].checked=x.form[i].checked?false:true
}
}
}
</script>
<form>
<input type="checkbox" name="selectAll" onclick="selectAll(this)" /> (Select all)<br />
<input type="checkbox" name="a" /> (A)<br />
<input type="checkbox" name="b" /> (B)<br />
<input type="checkbox" name="c" /> (C)<br />
<input type="checkbox" name="d" /> (D)<br />
<input type="checkbox" name="e" /> (E)
</form>
Yeah javascript is the way to go
here is a link for a way to do it
http://www.shiningstar.net/articles/articles/javascript/checkboxes.asp

Categories

Resources