Need help on Checkbox onclick jquery - javascript

trying to learn jquery and made a simple checkbox with a function where you can make all the options read-only checking on "none of the above" button.
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1"/>1
<br/>
<input type="checkbox" value="2"/>2
<br/>
<input type="checkbox" value="3"/>3
<br/>
</form><br/>
<input type="checkbox" value="" onclick="enableDisableAll(this);"/>None of the above
<script src="script.js">
</script>
</body>
</html>
function enableDisableAll(e) {
var own = e;
var form = document.getElementById("diagnosedForm");
var elements = form.elements;
for (var i = 0 ; i < elements.length ; i++) {
if(own !== elements[i] ){
if(own.checked == true){
elements[i].disabled = true;
elements[i].checked = false;
}else{
elements[i].disabled = false;
}
}
}
}
this will be the output
and the last checkbox will make it read-only
I want the same result but not putting onclick on the html file, instead using jquery to work it out.

You can assign an id to "none of the above" checkbox and then in your script.js you can do something like this:
// script.js
// Run enableDisableAll() on toggle click
$('#toggle').click(enableDisableAll)
function enableDisableAll() {
// Find all input elements inside "diagnosedForm"
const elements = $('#diagnosedForm input')
// Map thru inputs and toggle enable/disable state
elements.map((_, el) => {
$(el).prop('checked', false) // Reset checkboxes
$(el).prop('disabled', (i, v) => !v)
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1" />1
<br/>
<input type="checkbox" value="2" />2
<br/>
<input type="checkbox" value="3" />3
<br/>
</div>
</form>
<br/>
<input id="toggle" type="checkbox" value="" /> None of the above
</body>
</html>

Related

How to get Selected Checkbox value by ID

Currently my code works well with the input name, I can get the input value by input name
But I want my script to retrieve the input value with id input and not with name input?
here my code :
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
getSelectedCheckBoxwithValueText("test")
});
var getSelectedCheckBoxwithValueText = function (name1) {
var data = $('input[name="' + name1 + '"]:checked');
if (data.length > 0) {
var resultdata='' ;
data.each(function () {
var selectedValue = $(this).val();
resultdata += $('label[for="cb-' + selectedValue + '"]').text() + "<br/>";
});
$("#divchecked").html(resultdata);
}
else {
$("#divchecked").html("No Check box selected");
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="cb-cricket">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="cb-swimming">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="cb-blog">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="cb-coding">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>
</body>
jsfiddle: https://jsfiddle.net/showcode/L64nauo0/5/
You can use
var data = $('input[id=^"c"]:checked');
Only if the IDs not pseudos (so you really this IDs use), and do not use IDs thagt starts with c
This is a little hacker solution, but works!
There is no need to use id or name to select the checkboxes and/or their related labels. You can simplify your code like so
Select all the checkboxes from the DOM and listen to change event on them.
When the value of a checkbox changes, you get all selected checkboxes
using .filter().
And then get the text of the related labels using .map() and .get().
$(document).ready(function () {
let $checkboxes = $('input[type="checkbox"]');
$checkboxes.change(function () {
let labels = $checkboxes.filter(':checked').map(function(){
return $(this).next('label').text().trim();
}).get();
$("#divchecked").html(labels.join('<br />') || "No Check box selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="c1">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="c2">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="c3">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="c4">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>

addEventListener to multiple checkboxes

Below, I have a simple form that has 4 checkboxes acting as seats. What I am trying to do is when a visitor chooses, say, seat checkboxes with IDs A2 and A4, I want those IDs and their total value to be shown instantly after clicking inside a paragraph with which have a name called id="demo". When a button [Reserve Now] has been clicked, the total value should be assigned to a variable called $TotalCost.
How can I accomplish this? Here's my code:
<!DOCTYPE html>
<html>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<br>
Total: USD <input type="submit" value="Reserve Now">
</form>
</p>
<script>
document.getElementById("A1").addEventListener("click", displayCheck);
function displayCheck() {
document.getElementById("demo").innerHTML = ;
}
</script>
</body>
</html>
Here's one approach to setting up event listeners on checkboxes. I used document.querySelectorAll("input[type='checkbox']"); to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections object can keep track of which items have been checked. When a checkbox is clicked on, the item values are added to the object by key. When the checkbox is off, the item is deleted from the object. Whenever an action happens, the DOM is updated with all relevant information based on the contents of selections.
This example is just a quick sketch to give you the idea. You'll need another event listener for your submit button to handle sending the form data to your PHP script. I'll leave that as an exercise.
Note that the HTML you've provided is invalid because nesting is broken. A HTML validator can be helpful for fixing these sort of problems.
var selections = {};
var checkboxElems = document.querySelectorAll("input[type='checkbox']");
var totalElem = document.getElementById("seats-total");
var seatsElem = document.getElementById("selected-seats");
for (var i = 0; i < checkboxElems.length; i++) {
checkboxElems[i].addEventListener("click", displayCheck);
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
name: e.target.name,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
var result = [];
var total = 0;
for (var key in selections) {
var listItem = "<li>" + selections[key].name + " " +
selections[key].value + "</li>";
result.push(listItem);
total += parseInt(selections[key].value.substring(1));
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join("");
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p>Selected Seat(s)</p>
<!-- container for displaying selected seats -->
<ul id="selected-seats"></ul>
<div>
Total: $<span id="seats-total">0</span> USD
<input type="submit" value="Reserve Now">
</div>
</form>
</body>
</html>
Often, you'll want to generate the elements dynamically and add event listeners. Here's a toy example:
for (let i = 0; i < 1000; i++) {
const checkbox = document.createElement("input");
document.body.appendChild(checkbox);
checkbox.type = "checkbox";
checkbox.style.margin = 0;
checkbox.addEventListener("mouseover", e => {
e.target.checked = !e.target.checked;
});
checkbox.addEventListener("mouseout", e =>
setTimeout(() => {
e.target.checked = !e.target.checked;
}, 1000)
);
}
See also event delegation which lets you add a single listener on many child elements.
Here is a starter... About the math addition.
Since your question was tag with jQuery, It's a jQuery way.
Notice that the form will only send something like {vehicle:['on','','on','on']}... Which is way far from anyone would want to send to the server. But that is another question.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
Selected Seat(s): <span id="seats"></span>
<br>
<br>
Total: $<span id="demo">0.00</span> USD <input type="submit" value="Reserve Now">
</form>
<script>
$(document).ready(function(){
var total=0;
var seats=[];
$("form input").on("click",function(){
var id=$(this).attr("id");
if($(this).is(":checked")){
total+=parseInt($(this).val());
seats.push(id);
}else{
total-=parseInt($(this).val());
seats.splice(seats.indexOf(id),1);
}
$("#demo").text(total.toFixed(2));
$("#seats").html(seats.sort().join(","));
});
});
</script>
</body>
</html>

Javascript: How to get selected checkbox items in a table

I have a checkbox, where I am loading its inputs from a web service. I'm developing a function which filters the selected items and puts them in a table.
My checkbox looks like this:
<label class="checkbox" data-match-for="filtre-competences">
<input id="checkbox_competence" name="missionPlace" value="" type="checkbox" data-match-forcontent="id-competence">
<span class="check"></span>
<span class="checkbox-title" data-match-forcontent="titre-competence"></span>
<span>(<span data-match-forcontent="nb-mission"></span>)</span>
</label>
I want to filter the selected elements in a table and of course deselect items which may bed deselected dynamically.
My function looks like this:
selectCompetences:function () {
var checkbox = document.querySelector('#checkbox_competence');
var arr = new Array();
checkbox.addEventListener('click',function () {
if () {
//selected : add to table
arr.push(checkbox.getAttribute("value"))
}
else {
// deselected: remove from table
}
})
}
I need to complete this function. Any suggestions?
var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join(", "));
function togglecheckboxes(master,group){
var cbarray = document.getElementsByName(group);
for(var i = 0; i < cbarray.length; i++){
cbarray[i].checked = master.checked;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="checkbox" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbg1[]')"> Toggle All
<br><br>
<input type="checkbox" id="cb1_1" class="cbgroup1" name="cbg1[]" value="1"> Item 1<br>
<input type="checkbox" id="cb1_2" class="cbgroup1" name="cbg1[]" value="2"> Item 2<br>
<input type="checkbox" id="cb1_3" class="cbgroup1" name="cbg1[]" value="3"> Item 3<br>
<input type="checkbox" id="cb1_4" class="cbgroup1" name="cbg1[]" value="4"> Item 4<br>
</body>
</html>

How to select all checkbox using jquery or javascript? [duplicate]

This question already has answers here:
How to select all checkboxes with jQuery?
(15 answers)
Closed 8 years ago.
I have multiple checkboxes , there is a checkbox with select all name, now i want that when some tick
the select all checkbox, then all the checkbox must be selected. I think this will be in jquery.
any tutorial link or codes with hints would be appreciated.the code snip is under...
<input type="checkbox" value="">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
This should check all checkboxes when you check the "Select All" one, and also uncheck all checkboxes when you uncheck it.
$("#selectAll").click(function () {
$(":checkbox").not(this).prop("checked", $(this).is(":checked"));
});
If you don't want the uncheck behavior:
$("#selectAll").click(function () {
if ($(this).is(":checked")) {
$(":checkbox").not(this).prop("checked", true);
}
});
But of course, you must identify it. Do it by adding the id="selectAll" attribute (or any other id you wish, just make sure you change the JavaScript code as well):
<input type="checkbox" value="" id="selectAll">Select All<br/>
<input type="checkbox" value="">A<br/>
<input type="checkbox" value="">B<br/>
<input type="checkbox" value="">C<br/>
<input type="checkbox" value="">D<br/>
<input type="checkbox" value="">E<br/>
<input type="checkbox" value="">F<br/>
<input type="checkbox" value="">G<br/>
<input type="checkbox" value="">H<br/>
<input type="checkbox" id="exp" />Tick All Checkbox<br/>
<input type="checkbox" value="demo1" class="subchkbox"/>No 1<br/>
<input type="checkbox" value="demo2" class="subchkbox"/>No 2<br/>
<input type="checkbox" value="demo3" class="subchkbox"/>No 3<br/>
<input type="checkbox" value="demo4" class="subchkbox"/>No 4<br/>
<input type="checkbox" value="demo5" class="subchkbox"/>No 5<br/>
<sctipt type="text/javascript">
/*Include the jquery library 1.9.1*/
$(document).ready(function() {
$('#exp').click(function(event) {
if(this.checked) {
$('.subchkbox').each(function() {
this.checked = true;
});
}else{
$('.subchkbox').each(function() {
this.checked = false;
});
}
});
});
[the fiddle is here][1]
Using jQuery :
$("input[type=checkbox]").prop({ checked : true })
JSFiddle
Using pure JavaScript :
var inputs = document.querySelectorAll('input[type=checkbox]')
Object.keys(inputs).forEach(function(i){
inputs[i].checked = true
})
JSFiddle
$("checkboxContainer").find("input[type='checkbox']").each(function() {
$(this).prop("checked", true);
});
I think using .find() is faster when selecting multiple elements.
If you want to do this in plain JS, it's also pretty simple.
You just have to loop through all of the inputs and set checked to true (or false), which isn't very efficient.
document.getElementById("all").addEventListener("change", function() {
if (this.checked) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = true;
}
}
} else {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].type === "checkbox") {
boxes[i].checked = false;
}
}
}
});
<input type="checkbox" value="" id="all">Select All
<br/>
<input type="checkbox" value="">A
<br/>
<input type="checkbox" value="">B
<br/>
<input type="checkbox" value="">C
<br/>
<input type="checkbox" value="">D
<br/>
<input type="checkbox" value="">E
<br/>
<input type="checkbox" value="">F
<br/>
<input type="checkbox" value="">G
<br/>
<input type="checkbox" value="">H
<br/>
Derived from the current answer marked as correct, it can all be much simpler:
$(document).ready(function()
{
$('#exp').click(function(event)
{
$('.subchkbox').prop({
checked: $(this).prop('checked')
});
});
});

how to get checked radio button value in javascript

I have some set of radio button. I am trying to get checked radio button value using java script. But I got the error of uncaught id. I do the following code in html 5. I am not getting the value.
function timeout()
{
if (document.getElementById["RadioButton1"].checked)
{
choice = document.getElementById["RadioButton1"].value;
alert('choice');
}
if (document.getElementById["RadioButton2"].checked)
{
choice = document.getElementById["RadioButton2"].value;
alert('choice');
}
if (document.getElementById["RadioButton3"].checked)
{
choice = document.getElementById["RadioButton3"].value;
alert('choice');
}
if (document.getElementById["RadioButton4"].checked)
{
choice = document.getElementById["RadioButton4"].value;
alert('choice');
}
var c = document.getElementById("label1").value;
}
If you use the same name(in same radio button group) for all radio buttons like this
<input type="radio" id="RadioButton1" name="radio_group" value="1"/>
<input type="radio" id="RadioButton2" name="radio_group" value="2"/>
<input type="radio" id="RadioButton3" name="radio_group" value="3"/>
you can get the selected(checked radio button value ) using jQuery,in one line.
var Val = $("input[name=radio_group]:checked").val();
A set of radio buttons should all have the same name. So get the set, find the checked one and read its value:
function getValue(name) {
var rbs = document.getElementsByName(name);
for (var i=0, iLen=rbs.length, i<iLen; i++) {
if (rbs[i].checked) {
return rbs[i].value;
}
}
}
If the controls are in a form (which the usually are) and you have a reference to the form, you can get the set using:
var rbs = formRef[name];
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="radio"]:checked');
if (result.length > 0) {
$('#result').html(result.val()+" is Checked");
}else{
$('#result').html(" No radio button is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>
The major problem visible from your code is a syntax error.
document.getElementById is a method and not an object, so you should call it with parens:
// --------------------v--------------v
document.getElementById("RadioButton1").value
This is ans for #yogi comment(
how we can implement same for checkboxes?)
$(document).ready(function(){
$('#btnsubmit').click(function(){
var result = $('input[type="checkbox"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#result').html(resultstring);
}else{
$('#result').html(" No checkbox is Checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<input type="submit" id="btnsubmit" value="submit">
<div id="result"></div>

Categories

Resources