Materializecss - prop radio checkbox with jQuery on click - javascript

I have 1 radio item, and I want it to behave like a checkbox. So now, it gets selected but I couldn't bind it to prop state on click.
So I want to achieve is: when clicked on radio btn, it reverses its checked state.
Here is what I tried:
<form action="#">
<p>
<input name="group" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>
$(document).ready(function() {
$('#test').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
})
What interesting is, if I create another button and bind it to change checked value, it works
<button id="faker" type="button">
Faker Btn
</button>
$('#faker').click(function() {
$('#test').prop('checked', !$('#test').prop('checked'))
})
Here is a fiddle: https://jsfiddle.net/55L52yww/81/

A radio can behave like a checkbox if you add a state attribute to the radio element like in:
<input name="group" type="radio" id="test" data-state="false"/>
Now, you can save the last state and compare with the current value in order to decide the action to do.
The snippet:
$('#test').on('click', function(e) {
var a = $(this).data('state');
var b = $(this).prop('checked');
if (a && b) {
b = false;
$(this).prop('checked', b);
}
$(this).data('state', b);
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<form action="#">
<p>
<input name="group" type="radio" id="test" data-state="false"/>
<label for="test">Red</label>
</p>
</form>

When you get into the function that was triggered by the radio button itself, the state of the checked property has already changed. That causes a problem on the first click, because the new state is true and therefore your function sets it back to false.
You can solve this by keeping track of the checked state yourself in a separate data attribute and checking that instead.
$(function() {
$('#test').click(function() {
var $this = $(this);
if ($this.data('previousState')) {
$this.prop('checked',false).data('previousState',false);
}
else {
$this.prop('checked',true).data('previousState',true);
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<form action="#">
<p>
<input name="group1" type="radio" id="test" />
<label for="test">Red</label>
</p>
</form>

Related

How to properly use Jquery to disable checkboxes in a Django Form when a certain number of them are checked

I've been trying a couple of ways to disable checkboxes in a Django ModelForm. Using Jquery I was able to write some code that does disable checkboxes when a certain number is checked, but it also disables the ones that have been checked. I want a dynamic way to check and uncheck boxes and only block boxes that have not been checked when the limit is hit.
This is my JS:
function checkBoxes() {
$(' input[type=checkbox]').
attr('disabled', true);
$(document).on('click',
'input[type=checkbox]',
function (event) {
if ($(this).is(":checked")) {
console.log("1")
} else {
console.log('2')
}
});
}
The issue I'm having trying to figure this out is how to verify if the box has been checked or not because of how I'm creating the checkbox list with Django:
<div style="height:30px"></div>
<form method="post">
{% csrf_token %}
{{ context.form.as_p }}
<button type="submit">Submit</button>
</form>
How can I fix my JS and be able to enable and disable checkboxes dynamically, meaning when the limit is hit, disable all the unchecked boxes, and when the limit is reduced allow checkboxes to be clicked again?
Just use
:checked and :not(:checked) in your jquery selector, like this:
$(document).on('click', 'input[type=checkbox]', function(event) {
if ($('.checkbox-container input[type=checkbox]:checked').length >= 3) {
$('.checkbox-container input[type=checkbox]:not(:checked)').attr('disabled', true);
} else($('.checkbox-container input[type=checkbox]').attr('disabled', false));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<div class="checkbox-container">
<input type="checkbox" id="scales1" name="scales1" checked>
<input type="checkbox" id="scales2" name="scales2" checked>
<input type="checkbox" id="scales3" name="scales3">
<input type="checkbox" id="horns1" name="horns1">
<input type="checkbox" id="horns2" name="horns2">
<input type="checkbox" id="horns3" name="horns3">
</div>
</body>
</html>

How to capture whether a checkbox has been checked or not?

I have a Bootstrap form modal being used for a webinar signup. I've removed the other fields, but I have multiple text fields that are being captured and pushed to a CMS.
It's just these 3 checkboxes that I can't seem to get to push data across correctly. The checkboxes are recording all as "on" if the form is submitted once, but if the form is submitted a second time then the checkboxes that are checked/not checked will push through "on" and "off" accordingly. So it works on the second submit, but not on the first. Any help would be greatly appreciated. I'm new to javascript and jquery, so i'm now at the point of guessing.
$(document).ready(function() {
$('.register-webinar').click(function() {
checked = $("input[type=checkbox]:checked").length;
if (!checked) {
alert("You must select at least one session.");
return false;
}
});
$('input.webinar').change(function() {
if ($(this).is(":checked")) {
$(this).val("on")
} else {
$(this).val("off")
}
});
$('#railway_form').on("submit", function(e) {
e.preventDefault();
setTimeout(AoProcessForm(this), 200);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<div class="form-popup-bg">
<div class="form-container">
<button id="btnCloseForm" class="close-button">X</button>
<h1 style="text-align:center;">Register your attendance</h1>
<p style="text-align:center;">Please select which session/s you wish to attend.</p>
<form name="railway_webinar" id="railway_form" class="railway_webinar" action="">
<div class="form-group">
<input type="checkbox" id="Webinar_1" name="Webinar_1" class="webinar">
<label for="Webinar_1">webinar 1</label><br/>
<input type="checkbox" id="Webinar_2" name="Webinar_2" class="webinar">
<label for="Webinar_2">webinar 2</label><br/>
<input type="checkbox" id="Webinar_3" name="Webinar_3" class="webinar">
<label for="Webinar_3">webinar 3</label>
</div>
<input type="submit" value="Reserve my seat!" class="form-block-cta register-webinar" />
</form>
</div>
</div>
Figured it out. All I needed to do was set the checkbox value to "off", as they would all be "on" by default.

Radio button is showing div on selection but not hiding after selecting a different radio button

I have three divs I want to show based on a radio selection. I've written the below script, but the problem I've run into is the div doesn't hide after a different radio button is selected. I'm using ucalc so I can't change the class names or ids of the divs or the radio buttons so have to work with that.
Note, the radio button is automatically selected when the form loads so the first div needs to be showing initially.
Code below:
$(document).ready(function(){
// First Div/Radio Button
$('#input_radio-30-0-des').on('change', function(){
var a = $(this).prop('checked');
if(a) {
$("#grid-40-42").show();
} else {
$("#grid-40-42").hide();
}
});
// Second Div/Radio Button
$("#grid-44-46").hide();
$('#input_radio-30-1-des').on('change', function(){
var a = $(this).prop('checked');
if(a) {
$("#grid-44-46").show();
} else {
$("#grid-44-46").hide();
}
});
// Third Div/Radio Button
$("#grid-46-48").hide();
$('#input_radio-30-2-des').on('change', function(){
var a = $(this).prop('checked');
if(a) {
$("#grid-46-48").show();
} else {
$("#grid-46-48").hide();
}
});
});
I'm not very familiar with writing javascript (you can probably tell!) so an explanation for 'dummies' would be appreciated!
Thank you for your help!
You need to hide 2nd & 3rd div by CSS and when user change other button then find ID so according to ID show that div and rest div will hide as below snippet.
$(document).ready(function(){
$('#input_radio-30-0-des, #input_radio-30-1-des, #input_radio-30-2-des').on('change', function(){
var getid = $(this).attr('id');
if (getid=='input_radio-30-0-des') {
$('#grid-44-46, #grid-46-48').hide()//2nd and 3rd div hide
$("#grid-40-42").show();
}
if (getid=='input_radio-30-1-des') {
$('#grid-40-42, #grid-46-48').hide()//1st and 3rd div hide
$("#grid-44-46").show();
}
if (getid=='input_radio-30-2-des') {
$('#grid-40-42, #grid-44-46').hide()//1st and 2rd div hide
$("#grid-46-48").show();
}
})
});
#grid-44-46, #grid-46-48{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" name="div-show-hide" id="input_radio-30-0-des" checked> Button One</label>
<label><input type="radio" name="div-show-hide" id="input_radio-30-1-des"> Button Two</label>
<label><input type="radio" name="div-show-hide" id="input_radio-30-2-des"> Button Three</label>
<div id="grid-40-42"><h2>Show - Div One</h2></div>
<div id="grid-44-46"><h2>Show - Div Two</h2></div>
<div id="grid-46-48"><h2>Show - Div Three</h2></div>
Use wild card to hide all <div> which id start with grid- on radio change.
$("[id^=grid-]").hide();
$('#input_radio-30-0-des').on('change', function() {
$("[id^=grid-]").hide();
var a = $(this).prop('checked');
if (a) {
$("#grid-40-42").show();
} else {
$("#grid-40-42").hide();
}
});
$('#input_radio-30-1-des').on('change', function() {
$("[id^=grid-]").hide();
var a = $(this).prop('checked');
if (a) {
$("#grid-44-46").show();
} else {
$("#grid-44-46").hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='radio' id='input_radio-30-0-des' name="group1" />
<div id='grid-40-42'>grid-40-42</div>
<input type='radio' id='input_radio-30-1-des' name="group1" />
<div id='grid-44-46'>grid-40-46</div>
Note
No need multi-pal $(document).ready(function(){ .
Id must be unique.
I'm using a Javascript object to match each Radio button with it's targeted div.
I assume they are hidden by default. Just having fun and giving an alternative to multiple checks! A cleaner code also where you could easily setup all those confusing names...
$( document ).ready(function() {
let matches = {
"input_radio-30-0-des": 'grid-40-42',
"input_radio-30-1-des": 'grid-44-46',
"input_radio-30-2-des": 'grid-46-48'
};
$(":input[name='FM']").on("change", function () {
var target= matches[$(this).attr('id')];
$('#' +target).toggle($(this).checked);
$("[id^=grid-]").not('#' +target).hide();
})
});
div[id*='grid-'] { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="FM" id="input_radio-30-0-des" value="0"/>
<label for="input_radio-30-0-des">0</label>
<input type="radio" name="FM" id="input_radio-30-1-des" value="1"/>
<label for="input_radio-30-1-des">1</label>
<input type="radio" name="FM" id="input_radio-30-2-des" value="2"/>
<label for="input_radio-30-2-des">2</label>
<div id="grid-40-42">40-42</div>
<div id="grid-44-46">44-46</div>
<div id="grid-46-48">46-48</div>

How do i check if a specific Radio button is checked among the other radio buttons using Javascript?

I am trying to make javascript check if a specific Radio button is checked among the other radio buttons.
The validation method for checking if any radio button works perfectly:
This is a snippet the HTML code containing the radio buttons:
<form id = "buy" name = "buy" onsubmit = "return valiform()">
<input type="radio" name="Card_type" value="visa" > Visa </input>
<input type="radio" name="Card_type" value="mastercard" > Mastercard</input>
<input type="radio" name="Card_type" value="paypal" > Paypal </input>
<input type="submit" value="Confirm order">
</form>
This is the snippet of the Javascript code regarding the radio buttons:
<script type = "text/javascript">
function valiform(){
var visa = document.buy.Card_type;
var mastercard = document.buy.Card_type;
var paypal = document.buy.Card_type;
var message = "Error!\n";
function validateRadio (radios)
{
for (i = 0; i < radios.length; ++ i)
{
if (radios [i].checked) return true;
}
return false;
}
if(validateRadio (document.buy.Card_type))
{
}
else
{
message+= "Please select card.\n";
}
if(message != "Error!\n"){
alert(message);
return false;
}
}
</script>
So far the code works perfectly, but I want the code to check if specifically the Paypal radio button is selected. I cannot do it without inducing an error. Any ideas how to do it?
First change the paypal line to:
<label><input id="paypalRadio" type="radio" name="Card_type" value="paypal"> Paypal </label>
This use this code which will return true if a given radio button is checked:
document.getElementById('paypalRadio').checked
or you could do this without changing anything:
$("td[name=Card_type]")[2].prop("checked", true)
Instead of returning just true, you could have validateRadio() return the value of the checked button. Then you can assign this to a variable.
var selected = validateRadio(document.buy.Card_type);
if (selected == 'paypal') {
...
}
<input type="radio" name="Card_type" value="visa" > Visa </input> is invalid html; <input> is an empty element , where content is not permitted. You can use .addEventListener(), submit event attached to <form> element, .querySelectorAll(), Array.prototype.some(), check the element at index 2 from result of .querySelectorAll() to determine if input element having value equal to "paypal" is checked
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form id="buy" name="buy">
<input type="radio" name="Card_type" value="visa" />
<input type="radio" name="Card_type" value="mastercard" />
<input type="radio" name="Card_type" value="paypal" />
<input type="submit" value="Confirm order">
</form>
<script type="text/javascript">
function valiform(event) {
event.preventDefault();
var radios = this.querySelectorAll("input[type=radio]")
var message = "Error!\n";
function validateRadio(radios) {
return Array.prototype.some.call(radios, function(input) {
return input.checked
})
}
if (validateRadio(radios)) {
if (radios[2].checked) {
alert(radios[2].value + " radio is checked")
}
event.target.submit();
} else {
message += "Please select card.\n";
}
if (message != "Error!\n") {
alert(message);
return false;
}
}
document.getElementById("buy").addEventListener("submit", valiform)
</script>
</body>
</html>

How can I disable the submit button?

Here is the code How can I disable the submit button. It doesn't appear to be working for us.I want to be able to have the button disabled when the page is brought up. Do you have any ideas on how we can fix this?
// Script 10.5 - pizza.js
// This script creates a master checkbox.
// Function called when the checkbox's value changes.
// Function toggles all the other checkboxes.
function toggleCheckboxes() {
'use strict';
// Get the master checkbox's value:
var status = document.getElementById('toggle').checked;
// Get all the checkboxes:
var boxes = document.querySelectorAll('input[type="checkbox"]');
// Loop through the checkboxes, starting with the second:
for (var i = 1, count = boxes.length; i < count; i++) {
// Update the checked property:
boxes[i].checked = status;
} // End of FOR loop.
}
} // End of toggleCheckboxes() function.
function disabled () {
if ('')
{document.getElementById('submit').disabled = false;}
else
{document.getElementById('submit').disabled = true;}
// Establish functionality on window load:
window.onload = function() {
'use strict';
// Add an event handler to the master checkbox:
document.getElementById('toggle').onchange = toggleCheckboxes;
document.getElementById('submit').disabled = disabled;
};
Here is the html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Operating Systems</title>
<!--[if lt IE 9]>
<script </script>
<![endif]-->
</head>
<body>
<!-- Script 10.4 - pizza.html -->
<form action="#" method="post" id="theForm">
<fieldset><legend>Create Your Own Pizza</legend>
<div><label>Toppings</label> <input type="checkbox" name="toggle" id="toggle" value="toggle"> All/None
<p><input type="checkbox" name="ham" id="ham" value="ham"> Ham
<input type="checkbox" name="mushrooms" id="mushrooms" value="mushrooms"> Mushrooms
<input type="checkbox" name="onions" id="onions" value="onions"> Onions
<input type="checkbox" name="sausage" id="sausage" value="sausage"> Sausage
<input type="checkbox" name="greenPeppers" id="greenPeppers" value="greenPeppers"> Green Peppers </p>
</div>
<input type="checkbox" name="terms" id="terms" required> I agree to the terms, whatever they are.
<input type="submit" name="submit" value="Submit" id="submit">
</fieldset>
<div id="output"></div>
</form>
<script src="js/utilities.js"></script>
<script src="js/pizza.js"></script>
<script src="js/modal.js"></script>
</body>
</html>
There are a few things that could be improved:
You should close all your input tags to avoid any issues rendering the HTML document.
The for-loop should run until i < (boxes.length - 1) to avoid selecting the ToS checkbox. Or you could target just the toppings with querySelectorAll('p input[type="checkbox"]') and start from var i = 0.
The closing bracket for disable() is between the closing brackets for the for-loop andtoggleCheckboxes().
In disabled() #terms is selected, you want to check if it is checked or not. If it is, enable the submit button (disabled = false), else disable it (disabled = true).
Finally, you'll want to assign disabled() to the #terms' onclick function so it is called every time the checkbox is toggled.
Demo: http://jsfiddle.net/4Rwfs/1
HTML
<form action="#" method="post" id="theForm">
<fieldset>
<legend>Create Your Own Pizza</legend>
<div>
<label>Toppings</label>
<input type="checkbox" name="toggle" id="toggle" value="toggle">All/None</input>
<p>
<input type="checkbox" name="ham" id="ham" value="ham">Ham</input>
<input type="checkbox" name="mushrooms" id="mushrooms" value="mushrooms">Mushrooms</input>
<input type="checkbox" name="onions" id="onions" value="onions">Onions</input>
<input type="checkbox" name="sausage" id="sausage" value="sausage">Sausage</input>
<input type="checkbox" name="greenPeppers" id="greenPeppers" value="greenPeppers">Green Peppers</input>
</p>
</div>
<input type="checkbox" name="terms" id="terms" required> I agree to the terms, whatever they are.</input>
<input type="submit" name="submit" value="Submit" id="submit"></input>
</fieldset>
<div id="output"></div>
</form>
JavaScript
// Script 10.5 - pizza.js
// This script creates a master checkbox.
// Function called when the checkbox's value changes.
// Function toggles all the other checkboxes.
function toggleCheckboxes() {
'use strict';
// Get the master checkbox's value:
var status = document.getElementById('toggle').checked;
// Get all the checkboxes:
var boxes = document.querySelectorAll('p input[type="checkbox"]');
// Loop through the checkboxes, starting with the second:
for (var i = 0, count = boxes.length; i < count; i++) {
// Update the checked property:
boxes[i].checked = status;
} // End of FOR loop.
} // End of toggleCheckboxes() function.
function disabled () {
if (document.getElementById('terms').checked)
{document.getElementById('submit').disabled = false;}
else
{document.getElementById('submit').disabled = true;}
}
// Establish functionality on window load:
window.onload = function() {
'use strict';
// Add an event handler to the master checkbox:
document.getElementById('toggle').onchange = toggleCheckboxes;
document.getElementById('submit').disabled = true;
document.getElementById('terms').onchange = disabled;
};
If you want to disable the submit button on page load, try adding this:
document.getElementById('submit').disabled = true;
The following line doesn't make sense unless the disabled function returns a boolean:
document.getElementById('submit').disabled = disabled;
For example, this would work if you wanted the submit button to disable on click.
document.getElementById('submit').onclick = disabled;
The problem is not in the disable line.
What did you trying to do with if('') { ? Also, in your onload function, there is a line :
'use strict';
What are you trying to do again?
See : http://jsfiddle.net/ByKEJ/
How to disable html button using JavaScript?
I think this previous solution can help you dynamically disable something

Categories

Resources