jQuery - target second radiobutton only when first is checked - javascript

I have a set of yes/no radio buttons. I would like a modal window to open when the user clicks an unchecked 'no' radio button only if the yes radio button IS already checked. There is a state where none of the buttons will be checked and in this case I don't want the modal to appear.
My problem is I am showing this modal in a click event on the 'no' button. I have no way to tell if 'yes' was previously checked, since in this scope, we know 'no' is checked because we're inside of the click event for it. Any suggestions?
<span class="yesRadioButton" data-questionnumber="1">
<input id="MHQPreQuestion1_rbQuestAnswerYes" name="YesNo" type="radio"value="Yes" checked="checked">
</span>
<span class="noRadioButton" data-questionnumber="1">
<input id="MHQPreQuestion1_rbQuestAnswerNo" name="YesNo" type="radio"value="No">
</span>
$('.noRadioButton > input:radio:not(:checked)').click(function () {
DialogOpen();
});

You can set an attribute on the "yes" input when you click it, so you know if it has been previously set. Then you can grab the first input through jQuery and check its value before deciding whether you want to have the popup appear inside of the "no" click handler:
$('.noRadioButton > input').click(function() {
var yesButton = $('.yesRadioButton > input');
var yesValue = yesButton.attr('wasChecked');
if (yesValue === "true") {
//do your popup
}
yesButton.attr('wasChecked', false);
});
$('.yesRadioButton > input').click(function() {
$(this).attr('wasChecked', true);
});
Example here
edit: updated to work with radio buttons, i was thinking check boxes

Related

Radio Button client click event used to show or hide modal popup not setting the modal property correctly

I have 2 radio buttons on an ASP.NET WebForm page. I have a modal popup that is to be shown only when going from one of the radio buttons to the other, but not the other way. In other words, here are my choices:
if radio button 1 is clicked then the modal popup is shown.
If radio button 1 is currently selected and radio button 2 is clicked then the modal popup should NOT be shown.
I have a javascript function that toggles the show and hide but I briefly see the popup when #2 logic is performed. Here is the js function:
$(function () {
$('#<%=RadioButtonListServiceLevel.ClientID%>').click(function () {
var CustomerCountry = $('#<%=HiddenFieldCustomerCountry.ClientID%>').val();
var ServiceLevelSelected = $("#<%=RadioButtonListServiceLevel.ClientID%> input:checked").val();
if ((CustomerCountry != "US" && CustomerCountry != "CA") && ServiceLevelSelected == "24") {
$('#InternationalServiceLevelModal').modal('show');
} else {
$('#InternationalServiceLevelModal').modal('hide');
}
});
});
Any idea why the popup modal dialog would briefly show when the action described in #2 is performed?
Thanks
I was just playing around a bit using an 'alert' and when I used the 'click' event, like you have, the alert fired twice: as soon as i clicked - before the button visibly changed value, then again after the button visibly changed value.
I changed 'click' to 'change' and the alert only fired once. Could be the fix?
// changed 'click' to 'change'
$('#<%=RadioButtonListServiceLevel.ClientID%>').change(function () {

Uncheck a radio button after clicking on it again

I am looking for a way to uncheck a radio button after clicking on it again.
For example, when i click for the first time it gets checked, but I want that after clicking on it again, it gets unchecked
I tried the following How to reset/uncheck radio button onclick event?
But it does not work
Can someone help me out? thanks
<input id="button1" type="radio" name="optradio"></input>
<script>
window.onload=function(){
toggle0=1;
btn0=document.getElementById("button1");
btn0.addEventListener("click", function(e){
if(toggle0==0){
toggle0=1
btn0.checked=false;
}else{
toggle0=0;
btn0.checked=true;
}
});
}
</script>

Uncheck a checked radio on click

I want to create a radio button that can have an unchecked value. So I created the code:
$('form').on('click', 'input[type="radio"]:checked', function (event) {
$(this).prop("checked", false);
});
Well, this is pretty straightforward: click on a checked radio, uncheck it.
But, what happens is that it never checks the radio in the first place. When I click an unchecked radio it checks before detecting if is checked, then considers it checked and unchecks it.
Well, this is not a duplicate as it asks a different question. It's not about how to uncheck, but how to automatically uncheck upon clicking.
How can I go around this problem?
You can solve your issue like following.
$('form :radio').attr('data-ischecked', function() {
return this.checked;
}); //set initial status in data-ischecked attribute
$('form').on('click', ':radio', function () {
var status = $(this).data('ischecked'); //get status
status && $(this).prop("checked", false); //uncheck if checked
$(this).data('ischecked', !status); //toggle status
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio"/>
<input type="radio"/>
</form>
Your example only executes when the button is clicked. To have the radio button be checked when the page loads, I would put a $(document).onload() event that sets the button's value to checked.

prevent immediate Radio :checked property on click event

I have a click event handler attached to a group of radio inputs, and want to see if I am clicking on the radio button that is already selected (has property 'checked' set). I figured the event handler would act in a daisy chained fashion (first calling my event handler on the click and then continuing down the chain to the default behavior of the click). Apparently this is not the case, because when I evaluate if the property 'checked' is true on the radio button I just clicked, it always returns true in my click event handler.
The click has already been processed by the default behavior and has already applied the 'checked' property to the radio button I just clicked. Again, I figured my click event handler would be processed prior to that default behavior. What's even more odd is that even when I prevent the default behavior, it still returns true for the 'checked' property. I assume this is because the 'checked' property is being processed by the 'change' event, so preventing the default behavior on my click event handler is not affecting anything.
$("input[type='radio']").click(function(e) {
e.preventDefault();
alert($(this).prop("checked")); // always returns true; i want prop value immediately prior to click
});
How can I achieve what I'm after? That is, to see whether or not the radio button that was just clicked on was the one already checked. Thanks.
Based on the response of #Jeffman , I was able to get something to work for what I needed to do. I have custom buttons, only one of which can be selected (hence the use of radio buttons). However, if you click on the one that's already selected, it should deselect and select the default value instead.
Things I had to do. Handle mousedown events on the radio labels. If I am clicking on the already selected radio, set the default button to be 'checked'. Else I just select the button that has been clicked on. I had to disable the 'click' event on these buttons, as that would override my irregular handling of the radio buttons (for some reason the selection would snap back to the one that was clicked when I overrode it and chose the default one manually). This also meant I would need to manually trigger the change event, as I do the custom radio button styling there.
$(".radios > label").mousedown(function(e) {
var l = $(this); // label
var t = l.parent(); // container for radio group
var i = l.find("input"); // input element of this label
if(i.prop("checked")) { // clicking on the already selected button
t.find(".default_radio input").prop("checked", true).trigger("change");
} else {
i.prop("checked", true).trigger("change");
}
}).bind('click',false);
$("input[type='radio']").change(function(e) {
// style the buttons here
});
Save radio status before click via mousedown
var was_checked;
$( "#radio" ).mousedown(function() {
was_checked = $(this)[0].checked;
});
$( "#radio" ).click(function() {
$(this).attr('checked', !was_checked);
});
i think you should also return false. not only preventDefault
Here is a sample code that would do the trick
<script>
$(function() {
var radios = {};
$("input[type='radio']").each(function() {
radios[$(this).uniqueId().attr('id')] = false;
});
function resetRadioState() {
$("input[type='radio']").each(function() {
radios[$(this).attr('id')] = $(this).is(':checked');
});
}
resetRadioState();
$("input[type='radio']").click(function(e) {
alert(radios[$(this).attr('id')]);
resetRadioState();
});
})
</script>
<input type="radio" name="group[]"/>
<input type="radio" name="group[]" checked/>

Radio button group - change events for buttons become deselected?

Let's say I have a group of two radio buttons:
<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>
It seems that clicking the second button triggers an event handler on that button only. However, the first button does become deselected, and visually does change. Can anyone verify that events are fired only on the button that was selected, and not any of the other buttons in the group which become deselected as a result of the click? Any clever ways to watch a radio button for a deselecting event?
Although it cannot be confirmed, but the event change triggers don't happen on the entire group.
If you want that to happen, you can do it using various JS libraries like jQuery, YUI, etc. or even plain javascript, as follows:
function buttonGroupChange(){
var radioElements = document.getElementsByName("radio_group_name");
for(var i = 0; i < radioElements.length; i++){
if(radioElements[i].checked == true){
//do something
}
else{
//do something
}
}
}
This function can be called on the onClick or the onChange event.
I hope that solves your problem.
Firstly, it is important to note that a "Click" event on any of the radios fires AFTER the "checked" value is already updated. This is important - because it means you can't detect the previous item once the event is already fired. If you Cancel the event, you are actually changing the value BACK - not stopping it initially. This is important to how you approach the problem.
Example:
<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>
// At this point, the ':checked' item is button1.
$('input[type=radio]').bind('click', function (ev) {
// If you click on button2 - by this point, the ':checked' item is already button2.
ev.preventDefault(); // These two lines will stop the radio from actually
ev.stopPropagation(); // changing selection.
// At this point, the ':checked' item is set BACK to button1.
});
Because of this, the easiest solution is to track the "last" selected item in a closure alongside your event handlers, as follows:
<input type="radio" name="radioButtonGroup" value="button1" checked="true"/>
<input type="radio" name="radioButtonGroup" value="button2"/>
<script type="text/javascript">
var $last = $('[name=radioButtonGroup]:checked');
// Select the radio buttons as a group.
var $radios = $('[name=radioButtonGroup]').bind('change', function (ev) {
// Click event handler
var $clicked = $(ev.target); // This is the radio that just got clicked.
$last.trigger('unclick'); // Fire the "unclick" event on the Last radio.
$last = $('[name=radioButtonGroup]:checked'); // Update the $last item.
// Should see the clicked item's "Value" property.
console.log("Clicked " + $clicked.attr('value'), $clicked, ev);
}).bind('unclick', function (ev) {
// Handler for our new "unclick" event.
// - fires whenever a radio loses focus.
var $unclicked = $(ev.target); // The radio losing it's checked status.
// Should see the unclicked item's "Value" property.
console.log("Unclicked " + $unclicked.attr('value'), $unclicked, ev);
});
</script>
For a working example, see:
http://jsfiddle.net/TroyAlford/wvrtC/
I can't confirm that an event is only fired for the selected button, but if you needed to do something with the button that was just deselected, the following would work:
$(document).ready(function(){
var selectedRadio = null;
$("input:radio").change(function(){
if(selectedRadio != null){
alert(selectedRadio.val());
}
selectedRadio = $(this);
});
});
In action here.
If you need to keep track of multiple groups of radio buttons, you could do it with an array of currently selected buttons and match within that array when a change is detected.
The simple nature of the radio button set is that only one button can be selected at a time. Selecting a button automatically means the others are not selected, but there is no specific action for deselecting. Therefore, you only need to worry about the one event, because it affects all the buttons in the set at one time.
If you would like to use an element that allows for multiple selections try checkboxes.

Categories

Resources