Cold_Class Cold_Class - 1 year ago 46
HTML Question

Listen to radio buttons on change and when the document is ready with jQuery?

I'm searching everywhere and I can only find how to make a radio button listener or how to check if it's checked on

but never both, like I need:

When I edit an object in a form, depending on what was selected in a radio group a
should be visible or hidden. And when the user changes that, it should appear/disappear again.

I could initialize the correct state by adding a hidden class on the server side to the
but then I would have to program all my dependencies in php AND jQuery since I'm not using AJAX - that doesn't make sense to me.

I looked in the jQuery website for a best practice - it seemed to be this.

But I don't understand how I should do it in my case - the
seems not to be working and I don't exactly know why. Because I'm referencing a function outside of the event?

var fieldHider = function (turnOn, toggleFields, fadeIn) {
var visibilityAction;
if (turnOn) {
visibilityAction = (fadeIn) ? "fadeIn" : "show";
} else {
visibilityAction = (fadeIn) ? "fadeOut" : "hide";

var translatorRadioChanged = function (event) {
var isOn = ($(this).val() === '1');
var fading = (event) ? true : false;
fieldHider(isOn,'label[for="translator"]', fading);

var translatorRadioNames = "translatorNeeded";

$(function () {
$("input[name='" + translatorRadioNames + "']").change(translatorRadioChanged);

<script src=""></script>
<label for="translatorNeeded">
Translator needed
<input type="radio" value="1" name="translatorNeeded">
<input type="radio" value="0" checked="checked" name="translatorNeeded">
No -> Div below should be hidden!
<label for="translator">
<label class="lcapp-label clearfix" for="translator">
Translator Name + Language
<input type="text" name="name" size="5">
<input type="text" name="lang" size="5">

Answer Source

You are calling the function with 2 different contexts.

Try just triggering the change event on the matching checked input when page loads and after the change listener is assigned


$("input[name='" + translatorRadioNames + "']").change(translatorRadioChanged);


$("input[name='" + translatorRadioNames + "']")
       // assign event listener
       // trigger the event on checked one if it exists

Now the function will be called in the context of the event handler and will have the right context for this