Radio button onchange event not triggering

I have a group of radio buttons that are supposed to trigger the hider(something); function when they change, whether they are checked or unchecked. The script works correctly when the radio buttons are checked and call the JS function. However, if a different radio button in the same group is selected, causing one of them to become unchecked, the js script is not triggered again.

Should I be using something other than onchange for this functionality?

Here is how the radio buttons are currently set up:

<input name="ostype" type="radio" value="0" onchange="hider(solaris);">solaris
<input name="ostype" type="radio" value="1" onchange="hider(linux);">linux

The hider function code looks like this:

function hider(divid) {
 if ($(divid).is('.hidden')) {
  $(divid).removeClass('hidden');
 } else {
  $(divid).addClass('hidden');
 }
}

Answer №1

Even though this query about "radio button onchange" remains unanswered but is highly ranked on Google, here's a helpful solution for those still searching.

If you are utilizing jQuery, utilize jQuery's attribute selector as recommended by Flavius Stef.

If you want to signify an active radio button in your code by adding the "hidden" class, follow this example:

$("your selector here").change(function() {
    $('input[name="' + this.name + '"]').removeClass("hidden");

    $(this).addClass("hidden");
});

Remember the distinction between $(this) (jQuery object) and this (DOM object). The code removes the "hidden" class from all inputs with the same name and then adds it to the current input.

This method assumes unique names for different inputs on the page. Additionally, it only works for radio buttons since the "change" event triggers upon activation, not deactivation.

Responding to onchange events for checkboxes and radios

In my situation, I aimed to assign a "checked" class to active radio buttons and checkboxes. For checkboxes triggering the "onchange" event when checked or unchecked, extra code was necessary.

$('input[type="radio"]').change(function() {
    $('input[name="' + this.name + '"]').removeClass("checked");
    $(this).addClass("checked");
});

$('input[type="checkbox"]').change(function() {
    $(this).toggleClass("checked", ($(this).is(":checked")));
});

The latter function uses toggleClass to apply the "checked" class based on .is(":checked") being true.

You may consider combining both functions like so:

$('input[type="radio"], input[type="checkbox"]').change(function() {
    if(this.type == "radio")
        $('input[name="' + this.name + '"]').removeClass("checked");

    $(this).toggleClass("checked", ($(this).is(":checked")));
});

Always exercise caution when handling onclick events as they may not trigger during keyboard navigation.

Answer №2

Attach a change event to ALL radio buttons when the document is loaded:

$(function(){

   $('input[name=list_type]:radio').on("change", function(){   
       manageVisibility();
   });
   manageVisibility();    
});

Show or hide a block based on the status of ONE radio button:

function manageVisibility(){
   if ($("#Option").is(':checked')){
       $('#Block').show();
   } else {
       $('#Block').hide();
   }

}

Answer №3

<input name="ostype" type="radio" value="0" onclick="hider('sun');">sun
<input name="ostype" type="radio" value="1" onclick="hider('penguin');">penguin
function hider(divid) {
 $( 'div.div_class' ).hide();
 $( '#' + divid ).show();
}

Remember to assign a class to target the divs and include quotation marks around 'sun' and 'penguin' in the function calls

Answer №4

Take a look at this example for some inspiration (tested on Chrome and Firefox):

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
</head>
<body>
<input type="radio" name="ostype" checked="checked" onclick="hider('linux')">linux
<input type="radio" name="ostype" onclick="hider('solaris');">solaris

<div id="content">
        <div id="linux">linux</div>
        <div id="solaris" style="display:none;">solaris</div>
</div>
<script>
function hider(divname) {
        $('#content div').each(function(){
                $(this).hide(); 
        });

        $('#'+divname).show();
}
</script>
</body>
</html>

Answer №5

If my interpretation is correct, a simple solution would be to utilize an onClick event for each button. This way, you can hide all other buttons while displaying the one that is being clicked on. Here's an example:

function toggleButton(buttonId)
    {
        var buttons = document.getElementsByTagName("button");
        
        for (var i = 0; i < buttons.length; i++)
        {
            if (buttons[i].id == buttonId)
            {
                buttons[i].style.display = "block";
            }
            else
            {
                buttons[i].style.display = "none";
            }
        }
      
    }

This code will ensure that only the clicked button is visible, while hiding all others. You can expand this functionality by adding similar functions for additional buttons that need to be hidden.

If you prefer using jQuery, you can achieve the same effect with the following code:

function showAndHide(elementToHide, elementToShow)
{
    $(elementToHide).hide();
    $(elementToShow).show();
}

Remember to include style="display:none" in the CSS of each div element to ensure they are initially hidden.

Answer №6

Have you properly initialized the variables solaris and linux? If not, your browser may display an error message.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty Aligning Header Elements - Combining Navigation and Logo on the Same Line

I am currently facing an issue with positioning a logo and navigation links within a <header> element. When I apply the CSS property text-align:center;, the logo aligns to the center on one line while the navigation links appear on another line direc ...

The use of Ajax JQuery to retrieve data from a MySQL database using PHP is not functioning properly when attempting to handle

I spent hours working on this but couldn't find a solution on your website. I have a jsonTable.php file that connects to a database and returns JSON using echo: { "livres": [{ "titre": "John", "auteur": "Doe", "annee": ...

Error message: "Uncaught TypeError: Cannot read property 'module' of undefined when using AngularJS in conjunction with RequireJS."

Embarking on my journey of app development with angularJS was a thrilling experience. However, after investing weeks into the project, I had an epiphany - why didn't I start using require JS from the get-go to load my modules? A rookie mistake, yes, b ...

The issue of Bootstrap icons not displaying on the front-end arises when integrating them into a Vuejs Template

I'm in the process of constructing a web application using Vue.JS. I've integrated the [Bootstrap Icons][1] into my application, but for some reason, the icons are not showing up on the screen. Here are the steps I followed: Installed Bootstrap ...

Customizing CSS based on URL or parent-child relationship in WordPress

I'm having trouble finding a solution for what seems like a simple issue... Currently, my header has a border-bottom and I'd like to change the color of this border based on the section the user is in. For example, consider these parent pages: ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

Order table column by checkbox status using Jquery

My datatable includes a column named Waive Fee containing checkboxes. I need the ability to sort this column so that when the header is clicked, all checked checkboxes move up or down accordingly. Is there a method in jQuery to achieve this functionality? ...

What is the best method to retrieve the nested value in this JavaScript/HTML code?

Can anyone help me extract the value "Yes, I am a Speaker" from this code using Javascript DOM element with getElementById? The challenge is that the value is nested inside a list element without any specific attributes. Each block of code has a unique l ...

What is causing the backslash character to be removed from my ajax request?

When using Ajax to call a rest endpoint, the request takes two parameters: user and permission. $.ajax({ type: 'GET', cache: false, url: "/app/Rest/4.0/UserManagement/AddPermissionToUser", data: { username: encodeURI(user ...

Angular 6 canvas resizing causing inaccurate data to be retrieved by click listener

The canvas on my webpage contains clickable elements that were added using a for loop. I implemented a resizing event that redraws the canvas after the user window has been resized. Everything works perfectly fine when the window is loaded for the first ti ...

The process of ensuring a component updates upon clicking on it

In the process of creating a to-do app, I am working on implementing an edit mode for tasks. My goal is to have a task title that expands into task details when clicked (using Collapse from MUI). Additionally, I aim to enter into an edit mode by clicking o ...

Triggering a JavaScript event with every update to the DOM marked as "completed"

I've been having some trouble with a specific task. I'm working on a script where I need to execute some functions after DOM manipulation is complete. The challenge is that I can't make changes to any other scripts on the page, as they might ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Could someone help me understand this JavaScript code where a function takes an object as a formal parameter?

Within a Vue component's methods, I came across the following code snippet defining a function: methods: { onEditorChange({ editor, html, text }) { console.log('editor change!', editor, html, text) this.content = html ...

Changing the model does not automatically update the visibility of ng-show

I have a fragment of my view that simply displays a loading indicator. Html: <span class="app-loading-container"> <span class="app-loading-animation" ng-show="loading"></span> </span> When I initially load the page, the span ...

What is the best way to collapse all other nodes within a bootstrap4 list?

My goal is to implement a Bootstrap 4 event that collapses expanded lists in a navigation bar, ensuring that only one list is expanded at a time. The challenge is that the list is hierarchical, with items that can contain sub-lists. The current code only ...

Tips for transferring Json data through Ajax in jquery for an html element?

I am facing an issue while trying to display data from 5 rows of a MySQL database in a table using the success function of a jQuery AJAX call. The data is returned in JSON format. Problem: I am able to retrieve only one row at a time, even though the cons ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

Is it possible to encounter an issue where utilizing POST with React Fetch results in receiving an

My backend server, which is a simple Node/Express setup, can receive a post request as shown below: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()) app.post('/auth/login', (req, res) => { console.log(req.bo ...

Divs are piling up on one another, but they're not in the correct sequence

Currently, I have two divs placed side by side and utilizing a media query to stack them. However, my goal is to have the yellow div on top with the blue div below it once the script is executed. Unfortunately, I am unsure of how to achieve this. #wra ...