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')
Related
$("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.
I have an checkbox "Cut image" which will on select expand four more check-boxes (up, left, right, down) where you can select where image will be cut.
By default, these expanded check-boxes are selected.
What I want to achieve is:
If "cut image" checkbox is selected (and by default all other expanded check-boxes) append text value "Cut image: up, left, right, down" to textarea
If one of the expanded check-boxes are not selected (lets say "up"), remove it's value from appended text in textarea, and show only selected ones, "Cut image: left, right, down"
Html
<input type="checkbox" id="cut-image">
<label for="">Cut image</label>
<div id="main-group">
<input type="checkbox" class="cut-image-up" checked>
<label for="">up</label>
<input type="checkbox" class="cut-image-left" checked>
<label for="">left</label>
<input type="checkbox" class="cut-image-right" checked>
<label for="">right</label>
<input type="checkbox" class="cut-image-down" checked>
<label for="">down</label>
</div>
<textarea name="" id="checkbox-values" cols="20" rows="10"></textarea>
Javascript
$(function(){
$('#cut-image').on('change', function(){
$('#main-group').toggle();
if($(this).is(':checked')){
$('#checkbox-values').val('Cut image (up, left, right, down)');
}else{
$('#checkbox-values').val('');
}
});
})
Here is an jsfiddle also.
I would appreciate any suggestions on how to achieve this behavior.
Thanks.
There are always about a billion ways to do things like this. It seems to me like you need a couple of things:
A way to associate each checkbox with its direction
Something that listens for changes in the checkboxes -- as they are checked and unchecked
Every time a checkbox is changed, we grab all the checked checkboxes, and reattach the directions to the textbox
Here's an updated version. Note the slightly different HTML...
$(function() {
$('#cut-image').on('change', function() {
$('#main-group').toggle();
if ($(this).is(':checked')) {
setCheckboxValues();
} else {
$('#checkbox-values').val('');
}
$('.cut-image').on('change', function() {
setCheckboxValues()
})
});
})
function setCheckboxValues() {
const allCheckedText = $('input.cut-image:checked').map(function() {
return this.value;
}).get()
$('#checkbox-values').val(`Cut image (${allCheckedText.join(', ')})`);
}
#cut-image,
#main-group,
#checkbox-values {
display: block;
margin: 10px 0;
}
#main-group {
display: none;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cut-image">
<label for="">Cut image</label>
<div id="main-group">
<input type="checkbox" class="cut-image" checked value="up">
<label for="">up</label>
<input type="checkbox" class="cut-image" checked value="left">
<label for="">left</label>
<input type="checkbox" class="cut-image" checked value="right">
<label for="">right</label>
<input type="checkbox" class="cut-image" checked value="down">
<label for="">down</label>
</div>
<textarea name="" id="checkbox-values" cols="20" rows="10"></textarea>
This won't completely take care of all the various scenarios but will give you a good start point
Add values to the checkboxes and build array of those values using jQuery map(). Then join() those array values to add to the text
<input type="checkbox" class="cut-image-up" value="up" checked>
JS
$('#cut-image').on('change', function() {
$('#main-group').toggle();
if ($(this).is(':checked')) {
// array of checked checkbox values
var directions = $('#main-group :checkbox:checked').map(function() {
return this.value
}).get().join(', ');
$('#checkbox-values').val('Cut image (' + directions + ')');
} else {
$('#checkbox-values').val('');
}
});
DEMO
$('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
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());
});
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/