How to check value of radio button before click with jQuery - javascript

I have two check boxes on a page, with one checked by default. I want to use jQuery to trigger a custom event when either of the check boxes is clicked. However, the problem is I want to get the checked value before the click event, but I keep getting checked as true.
My HTML looks like this:
<div class="clearfix controls">
<label class="radio inline" for="yes">
<input type="radio" name="recycle" value="1" id="yes" data-price-increase="29">
Yes
</label>
<label class="radio inline" for="no">
<input type="radio" name="recycle" value="0" id="no" checked="checked" data-price-decrease="29">
No
</label>
</div>
And my JavaScript looks like this:
$('[data-price-increase]').on('click', function(e) {
$('body').trigger('price.increase', [ $(this).data('price-increase') ]);
});
$('[data-price-decrease]').on('click', function(e) {
$('body').trigger('price.decrease', [ $(this).data('price-decrease') ]);
});
But the click handlers get fired multiple times if I continually click a radio button, even if it’s already checked.
The radio buttons add or remove an additional charge respectively, so continually clicking the “Yes” radio button continually adds the charge to the price, which is undesired. If “Yes” is already checked then I don’t want the value adding again.

I think you look for change event:
$('[data-price-increase]').on('change', function(e) {
console.log('changed');
$('body').trigger('price.increase', [ $(this).data('price-increase') ]);
});
$('[data-price-decrease]').on('change', function(e) {
console.log('changed');
$('body').trigger('price.decrease', [ $(this).data('price-decrease') ]);
});
So action is only triggered in case check is changed, not on each click.

ask the target if it´s checked
$('[data-price-increase]').on('click', function(e) {
if(!jQuery(event.target).is(":checked"))
$('body').trigger('price.increase', [ $(this).data('price-increase') ]);
});

Related

KnockoutJS - Correct Way of Writing KO BindingHandlers for Input Type Radio

I have set a custom binding for input type radio, which is like this:
"radio-yesno": function(bindingContext, dataClasses){
return {
click: this,
}
},
The Html Input Type Radio binds to this is written like this:
<label class="radio inline">
<input type="radio" name="RadioTest" id="RadioYes" data-class="radio-yesno"/>
Yes
</label>
<label class="radio inline">
<input type="radio" name="RadioTest" id="RadioNo" data-class="radio-yesno"/>
No
</label>
(You may notice that I am using data-class here to bind the element, it is because I am using the ClassBindingProvider plugin)
The problem now is when the radio button is clicked, the function which contains the associated observable of this element is actually triggered and during debugging it can be seen that the value of
$('#RadioNo').is(':checked')
is actually true when the No Radio Button is clicked and is false when the Yes Radio Button is clicked. BUT, the page itself doesn't show the Radio Button to be selected (checked).
Currently the ko BindingHandlers that I am using here is "click" only.
I have tried to add more bindingHandler which is "checked: this" and put it below the "click: this" line, but still doesn't work.
Could someone please help me to identify what is the problem here and how should it be fixed?
Thanks.
It's not clear from your question exactly what you want the behavior to be, but I've put together a snippet with typical radio button behavior. The most important change is that I added a value attribute to each radio button element. Without them, there's no value change on selecting a different radio button.
I have written but commented out a click binding here, and am using a checked binding, which is usually the better way to bind a radio group. I subscribe to the bound variable just to output information when it changes.
let bindings = {
"radio-yesno": function(bindingContext, dataClasses) {
return {
// click: this.clickHandler,
checked: this.checkedVariable
}
}
};
ko.bindingProvider.instance = new ko.classBindingProvider(bindings);
let vm = {
clickHandler: function(data, event) {
console.debug("Click:", data, event);
true;
},
checkedVariable: ko.observable('on')
};
vm.checkedVariable.subscribe((newValue) => {
console.debug('New value:', newValue);
});
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="//rawgit.com/rniemeyer/knockout-classBindingProvider/master/src/knockout-classBindingProvider.js"></script>
<label class="radio inline">
<input type="radio" name="RadioTest" value="on" data-class="radio-yesno" />Yes
</label>
<label class="radio inline">
<input type="radio" name="RadioTest" value="off" data-class="radio-yesno" />No
</label>

Unchecking a radio box without use of id's

I'm setting up a table, where each row will contain several radio boxes. There are certain conditions for the radio boxes, for example:
If "Home" is checked, the "Text" radio box will be unchecked and "Voice" will be checked instead (ie. You can't text a home phone number). Similarly, when "Home" and "Voice" are checked, clicking "Text" will force "Home" to be unchecked and "Cell" will become checked.
I can get this working fine for one instance, with the use of .getElementById and the click function, but where I run into trouble is when things are scaled up. This table might have 20 or 30 rows, each of which containing a cell with these radio boxes.
I'm not great with jQuery, so I'm not sure how to make a more general version, so that each set of radio boxes are their own contained units, so to speak. I made a jsfiddle where you can see that only the first instance is working, likely because I am targeting the boxes using their id and you can't have two elements with the same id... help? Thanks!
http://jsfiddle.net/3uHqS/
Script
$( document ).ready(function() {
document.getElementById('contact-home').onclick = function () {
document.getElementById('format-voice').checked = true;
};
document.getElementById('format-text').onclick = function () {
document.getElementById('contact-cell').checked = true;
};
});
HTML
<form>
<input type="radio" name="contact" value="" id="contact-cell" />
<label for="contact-cell">Cell</label>
<input type="radio" name="contact" value="" id="contact-home" />
<label for="contact-home">Home</label>
<input type="radio" name="format" value="" id="format-voice" />
<label for="format-voice">Voice</label>
<input type="radio" name="format" value="" id="format-text" />
<label for="format-text">Text</label>
</form>
You are going to want to assign every radio box a descriptive class like 'text-radio' or 'home-radio'. Then when you need to change all of the Text radio boxes you do something like the following in jQuery:
$(".text-radio").attr('checked', 'checked');

How to trigger a click on checked radio button in jquery or javascript

Javascript:
if (GetCookie('prev_radio_value')!=null){
alert(GetCookie('prev_radio_value'));
$(":radio[value="+GetCookie('prev_radio_value')+"]").attr('checked',true);
$(":radio[value="+GetCookie('prev_radio_value')+"]").triggerHandler('click');
$(':radio:checked').triggerHandler('click');
$('input:radio[name=theme]:checked').click();
}else{
alert("clicking first");
$("input:radio:first").attr("checked", true).trigger("click");
}
HTML code:
<ul>
<li><input type="radio" name="theme" value="theme1"/>Theme1</li>
<li><input type="radio" name="theme" value="theme2"/>Theme2</li>
</ul>
this code is inside div -> 'checkbox_div'
click function :
$("#checkbox_div input:radio").click(function() {
alert("clicked") ;
});
I have used the trigger click in 3 ways but none of them worked or triggered the click event.
example link : http://jsbin.com/ezesaw/1/edit is not triggering the click event upon selection of first radio button.
Just call "click()" without the function as an argument
$("#checkbox_div input:radio").click();
It works just fine:
http://jsbin.com/ivojoz/1/edit
The problem may be that you are not selecting the radio correctly
try
$('#checkbox_div input[type="radio"]').click(function() {
alert("clicked") ;
});
$("#checkbox_div").on('click','input:radio', function() {
alert("clicked");
});
Give this code a shot. It worked for me.
In case u are still interested in this question:
The click event is implied when selecting/checking a radio button, all you need is to bind a procedure to it, this is just ONE way:
//js for radio button click
$('input[type="radio"]').on('click', function(){
window.alert($(this).val());
})
<!--html-->
<input type="radio" value="first" name="same"/>
<input type="radio" value="second" name="same"/>
<input type="radio" value="third" name="same"/>
Whether done manually or programmatically, it seems that clicking an already checked radio button does not necessarily have any effect!
Assuming HTML of:
<input type="radio" name="rv_submit" value="delete" id="rb2" checked>
Trigger the required action via jQuery as follows:
$('#rb2').prop('checked', false); // Turn off 'checked' ...
$('#rb2').click(); // ... or click() has no effect

Why am I submitting the form twice? jQuery submit() with radio button

I'm using jQuery to submit a form in an MVC app. I have a breakpoint inside the controller and I see it is being hit twice. What am I doing wrong?
Here is my jQuery
(function ($) {
$(document).ready(function () {
$(':radio').change(function () {
$('#frmMDR').submit();
});
});
})(jQuery);
and here is the form html
<form action="/Module/ModuleIndex" id="frmMDR" method="get">
<input id="rdoMaintenance" name="module" type="radio" value="Maintenance" /><label for="rdoMaintenance">M</label>
<input id="rdoDiagnostics" name="module" type="radio" value="Diagnostics" /><label for="rdoDiagnostics">D</label>
<input id="rdoRepair" name="module" type="radio" value="Repair" /><label for="rdoRepair">R</label>
<input id="hdnVehicle" name="hdnVehicle" type="hidden" value="" />
</form>
I'm guessing I shouldn't be using the change event. If anyone knows how to correct the problem, I'd love to hear any ideas. Thanks so much for any tips.
Cheers,
~ck in San Diego
You are getting two hits because two radio buttons are changing state. Radio buttons only allow one element in a group to be selected so when you are clicking a radio button, two events are happening:
A new radio button is selected
The previously selected radio button is deselected
This is two events and the reason why your code is being hit twice. To solve it you could give your radio buttons a class and then handle the event on click using the class as the selector.
<input class="radio" id="rdoMaintenance" name="module" type="radio" value="Maintenance" /><label for="rdoMaintenance">M</label>
<input class="radio" id="rdoDiagnostics" name="module" type="radio" value="Diagnostics" /><label for="rdoDiagnostics">D</label>
<input class="radio" id="rdoRepair" name="module" type="radio" value="Repair" /><label for="rdoRepair">R</label>
And your jQuery could be:
$('.radio').click(function () {
$('#frmMDR').submit();
});
You should probably just check for selected within the change function for which is selected. This way it'll only fire for the selected radio button, and you don't need to worry about binding or unbinding any events, and it should work regardless of what input method changed it.
Here's an article on handling events from check boxes and radio buttons in JQuery.

I need to perform an action based on which radio button is selected (by jQuery), but neither jQuery's click or change method is doing what I want

In the callback of a HttpRequest I have, I run this jQuery code:
$("input[value='"+data.notetype+"']").click();
So the radio button with the value of data.notetype is selected. This works fine. But I need to perform an action based on what button is now selected.
If I use the change() method like this
$("input[name='note_type']").change(function () {
var clicked = $("input[name='note_type']:checked").val()
alert(clicked);
});
it works fine when I click on the radio buttons, but when the radio button is set by the first line of code above, nothing happens.
If I use the click() method like this
$("input[name='note_type']").change(function () {
var clicked = $("input[name='note_type']:checked").val()
alert(clicked);
});
it works fine when I click on the radio buttons, but when the radio button is set by the first line of code above, the message box shows the value of the radio button that was selected, not the one it is changing to.
Can anyone let me know how to fix this problem? Thanks for reading.
$("input[name='note_type']").click(function () {
var clicked = $(this).val();
alert(clicked);
});
Here is a solution for this problem, I think this will help you
For example following is your html
<input type="radio" name="some_name" value="1"> 1 <br />
<input type="radio" name="some_name" value="2"> 2 <br />
<input type="radio" name="some_name" value="3"> 3 <br />
<input type="radio" name="some_name" value="4"> 4 <br />
Try following jquery for this html
$('input[type=radio]').bind('click', function() { alert( $(this).val() ); });
I hope this will help

Categories