Extract the content of a div with a specific class using JavaScript

I have a pair of div elements

<div class="tab-pane active" id="home">

<div class="tab-pane" id="profile">

Both of these divs contain forms with a hidden field

<input type="hidden" name="selectedRadioValue" id="selectedRadioValue">

Therefore, I want to develop a javascript function that can set a value for the hidden input field.

if($("#home").hasClass("active")) {
      assign "radio1" as the value in the hidden input field 
    }
else if($("#profile").hasClass("active")) {
     assign "radio2" as the value in the hidden input field  
    }

I apologize for asking this kind of question. I am new to javascript and have attempted some code on my own but need assistance. How can I achieve this? Please provide guidance.

Solution:

$(function () {
    $('button').on('click', function () {
        if ($("#home").hasClass("active")) {
            $('.selectedRadioValue').val('radio1');
        } else if ($("#profile").hasClass("active")) {
            $('.selectedRadioValue').val('radio2');
        }
    });
});

Answer №1

To retrieve the hidden value from a form within an active tab pane, iterate through each tab pane, locate the form inside it, and then extract the hidden value. Once you have the value, assign it to the corresponding radio button within the same form.

It's advisable to avoid using the same ID for multiple elements, such as #selectedRadioValue. Using classes would be a better approach in such cases.

$(function() {
    // Iterate over all active tab panes
    $('.tab-pane.active').each(function() {
        // Retrieve hidden input value
        var hiddenValue = $('form #selectedRadioValue', $(this)).val();

        // Assign hidden value to radio input
        // Radio inputs should have '.radio-input' class
        $('form .radio-input', $(this)).val(hiddenValue);
    });
});

Edit

If you want to map hidden inputs to radio1/radio2, simply ensure your code correctly assigns radio1/radio2 as values to the input. Add a class like radio-hidden to the input, and set the values using

$('.radio-hidden').val('radio1');
and so on.

$(function () {
    $('button').on('click', function () {
        if ($("#home").hasClass("active")) {
            $('.radio-hidden').val('radio1');
        } else if ($("#profile").hasClass("active")) {
            $('.radio-hidden').val('radio2');
        }
    });
});

Check out the fiddle here: http://jsfiddle.net/3NAC9/

Answer №2

if($("#home").hasClass("active"))                              
{
  $("#selectedRadioValue").val("radio1");
}
else if($("#profile").hasClass("active"))
{
   $("#selectedRadioValue").val("radio2");
}

Hopefully this code accomplishes what you need it to do.

Answer №3

Modify the input fields to make them hidden:

<input type="hidden" name="selectedRadioValue" class="selectedRadioValue">

Then adjust your JavaScript code as follows:

var radio_map = {
    'home': 'radio1',
    'profile': 'radio2'
};
$('.selectedRadioValue').val(radio_map[$(".tab-pane.active").attr('id')]);

This is how the code functions:

  • $(".tab-pane.active") selects the active tab-pane element.
  • .attr('id') retrieves the ID of that element.
  • radio_map[id] accesses the value in radio_map related to the provided ID.
  • $(".selectedRadioValue") selects all hidden inputs with that class.
  • $(".selectedRadioValue").val(...)
    updates their values accordingly.

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

What is the method for retrieving properties with varied names from a collection?

My collection has the following structure https://i.sstatic.net/FZIqt.png Is there a way to access properties with different names within a collection? I attempted it this way: for(i=0;i<$scope.users.length;i++) { console.log($scope.users[i].goo ...

Is it possible to bypass the execution of jQuery jsonp requests?

I am attempting to utilize jQuery to determine whether a specific website/port is blocked or unblocked by a user's computer. While I have managed to make it work effectively, I am encountering an issue where it throws errors such as "Uncaught SyntaxEr ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

Explore the contents of your Webpack bundle directly from your browser console

When using Typescript with Webpack for a debug build that includes source maps, I am able to access static class files in the sources tab without any issues. However, the actual class name is undefined at the global scope. class SomeStaticClass { public ...

css top navigation does not appear at the top of the webpage

My navigation bar appears to have an unexpected 5px padding issue that is causing it not to align properly at the top. To investigate, I have created a basic header.html + header.css setup as follows: <link href="css/header.css" rel="stylesheet"> &l ...

Using Javascript to transmit audio via a microphone

I am currently trying to use Selenium to simulate a user on a website that features audio chat. My goal is to emulate the user speaking through the microphone. While I have come across several resources discussing how to listen to the microphone in JavaSc ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

Utilize image maps for dynamically displaying and concealing div elements

Here is the current state of my code... VIEW DEMO I am aiming to display the blue text to the user only when they click on the blue circle, etc... I believe I need to modify the attributes of the div elements, but I am not very familiar with jQuery and ...

How can I show pagination links as buttons on a gridview in ASP.NET?

When working on asp.net web forms, I encountered an issue where I was unable to display pagination links as buttons with a gray background on the grid view control. To achieve this, I needed to assign a CSS class to the pager style on the grid view in ord ...

Navigating through an array of images using ng-repeat

I am attempting to iterate through the image array and have each image correspond to a separate li. Despite using the variable "image" as my identifier, I am encountering difficulties looping through the array. The line that I am trying to modify is as fol ...

Is it possible for jquery to run an entire HTML file using ajax?

Based on information from a discussion on Stack Overflow, it seems that I can utilize the jquery getScript() method to run a remote JavaScript file loaded via Ajax. However, in my specific scenario, the script file is located within an HTML file. Is ther ...

When the language in Next.js is changed using setAppLanguage, the query becomes empty

In my Nextjs project, I encountered an issue where, upon redirecting to a specific page (pages/search/index), I was able to retrieve the query parameter in getServerSideProps. However, when I changed the language using setAppLanguage imported from next-t ...

A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below let columns = [ {id: 1, columnName: 'Column 1'}, {id: 2, columnName: 'Column 2'}, {id: 3, columnName: 'Column 3'}, {id: 4, columnName: 'Column 4'} ]; My ...

jQuery user interface Dialog buttons

Is it possible to access the button within a click event handler when creating a dialog with buttons like: buttons: { 'button text': function(){ // do something }, In this ...

The uploadify plugin in jQuery: onAllComplete event triggered regardless of any errors

I'm currently utilizing the jquery uploadify plugin for enabling users to upload their profile pictures on my ASP.NET MVC platform. As I encountered a few issues, I am seeking assistance: $popup.find('#fileInput').uploadify({ 'uplo ...

Is there a way to reveal hidden content using jQuery?

Is there a way to toggle between showing and hiding content based on user clicks? I noticed that in anchor tags, 'scr' is used before the id, like scrhome_screen. However, in the div tag that I want to display, it only has the id home_screen. ...

Instructions on adding an activity indicator in a centered box with a loader inside

I'm currently working on integrating an Activity Indicator into my Vue Native App, but I've been facing some issues as it doesn't seem to be displaying the Activity Indicator properly. Here is the code snippet I've tried: <Absolute ...

Leveraging jQuery plugins within an AngularJs application

I am currently trying to implement the tinyColorPicker plugin from here in my Angular app, but I am facing difficulties with it. An error message keeps appearing: TypeError: element.colorPicker is not a function In my index.html file, I have included th ...

unable to toggle the navbar

Currently, I am facing an issue with the navbar-toggle button while using Bootstrap. Initially, I thought the problem was with my navbar code, so I tried pasting the example from the Bootstrap Website, but it did not work either. The button appears, but t ...

The code is running just fine when tested locally, but it seems to encounter an issue when accessed remotely, yielding

Currently, I am in the process of developing a dual twin setup using a Raspberry Pi. The goal is to simulate a continuous transmission of body temperature data, which is then sent to a server that stores the information in a MongoDB database. Everything fu ...