Add some pizzazz to your design using jQuery!

I have been working on a web application using asp.net c#. I have a div element where I applied the following style to it at the server side:

spanNivelRiesgo1.Attributes.Add("style", "display:none; visibility:hidden");

Now, I have a radiobutton list and on its click event, I am attempting to display the div element, but unfortunately, it's not working as expected.

var spanNivelRiesgo = $("spanNivelRiesgo1").is(":visible") ? $("spanNivelRiesgo1") : $("spanNivelRiesgo2");

If the 'no' option is clicked, the div should appear:

$(spanNivelRiesgo).css({'display':'block', 'visibility':'visible'});

However, despite my efforts, it doesn't seem to be working correctly. As I am relatively new to jQuery, I'm unsure about what might be going wrong.

Below is the full code snippet:

<div class="span" id="spanNivelRiesgo1" runat="server" visible="False">
                <table class="table_span">
                    <tr>
                        <td style="width: 230px;">Nivel de Riesgo:</td>
                        <td>
                            <asp:DropDownList ID="ddlNivelRiesgo1" runat="server" Width="150px" CausesValidation="True" ValidationGroup="a"></asp:DropDownList></td>
                    </tr>
                </table>
            </div>

<div class="span" id="spanNivelRiesgo2" runat="server" visible="False">
                <table class="table_span">
                    <tr>
                        <td style="width: 230px;">Nivel de Riesgo:</td>
                        <td>
                            <asp:DropDownList ID="ddlNivelRiesgo2" runat="server" Width="150px" CausesValidation="True" ValidationGroup="a"></asp:DropDownList></td>
                    </tr>
                </table>
            </div>

On the server side:

if (_oportunidadMejora)
            {
                rblOportunidadMejora1.Items[0].Selected = rblOportunidadMejora2.Items[0].Selected = true;
                spanNivelRiesgo1.Attributes.Add("style", "display:none; visibility:hidden");
                spanNivelRiesgo2.Attributes.Add("style", "display:none; visibility:hidden");
            }
            else
            {
                rblOportunidadMejora1.Items[1].Selected = rblOportunidadMejora2.Items[1].Selected = true;
                try
                {
                    spanNivelRiesgo1.Attributes.Add("style", "display:block; visibility:visible");
                    ddlNivelRiesgo1.SelectedValue = _nivelRiesgo;
                    spanNivelRiesgo2.Attributes.Add("style", "display:block; visibility:visible");
                    ddlNivelRiesgo2.SelectedValue = _nivelRiesgo;
                }
                catch { }

On page load:

rblOportunidadMejora2.Attributes.Add("onclick", string.Format("javascript:return OportunidadMejora();"));

Client-side function:

function OportunidadMejora(){

            var RB1 = document.getElementById("<%=rblOportunidadMejora2.ClientID%>");
            var spanNivelRiesgo = $("spanNivelRiesgo1").is(":visible") ? $("spanNivelRiesgo1") : $("spanNivelRiesgo2");
            var lblFecha = document.getElementById("<%=lblFechaCumplimiento.ClientID%>");
            var lblPlazo = document.getElementById("<%=lblPlazo.ClientID%>");

            var radio = RB1.getElementsByTagName("input");
            var isChecked = false;

            for (var i = 0; i<radio.length;i++){
                if(radio[i].checked){
                    if(radio[i].value == "True"){//La opción si, está marcada
                        $(spanNivelRiesgo).css({'display':'none', 'visibility':'hidden'});
                        //spanNivelRiesgo.hide();
                        lblFecha.innerHTML = "Fecha de Seguimiento:";
                        lblPlazo.innerHTML = "Plazo de Seguimiento:";
                    }
                    else{//La opción no fue marcada
                        $(spanNivelRiesgo).css({'display':'block', 'visibility':'visible'});
                        //spanNivelRiesgo.show();
                        lblFecha.innerHTML = "Fecha de Cumplimiento:";
                        lblPlazo.innerHTML = "Plazo de Cumplimiento:";
                    }
                }
            }
        }

Answer №1

One way to solve this is by utilizing the id (#) selector. Here's how you can make the necessary changes:

var spanNivelRiesgo = $("#spanNivelRiesgo1").is(":visible") ? $("#spanNivelRiesgo1") : $("#spanNivelRiesgo2");

Additionally, there is no need to encapsulate spanNivelRiesgo again since it's already a jQuery object. You can simply do:

spanNivelRiesgo.css({'display':'block', 'visibility':'visible'});

Rather than doing it like this:

$(spanNivelRiesgo).css({'display':'block', 'visibility':'visible'});

Answer №2

I encountered some issues with my code, prompting me to switch from jQuery to pure JavaScript.

Below is the JavaScript function I used:

var spanRiskLevel = document.getElementById('<%=(spanRiskLevel1.Visible)?spanRiskLevel1.ClientID:spanRiskLevel2.ClientID%>')
;

if(radio[i].value == "True"){//The option yes is selected
                        spanRiskLevel.style.display = "none";
                        spanRiskLevel.style.visibility = "hidden";
                        lblDate.innerHTML = "Follow-up Date:";
                        lblDeadline.innerHTML = "Follow-up Deadline:";
                    }
                    else{//The option no is selected
                        spanRiskLevel.style.display = "block;
                        spanRiskLevel.style.visibility = "visible";
                        lblDate.innerHTML = "Completion Date:";
                        lblDeadline.innerHTML = "Completion Deadline:";
                    }

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

The JavaScript function is not being activated by clicking on Selenium in Chrome

Take a look at the HTML snippet below: <table class="table-main "> <thead> <tbody> <!----> <tr class="" ng-if="mapCtrl.isAdded" style=""> <td/> <td> <td> <t ...

The Disabled element does not exhibit effective styling

When we include the disabled attribute in the text element, the style does not work. Can you explain why? <input pInputText [style]="{'padding-bottom':'10px','padding-top':'10px','width':'100%&apos ...

Elegant Decline of Javascript Functionality - Imported Web Assets

Looking for assistance from experienced JS coders. I'm currently working on a Wordpress website that utilizes jQuery AJAX methods to reload either the entire content area or just the main content section based on different navigation clicks. My aim i ...

Ways to retrieve the user's IP address and provide the information in JSON format

Although I am not an expert in PHP, I specialize in developing Android apps. One of the challenges I face is extracting the user's IP address from a specific URL . This URL provides various information when accessed, but my main requirement is to retr ...

Convert an image into a byte array and then into hexadecimal using the 0x? format

Hello everyone, I'm attempting to convert my image file into HEX format similar to what is done on this website. However, the code I am using produces an output like this: The output goes here... I would like the output to be formatted as follows: ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...

Tips for achieving JSON formatting with JavaScript or jQuery

To achieve the desired output format, I am required to transform the provided input json. input json: [ { "key a": "value alpha" "key b": "value beta" "key c": "value gamma& ...

Display an image in HTML, followed by a brief pause, and then showcase a second image

I am attempting to create a functionality where when a user checks off a radio box, an image displays first, followed by an swf file after 10 seconds. I have successfully implemented the image display. However, my attempt at using PHP sleep function within ...

Utilize page variables to activate audio clips upon clicking

Can someone assist me with a script that activates an audio clip when five icons on a page are clicked? The image of the icons can be found below: https://i.stack.imgur.com/mBC6o.png Here is the HTML code: <div class="slide overlay-container" id="int ...

Implementing a distinct approach to adding margins to div boxes using

Hello, I've been experimenting with the developer tools in Google Chrome to add margins to my navigation bar. The goal is to create gaps between the boxes. Any assistance would be greatly appreciated! http://jsfiddle.net/3jp1d0fe/8/ CSS div.contain ...

width restriction to only accommodate on two lines

Whether my text is short or long, I always want to ensure that it remains within two lines by defining the width of my div. Short Text +-------------------------+ | Short text goes here | | Short text goes here | +---------------------- ...

Choose a HTML element <a> containing a hyperlink reference and a nested child element <li>

Does anyone know of a way in javascript/css to select the (n) <li> in my code, while also specifying that the <li> must have a parent with the current <a> tag containing a specific href link? <a href="www.link.com">CATEGORY NAME& ...

Stop Bootstrap 4 from automatically wrapping columns to the next row

I'm experiencing an issue with a component using Bootstrap 4 where a column is expanding to another row due to the presence of a long text element with the "text-truncate" class. This results in Chrome vertically stacking the column below its intended ...

Boost the delay in the transition speed for hiding the Navbar while scrolling down with the help of Bootstrap

Hi there! I am currently learning HTML, CSS, and JS. I'm working on a homepage project using Bootstrap-5 and have successfully integrated a navbar. However, I've noticed that the navbar disappears too quickly when I scroll down. Is there a way to ...

Showcase big image upon hovering mouse with automatic positioning on Magento

As a newcomer to magento, I am interested in adding an effect that displays a large image when hovering over it with the mouse. This feature should automatically position itself on the product listing page in magento. Your assistance is greatly appreciate ...

What's the best way to customize the color of the text "labels" in the Form components of a basic React JS module?

I have a React component named "Login.js" that utilizes forms and renders the following:- return ( <div className="form-container"> <Form onSubmit={onSubmit} noValidate className={loading ? 'loading' : ''}&g ...

A guide on locating the row number of a table with Selenium Webdriver in Java

I have a table that contains multiple rows and columns. Here is an example of the HTML code: <!-- language: lang-html --> <div id="ScheduleTable-01" class="widget Scheduletable suppress-errors Schedule-grid" data-widget="ScheduleTable"> ...

Tips for deserializing JSON data in NewtonSoft into static classes with nested structures

One scenario involves a nested class with static properties, as demonstrated below: public class X { public class Y { public static string YString = null; } } Consider the following JSON data: { Y { "YString" : "World" } ...

Arrange the icons in multiple rows to ensure an equal distribution of icons on each row

There are 12 image icons displayed in a row within div elements using display: inline-block. However, when the browser window is resized, I would like the icons to be arranged on two or more rows so that each row contains an equal number of icons. ...

In ReactJS with Bootswatch, the font styles are not applied

I have experimented with various methods to apply this font, but it is still not functioning correctly. @font-face { font-family: 'Samim'; src: local('Samim'), url(./resources/fonts/Samim.ttf) format('truetype'); fon ...