Disable button if radio is unchecked. Enable when checked - javascript

I can't seem to get my button to re-enable after it's been disabled. Currently, if nothing is checked and I mouseover it, the button disables. It stays enabled if I have something checked, but if I first hover over then button, with nothing checked, I can't get it to re-enable if I check something.
Here's My JS:
var inputs = document.getElementsByTagName('input');
var letsCookButton = document.querySelector('#letsCook');
letsCookButton.addEventListener('mouseover', checkIfChecked);
function checkIfChecked() {
letsCookButton.disabled = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
letsCookButton.disabled = false;
}
}
}
Here's my HTML:
div class="mainBox" id="box-one">
<p id="left-box-title">What are you looking for?<span>*</span></p>
<ul>
<li><input type="radio" name="food" id="side-food"> Side</li>
<li><input type="radio" name="food" id="main-food"> Main Dish</li>
<li><input type="radio" name="food" id="dessert-food"> Dessert</li>
<li><input type="radio" name="food" id="entire-meal"> Entire Meal</li>
</ul>
<button id="letsCook">LET'S COOK!</button>
</div>

You will have to slightly rethink how you want the UX of your app to work, because disabled elements do not produce events.
Since at least one radio button will remain checked after the first click, I would suggest disabling the button from the start and then enabling it on a radio click event.
<div class="mainBox" id="box-one">
<p id="left-box-title">What are you looking for?<span>*</span></p>
<ul id="radio-group">
<li><input type="radio" name="food" id="side-food"> Side</li>
<li><input type="radio" name="food" id="main-food"> Main Dish</li>
<li><input type="radio" name="food" id="dessert-food"> Dessert</li>
<li><input type="radio" name="food" id="entire-meal"> Entire Meal</li>
</ul>
<button id="letsCook" disabled>LET'S COOK!</button>
</div>
var inputGroup = document.querySelector('#radio-group');
var letsCookButton = document.querySelector('#letsCook');
inputGroup.addEventListener('click', function () {
letsCookButton.removeAttribute('disabled')
});
Working example in JS Fiddle: https://jsfiddle.net/Ollie1700/wxn9f63p/4/

Related

Convert checklist auto submit code to checklist with submit button

Here is the checklist radio button code I am using right now, I would like to convert it into a checklist with submit button. Currently, selecting one option will filter the result instantly, but i want to select multiple options and click submit button to get result. I want to use it without effecting the existing functions, as an addon feature.
In short it should allow to select more than one option at a time and submit.
Someone give me an example on how to do this ?
I am trying to learn JQuery and javascript, and need someone's help.
I tried but couldn't get a working result.
I want to use this method
<form>
<ul>
Brand
<li><input name="Samsung" type="checkbox" value="Samsung" /> Samsung</li>
<li><input name="OnePlus" type="checkbox" value="OnePlus" /> OnePlus</li>
<li><input name="Apple" type="checkbox" value="Apple" /> Apple</li>
</ul>
<ul>
RAM
<li><input name="1GB" type="checkbox" value="1GB" /> 1GB</li>
<li><input name="2GB" type="checkbox" value="2GB" /> 2GB</li>
</ul>
<div><button id="apply">Apply</button> <button id="apply">Clear</button></div>
</form>
So that the filter will not apply automatically, this funtion is for mobile pages.
and in PC, the regular auto filter will work.
Example image attached
<h3>Sort</h3>
<div class="list-group-item checkbox">
<label for="radio1">
<input type="radio" id="radio" class="common_selector brand" name="radio" value="Samsung"> Samsung
</label>
<label>
<input type="radio" class="common_selector brand" name="radio" value="Apple" > Apple
</label>
<label>
<input type="radio" class="common_selector brand" name="radio" value="Nokia" > Nokia
</label>
<label>
</div>
The following JQuery function is capturing data from this checklist
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var sort = get_filter('sort');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, sort:sort},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
$('#price_range').slider({
range:true,
min:1000,
max:95000,
values:[1000, 95000],
step:500,
stop:function(event, ui)
{
$('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
$('#hidden_minimum_price').val(ui.values[0]);
$('#hidden_maximum_price').val(ui.values[1]);
filter_data();
}
});
});
</script>
I tried the following code, but it didn't work.
<form>
<input type="checkbox" value="Samsung"> Samsung
<input type="checkbox" value="Apple"> Apple
<input type="button" id="apply" class="common_selector brand" value="Submit">
</form>
$('#apply').click(function(){
filter_data();
});
In the html, convert the radiobuttons to checkboxes. Then create the Apply button. In the script, connect the click event of the Apply button to the filter_data function.
<form>
<input type="checkbox" class="brand" id="samsung" value="Samsung"> Samsung
<input type="checkbox" class="brand" id="apple" value="Apple"> Apple
<button id="apply" class="common_selector brand">Apply</button>
</form>
The script would then be
$('#apply').click(function(){
filter_data();
});
In place of "$('#apply')" you will include a selector for the button, which can be based on the identifier (as above).

How to limit the checked checkboxes to just one at a time?

I am trying to create a filter using checkboxes. I need to only have one checkbox checked at a time. How do I do this?
Scenario: The page has a catalog of watches. The user wants to filter the watches according to for men or for women
Here is my code:
$("#filter-options :checkbox").click(function()
{
$(".collection-wrapper .strap-wrapper").hide();
$("#filter-options :checkbox:checked").each(function()
{
$("." + $(this).val()).fadeIn();
});
if($('#filter-options :checkbox').filter(':checked').length < 1)
{
$(".collection-wrapper .strap-wrapper").fadeIn();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Filter Items</h3>
<ul id="filter-options">
<li><input type="checkbox" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="checkbox" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
<div class="collection-wrapper">
<div class="strap-wrapper filter_man">
<h2>man</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_man filter_woman">
<h2>man / woman</h2>
<p></p>
</div>
<div class="strap-wrapper filter_woman">
<h2>woman</h2>
<p></p>
</div>
</div>
Thanks in advance!
Checkboxes are used for selecting multiple values of choices. What you need is Radio Buttons. They are used exactly for this purpose. One can select only one radio button at a time. So replace your code with:
<ul id="filter-options">
<li><input type="radio" name="filter" value="filter_man" data-filter_id="man"> Man</li>
<li><input type="radio" name="filter" value="filter_woman" data-filter_id="woman"> Woman</li>
</ul>
See an example here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio
Radio buttons are what you are looking for ;)
take at look at these links:
jQuery api demo
Fiddle example
HTML:
<form id="myForm">
<input type="radio" name="myRadio" value="1" /> 1 <br />
<input type="radio" name="myRadio" value="2" /> 2 <br />
<input type="radio" name="myRadio" value="3" /> 3 <br />
</form>
JS
$('#myForm input').on('change', function() {
alert($('input[name="myRadio"]:checked', '#myForm').val());
});
You could use radio buttons or you could do something like:
$('input[type=checkbox]').change(function(){
if ($('input[type=checkbox]:checked').length > 1) {
this.checked = false;
}
})
You could just use radio buttons, but if you want to do it with checkboxes, solution is pretty simple.
When you click on one of the checkboxes, select all the checkboxes and remove "checked" state, and then just add checked on clicked checkbox
Something like this:
// On checkbox click
$("#filter-options input[type=checkbox]").click(function(event) {
// Uncheck all checkboxes
$("#filter-options input[type=checkbox]").prop("checked", false);
// Check that one that you clicked
$(this).prop("checked", true)
});

Checkbox - Getting multiple check boxes checked on checking only one

I am trying to implement a check box which checks all the check boxes on the page. But when I changed the code slightly, it stopped working. I want to keep the changed code and still want the functionality to be working. Kindly help!
* Kindly ignore the missing tags if any. It is correct unless I made mistake in editing the question.
<script>
function toggle(source) {
checkboxes = document.getElementsByName('qchecked[]');
for(var i=0, n=checkboxes.length;i<n;i++){
checkboxes[i].checked = source.checked;
}
}
</script>
<html>
/* Code for the check box which when checked, checks all the checkbox. */
<input type='checkbox' class='css-checkbox' id='checkbox' onClick='toggle(this)'/>
<label for='checkbox' class='css-label lite-y-green'></label>
/* Code for the check boxes which should be checked when the check box with id=checkbox is checked.
I changed the code from INITIAL CODE to CHANGED CODE for some other purpose and the toggle stopped working.
Now clicking on that one check box is not marking or un marking all the check boxes. */
<!-- INITIAL CODE -->
<input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[]'/>
<label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
<!-- CHANGED CODE -->
<input type='checkbox' id='yes_checkbox[$index]' class='css-checkbox' name='qchecked[$array6[qID]]'/>
<label for='yes_checkbox[$index]' class='css-label lite-y-green'></label>
</html>
Instead of name, give a class to all elements and you should use by
getElementsByClassName('your_class');
Since you name of inputs are different, you can make use of common class
checkboxes = document.getElementsByClassName('css-checkbox');
Try this..
<ul class="chk-container">
<li><input type="checkbox" id="selecctall"/> Selecct All</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item1"> This is Item 1</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item2"> This is Item 2</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item3"> This is Item 3</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item4"> This is Item 4</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item5"> This is Item 5</li>
<li><input class="checkbox1" type="checkbox" name="check[]" value="item6"> This is Item 6</li>
<li><input class="checkbox2" type="checkbox" name="check[]" value="item6"> Do not select this</li>
</ul>
$(document).ready(function() {
$('#selecctall').click(function(event) { //on click
if(this.checked) { // check select status
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.checkbox1').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
});
}
});
});
demo:https://jsfiddle.net/go1gL743/

Check all other checkboxes when one is checked

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):
<div id="ScrollCB">
<input type="checkbox" name="ALL" value="checked" checked="checked">
All (if nothing selected, this is default) <br>
<c:forEach items="${serviceList}" var="service">
<input type="checkbox" name="${service}" value="checked"> ${service} <br>
</c:forEach>
</div>
What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).
I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):
<script type="text/javascript">
$ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
$(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>
Could you tell me some simple approach how to get it work? Thanks a lot!
demo
updated_demo
HTML:
<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
JS:
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('div input').attr('checked', true);
} else {
$('div input').attr('checked', false);
}
});
HTML:
<form>
<label>
<input type="checkbox" id="selectall"/> Select all
</label>
<div id="checkboxlist">
<label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" name="sample[]"/>checkbox4</label><br />
</div>
</form>
JS:
$('#selectall').click(function() {
$(this.form.elements).filter(':checkbox').prop('checked', this.checked);
});
http://jsfiddle.net/wDnAd/1/
Thanks to #Ashish, I have expanded it slightly to allow the "master" checkbox to be automatically checked or unchecked, if you manually tick all the sub checkboxes.
FIDDLE
HTML
<label><input type="checkbox" name="sample" class="selectall"/>Select all</label>
<div id="checkboxlist">
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox1</label><br/>
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox2</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox3</label><br />
<label><input type="checkbox" class="justone" name="sample[]"/>checkbox4</label><br />
</div>
SCRIPT
$('.selectall').click(function() {
if ($(this).is(':checked')) {
$('input:checkbox').prop('checked', true);
} else {
$('input:checkbox').prop('checked', false);
}
});
And now add this to manage the master checkbox as well...
$("input[type='checkbox'].justone").change(function(){
var a = $("input[type='checkbox'].justone");
if(a.length == a.filter(":checked").length){
$('.selectall').prop('checked', true);
}
else {
$('.selectall').prop('checked', false);
}
});
Add extra script according to your checkbox group:
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('colors[]');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
HTML Code:
<input type="checkbox" id="selectall" onClick="selectAll(this,'color')" />Select All
<ul>
<li><input type="checkbox" name="colors[]" value="red" />Red</li>
<li><input type="checkbox" name="colors[]" value="blue" />Blue</li>
<li><input type="checkbox" name="colors[]" value="green" />Green</li>
<li><input type="checkbox" name="colors[]" value="black" />Black</li>
</ul>
use this i hope to help you i know that this is a late answer but if any one come here again
$("#all").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Only in JavaScript with auto check/uncheck functionality of master when any child is checked/unchecked.
function FnCheckAll()
{
var ChildChkBoxes = document.getElementsByName("ChildCheckBox");
for (i = 0; i < ChildChkBoxes.length; i++)
{
ChildChkBoxes[i].checked = document.forms[0].CheckAll.checked;
}
}
function FnCheckChild()
{
if (document.forms[0].ChildCheckBox.length > document.querySelectorAll('input[name="ChildCheckBox"]:checked').length)
document.forms[0].CheckAll.checked = false;
else
document.forms[0].CheckAll.checked = true;
}
Master CheckBox:
<input type="checkbox" name="CheckAll" id="CheckAll" onchange="FnCheckAll()" />
Child CheckBox:
<input type="checkbox" name="ChildCheckBox" id="ChildCheckBox" onchange="FnCheckChild()" value="#employee.Id" />```
You can use jQuery like so:
jQuery
$('[name="ALL"]:checkbox').change(function () {
if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
else $('input:checkbox').removeAttr('checked');
});
A fiddle.
var selectedIds = [];
function toggle(source) {
checkboxes = document.getElementsByName('ALL');
for ( var i in checkboxes)
checkboxes[i].checked = source.checked;
}
function addSelects() {
var ids = document.getElementsByName('ALL');
for ( var i = 0; i < ids.length; i++) {
if (ids[i].checked == true) {
selectedIds.push(ids[i].value);
}
}
}
In HTML:
Master Check box <input type="checkbox" onClick="toggle(this);">
Other Check boxes <input type="checkbox" name="ALL">
You can use the :first selector to find the first input and bind the change event to it. In my example below I use the :checked state of the first input to define the state of it's siblings. I would also suggest to put the code in the JQuery ready event.
$('document').ready(function(){
$('#ScrollCB input:first').bind('change', function() {
var first = $(this);
first.siblings().attr('checked', first.is(':checked'));
});
});
I am not sure why you would use a label when you have a name on the checkbox. Use that as the selector. Plus your code has no labels in the HTML markup so it will not find anything.
Here is the basic idea
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings().prop("checked",this.checked);
});
if there are other elements that are siblings, than you would beed to filter the siblings
$(document).on("click",'[name="ALL"]',function() {
$(this).siblings(":checkbox").prop("checked",this.checked);
});
jsFiddle

How to show different links when certain questions are answered

How do I make it so that when I click AT&T, 8GB, and Black it shows a link and when I click Other, 8GB, and White it shows a different link. This is what I came up with. This is my first ever attempt so don't be rough on me. I'm trying to achieve something similar to http://glyde.com/sell/iphone-4s.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
<!--
.bgclr {background-color: white; color: black; font-weight: bold;}
-->
</style>
<script language="JavaScript">
<!-- Begin
var numQues = 3;
var numChoi = 3;
var answers = new Array(3);
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
break;
}
}
}
}
</script>
</head>
<body>
<form name="quiz">
What carrier do you have?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q1" value="AT&T"/>AT&T</li>
<li><input type="radio" name="q1" value="Other"/>Other</li>
<li><input type="radio" name="q1" value="Unlocked"/>Unlocked</li>
</ul>
What is your phones capicity?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q2" value="8GB"/>8GB</li>
<li><input type="radio" name="q2" value="16GB"/>16GB</li>
</ul>
What color is your phone?
<ul style="margin-top: 1pt">
<li><input type="radio" name="q3" value="Black"/>Black</li>
<li><input type="radio" name="q3" value="White"/>White</li>
</ul>
<input type="button" value="Get score" onClick="getScore(this.form)"/>
</body>
</html>
http://jsfiddle.net/XwN2L/2547/
OK. Add an "onclick" event to each element of the form, which calls a method called tryToMakeLink(). So for every element
<input type="radio" name="q1" value="AT&T"/>
should now read
<input type="radio" onclick=tryToMakeLink(); name="q1" value="AT&T"/>
Also, add a div to the bottom to display the dynamic link.
<form name="quiz" id='quiz'>
What carrier do you have?
<ul style="margin-top: 1pt">
<li><input type="radio" onclick=tryToMakeLink(); name="q1" value="AT&T"/>AT&T</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q1" value="Other"/>Other</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q1" value="Unlocked"/>Unlocked</li>
</ul>
What is your phones capicity?
<ul style="margin-top: 1pt">
<li><input type="radio" onclick=tryToMakeLink(); name="q2" value="8GB"/>8GB</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q2" value="16GB"/>16GB</li>
</ul>
What color is your phone?
<ul style="margin-top: 1pt">
<li><input type="radio" onclick=tryToMakeLink(); name="q3" value="Black"/>Black</li>
<li><input type="radio" onclick=tryToMakeLink(); name="q3" value="White"/>White</li>
</ul>
<input type="button" value="Get score" onClick="getScore(this.form)"/>
<br>
<div id=linkDiv>
--
</div>
</form>
The tryToMakeLink() method does the following:
Look at each radio. If the user has not made a choice for each question, do nothing.
If the user has made a choice for each question, then show 1 link if they have 8gb at&t black, show another link if they have other 8gb white, show a 3rd link if they have any other combination. you can easily add other configurations by adding more else if clauses to the function.
So here it is (JavaScript)
function tryToMakeLink()
{
//get all selected radios
var q1=document.querySelector('input[name="q1"]:checked');
var q2=document.querySelector('input[name="q2"]:checked');
var q3=document.querySelector('input[name="q3"]:checked');
//make sure the user has selected all 3
if (q1==null || q2==null ||q3==null)
{
document.getElementById("linkDiv").innerHTML="--";
}
else
{
//now we know we have 3 radios, so get their values
q1=q1.value;
q2=q2.value;
q3=q3.value;
//now check the values to display a different link for the desired configuration
if (q1=="AT&T" && q2=="8GB" && q3=="Black")
{
document.getElementById("linkDiv").innerHTML="<a href=#>att 8gb black</a>";
}
else if (q1=="Other" && q2=="8GB" && q3=="White")
{
document.getElementById("linkDiv").innerHTML="<a href=#>other 8b white</a>";
}
else
{
document.getElementById("linkDiv").innerHTML="<a href=#>some third option</a>";
}
}
}
This is all javascript, as indicated by your post; however you may want to look into jQuery.
EDIT:
A better way to do this is to bind the click event to each radio when the document loads, instead of needing an "onclick=" in each input tag.
so you add an onload to your body
<body onLoad="attachClickEvents();">
and add this javascript
function attachClickEvents()
{
var inputs=document.getElementById('quiz').elements;
for (var i=0;i<inputs.length;i++)
{
inputs[i].onclick = function() {
tryToMakeLink();
};
}
}
I think that this could help you!
How to change the images on button click
It is another SO question that I found useful for the same thing!

Categories

Resources