Make radio buttons checked /unchecked - javascript

$("input[type='radio']").each(function() {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">
My approach is to first check if my inputs are :checked and if they are, put some CSS class with the background color. I achieve that, the next thing I want to is to remove that :checked when users click on radio button or any other (better) idea. After the form is submitted, this code checks if inputs are:checked, the problem is when I want to select another radio button I get something like this:
1 and 2 radio buttons are selected, it should be only 2 :checked

You need to add the else to remove the blue color like :
$("input[type='radio']").each(function () {
if ($(this).is(":checked")) {
$(this).css('background', 'blue');
}else{
$(this).css('background', 'white');
}
});
You could also attach a click event for those radios like :
$("body").on("click", "input[type='radio']", function () {
$("input[type='radio']").css('background', 'white');
$(this).css('background', 'blue');
});

The issue with your JS is that you never remove the class from any of the unselected checkboxes. Also note that each() only runs when the page loads (assuming you've not placed it in an event handler, but the question doesn't show that), so you need to instead run your logic in a change event handler:
var $radio = $("input[type='radio']").on('change', function() {
$radio.removeClass('blue');
$(this).toggleClass('blue', this.checked);
});
That being said, what you're trying to do can be achieved more simply by using CSS:
input {
visibility: hidden;
}
input:before {
content: '';
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: #CCC;
visibility: visible;
}
input:checked:before {
background-color: blue;
}
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">

I think the issue with your code is that you are using each event instead of change or click event. It means that you are trying to change the color of your radio button, even before user has performed any action. Read the following code, this will solve the issue of submitting the form and also customizing the radio button:
$(".radio-button").click(function() {
$(this).addClass("blue-background");
$(this).siblings().removeClass("blue-background");
var radioID = $(this).data('radio');
$('#' + radioID).attr("checked", "checked");
if ($('#' + radioID).siblings(":checked")) {
$('#' + radioID).siblings().removeAttr("checked");
}
});
.blue-background {
background-color: blue;
}
input[type='radio'] {
visibility: hidden;
}
.radio-button {
height: 15px;
width: 15px;
margin: 5px;
border-radius: 50%;
display: inline-block;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<input type="radio" id="radio1" data="cool" name="cool" checked="checked">
<input type="radio" id="radio2" data="cool" name="cool">
<input type="radio" id="radio3" data="cool" name="cool">
<div class="radio-button" data-radio="radio1"></div>
<div class="radio-button" data-radio="radio2"></div>
<div class="radio-button" data-radio="radio3"></div>
</div>
I hope this was helpful.

Related

MySQLi - JS - drop down multi select

beginner here.
Made a drop down where you can select 3 options that i would have placed in my 3 place holders in my database.
In other words, i have 3 attribute records "at1. at2, at3" and a drop down of attributes, like "Red, Blue, Black, Orange, Green" (in the code below, for the moment i just labeled them "one, two, three") that i want placed into at1, at2, at3.
So.. so far i have..
$at0 = $_POST['at0'];
$at1 = $_POST['at1'];
$at2 = $_POST['at2'];
And
<style>
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
</style>
Attributes:
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Select an option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<input type="checkbox" name="at0" id="one" /> one
<label for="two"><input type="checkbox" name="two" id="two" />two
<label for="three"><input type="checkbox" name="three" id="three" />three
</div>
</div>
<script>
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
</script>
Is there an easier/cleaner way to have a user select multiple options which all get put in my database?
At the moment it kind of works, when i click on the first checkbox, the word "On" is left in 'at1' in my database.. How do i get what i want to achieve?
As specified in https://developer.mozilla.org/es/docs/Web/HTML/Elemento/input/checkbox
The input checkbox will pass the default "on" if checked.
You can pass a custom value using:
<input type="checkbox" name="at0" id="one" value="mycustomvalue" />
That will make the POST or GET (depending on your form) var "at0" to receive the value "mycustomvalue" if the checkbox is checked.
EDIT:
If you want multiple checkboxes that may or not be checked you can use the array syntax for the name. That is:
HTML:
<input type="checkbox" name="at0[]" id="one" value="valueone" />
<input type="checkbox" name="at0[]" id="two" value="valuetwo" />
<input type="checkbox" name="at0[]" id="three" value="valuethree" />
<input type="checkbox" name="at0[]" id="four" value="valuefour" />
If you check boxes 1 and 3, the PHP part will be
PHP:
echo $_POST["at0"][0]; // will echo "valueone";
echo $_POST["at0"][1]; // will echo "valuethree";
Then it's matter of you how you save that into the DB. Just remember to sanitize your inputs to avoid SQL Injection Attacks

Need help to optimze a code for radio button

$('input[type="radio"]').change(function(){
if ($('#subscribe').is(':checked')){
$("#subNow").show();
$('#oneTime').hide();
}
if ($('#one-time').is(':checked')){
$('#oneTime').show();
$("#subNow").hide();
}
});
The above code is to show and hide 2 div's on click of 2 radio buttons. I am new to jquery so would like to know is there a better way to write this same functionality.
If you setup the initial state, say #subNow { display: none; }, then just use the .toggle() method, no conditions check what-so-ever...
$('input[type="radio"]').change(function(){
$("#subNow").toggle();
$('#oneTime').toggle();
});
#subNow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type='radio' name='rd' checked />1
<input type='radio' name='rd' />2
<br />
<div id="subNow">subNow</div>
<div id="oneTime">oneTime</div>
Also,
if perhaps they are followed on the markup, why not drop JS and go CSS-only??
input[type="radio"]:nth-child(2):checked ~ #oneTime,
#subNow
{
display: none;
}
input[type="radio"]:nth-child(2):checked ~ #subNow{
display: block;
}
<input type='radio' name='rd' checked />1
<input type='radio' name='rd' />2
<br />
<div id="subNow">subNow</div>
<div id="oneTime">oneTime</div>
This is exactly the way I would do this. The only other option would be to get the value of the radio buttons, but you'd essentially be doing the same thing that you already are.
One way is to use common classes and data attributes
$(".rads").on("change", '[type="radio"]', function (e) {
var show = $(this).data("show");
$(".details").hide().filter(show).show();
});
.details {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="rads">
<input type="radio" id="x" name="rad" data-show=".foo" />
<label for="x">A</label>
<input type="radio" id="y" name="rad" data-show=".bar" />
<label for="y">B</label>
</div>
<div class="foo details">Apple</div>
<div class="bar details">Bacon</div>
There is also pure CSS solutions using the :checked selector.
If you don't have any other states to worry about, you can cut the second if and place a else
$('input[type="radio"]').change(function(){
if ($('#subscribe').is(':checked')){
$("#subNow").show();
$('#oneTime').hide();
}
else{
$('#oneTime').show();
$("#subNow").hide();
}
});
You can also use switch

Change css of class when select radio button

I have a image with the css class .normalImage
I made 3 radio buttons and when the user select 1 of the radio buttons the style of the image must change to .blackImage or .sepiaImage
I have 3 radio buttons, each must activate a new style to the image :
<input type="radio" name="color" value="grijs">Black<br>
<input type="radio" name="color" value="sepia">Sepia<br>
<input type="radio" name="color" value="normal">Normaal<br>
How can i change the style of the image when someone checks one of the radio buttons?
You can use .addClass() method
Try this :
$('input[type=radio]').change(function() {
$("img").removeClass();
if($(this).val() == "grijs"){
$('img').addClass('blackImage');
}
else if($(this).val() == "sepia"){
$('img').addClass('sepiaImage');
}
else if($(this).val() == "normal"){
$('img').addClass('normalImage');
}
});
Working Example
Is that what you are looking for?
$('input[name=color]').on('click', function() {
$('#my-image').removeClass().addClass( $(this).val()+"Image" );
});
you can add a click function with parameter off the css class.
function setCssClass(className){
$("#IMAGE_ID").addClass(className);
}
<input type="radio" name="color" value="grijsImage" onclick="setCssClass('grijs');">Black<br>
<input type="radio" name="color" value="sepiaImage" onclick="setCssClass('sepiaImage');">Sepia<br>
<input type="radio" name="color" value="normal"onclick="setCssClass('normal');">Normaal<br>
You can use, addClass()
<script type="text/javascript">
if ("input[type='radio']")
{
$(this).addClass("newclass");
}
</script>
if you wish to remove the previous class then you can use:
if ("input[type='radio']")
{
$(this).removeClass().addClass("newclass");
}
I think you need to handle radio button .change() event and check for selected and deselected. After that use .removeClass() and .addClass() methods.
DEMO
jQuery:
var $img = $("#myImage");
$('input[name=color]').on('change', function() {
$img.removeClass().addClass($(this).val());
});
HTML:
<p id="myImage">Text instead of an image</p>
<input type="radio" name="color" value="grijs">Black<br>
<input type="radio" name="color" value="sepia">Sepia<br>
<input type="radio" name="color" value="normal">Normaal<br>
CSS:
.grijs {
color: red;
}
.sepia {
color: blue;
}
.normal {
color: green;
}
There is a better way to change the class; rather than removing then adding a new class, you could use the jQuery switchClass() function.
Like this:
var $img = $("#myImage");
$('input[name=color]').on('change', function()
{
$img.switchClass($img.attr('class'), $(this).val());
});

Toggle a button to be viewed after a checkbox has been checked, and disappear if unchecked

Below I have code for a specific application that I am building with PHP. My job is User interface, and I have looked and looked for code on how to make this work.
With this form, it's using the latest update of Jquery UI to styalize the buttons and checkboxes. I need for the button to appear when a check box has been checked, and disappear when unchecked.
Haven't been able to find any code that works for this, and is driving me half insane, and lagging me behind.
<form name="purpose" method="post" action="" >
<div id="radiosetPURPOSE">
<input type="checkbox" id="radio1" name="homework" value="homework" ><label for="radio1" style="font-size: 13pt; width: 130px; height: 40px;">Homework</label>
<input type="checkbox" id="radio2" name="computer" value="computer" ><label for="radio2" style="font-size: 13pt; width: 130px; height: 40px;">Computer</label>
</div>
<br />
<div id="radiosetPURPOSE2">
<input type="checkbox" id="radio3" name="books" value="books" ><label for="radio3" style="font-size: 13pt; width: 130px; height: 40px;">Books</label>
<input type="checkbox" id="radio4" name="reading" value="reading" ><label for="radio4" style="font-size: 13pt; width: 130px; height: 40px;">Reading</label>
</div>
<br />
<div id="radiosetPURPOSE3">
<input type="checkbox" id="radio5" name="tutoring" value="tutoring" ><label for="radio5" style="font-size: 13pt; width: 130px; height: 40px;">Tutoring</label>
</div>
<br /><br /><br /><br />
<div id="btnCheckin" style="display:none">
<button id="btnCheckinBtn" style="font-size: 18pt; width: 175px; height: 75px;">Check In</button>
</div>
</form>
IF I read your requirements properly, you need to check if ANY of the checkboxes are check to show the button, and if ALL are unchecked, hide it?
This can occur on a click or on a keyboard action so you need to check the change event for that. Wrap this up in a document ready handler, include jQuery and you are set.
$('input:checkbox').change(function () {
if ($('input[type=checkbox]:checked').length > 0) {
$('#btnCheckin').show();
} else {
$('#btnCheckin').hide();
}
});
Here is a fiddle with your markup:http://jsfiddle.net/GGdtw/
Seems I misread your question, and you want the button enabled when any checkbox is checked.
This will look and see if any checkboxes are ticked, within the form with name purpose.
$("input:checkbox").change(function() {
$("#btnCheckin").toggle(!!$('form[name="purpose"] > input:checkbox:checked').length))
});
You can also use jQuery '.toggle()':
http://api.jquery.com/toggle/
When you click the checkbox, check to see if it is checked or unchecked, and based on that, enable or disable the button. (Using jQuery)
<script>
$(document).ready(function() {
$("#checkbox").click(function() {
if (("#checkbox").is(":checked")) {
//button show (.show())
else {
//disable the button (.hide())
}
});
});
</script>
Also, get rid of the "display: none;" in the button style.
Fiddle: http://jsfiddle.net/mbYby/

jQuery Custom Radio Buttons not working as radio buttons

I am using JQuery and custom images for custom radio buttons. Right now, it would work as a checkbox. I need it to work as a radio.
When I click on either of both radio's both will get ticked instead of one at a time. Am I missing something?
HTML:
<label for="radio1">
<img src="radio_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio1" style="display:none;">
</label>
<label for="radio2">
<img src="radio_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio2" style="display:none;">
</label>
JavaScript:
$(document).ready(function() {
$("#radio1").change(function() {
if (this.checked) {
$(this).prev().attr("src", "radio_checked.png");
} else {
$(this).prev().attr("src", "radio_unchecked.png");
}
});
$("#radio2").change(function() {
if (this.checked) {
$(this).prev().attr("src", "radio_checked.png");
} else {
$(this).prev().attr("src", "radio_unchecked.png");
}
});
});
The radio buttons are working correctly (proof), but your logic for updating the images is incorrect. Both images have to change when either radio button is clicked, since both values change (and the change handler is only fired on the one that you clicked). Have a single change handler used by both radio buttons, and set both images on every change, e.g.:
$('#radio1, #radio2').change(function() {
var r;
r = $("#radio1");
r.prev().attr("src", r[0].checked ? checkedImage : uncheckedImage);
r = $("#radio2");
r.prev().attr("src", r[0].checked ? checkedImage : uncheckedImage);
});
Live example
Side note: If your target browsers support the :checked pseudo-class (IE only has this as of IE9, not in IE8 or earlier) and adjacent sibling combinator from CSS3, you can do this entirely with CSS:
HTML:
<input type="radio" name="radiogroup" id="radio1" style="display: none">
<label for="radio1"></label>
<input type="radio" name="radiogroup" id="radio2" style="display: none">
<label for="radio2"></label>
CSS:
#radio1 + label, #radio2 + label {
display: inline-block;
background-image: url(radio_unchecked.png);
width: 32px; /* Whatever matches the images */
height: 32px; /* Whatever matches the images */
}
#radio1:checked + label, #radio2:checked + label {
background-image: url(radio_checked.png);
}
Live example
Or alternately (it's just the selectors that are different):
input[name="radiogroup"] + label {
display: inline-block;
background-image: url(radio_unchecked.png);
width: 32px; /* Whatever matches the images */
height: 32px; /* Whatever matches the images */
}
input[name="radiogroup"]:checked + label {
background-image: url(radio_checked.png);
}
The change event fires only for the radio button that was changed by the user, not for any other radio buttons that may be automatically unchecked in that process.
You should update all of the images when the change event for any radio button fires:
var radios = $('input:radio');
radios.change(function() {
radios.filter(':checked').prev().attr("src", "radio_checked.png");
radios.filter(':not(:checked)').prev().attr("src", "radio_unchecked.png");
});
This will work for any number of radio buttons. A reference to the original collection of radio inputs is kept in radios (this is more efficient). When any of the <label>s is clicked, the event handler fires. Inside the handler, filter() is used to separate the radios collection into checked and the unchecked radio inputs.
Working demo: http://jsbin.com/ibaqid/2/edit#javascript,live
This should work:
<label for="radio1">
<img src="radio_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio1" style="display:none;">
</label>
<label for="radio2">
<img src="radio_unchecked.png" style="vertical-align:middle" />
<input name="radiogroup" type="radio" id="radio2" style="display:none;">
</label>
<script>
$(document).ready(function(){
$("input[name=radiogroup]").change(function() {
$("input[name=radiogroup]").prev().attr("src", "radio_unchecked.png");
$(this).prev().attr("src", "radio_checked.png");
});
});
</script>
Try replacing:
this.checked
with this:
$(this).is(':checked')

Categories

Resources