Choose a different element based on its data attribute

Check out this fiddle I created: http://jsfiddle.net/4Ly1973u/.

Below is the HTML code I used:

<article>
  <select>
    <option name='First' value='first'>First</option>
    <option name='Second' value='second'>Second</option>
    <option name='Third' value='third'>Third</option>
  </select>
  <div data-name='first' class='show'>
    This one should show by default.
  </div>
  <div data-name='second'>
    only visible when "second" option is selected
  </div>
  <div data-name='third'>
    only visible when "third" option is selected
  </div>
</article>

My goal is to have the first div displayed by default, and dynamically switch to the corresponding div based on the select option chosen. While I could achieve this with an if statement, considering a scenario where there are multiple options, I am exploring cleaner alternatives. Is there any other approach apart from using if statements?

Answer №1

Check out this solution

$(function () {
    $("select").on("change", function () {
        $('.show').removeClass('show');
        $('div[data-name="' + $(this).val() + '"]').addClass('show');
    });
});

See it in action: http://jsfiddle.net/4Ly1973u/1/

Answer №2

Check out this live example: http://jsfiddle.net/8gHjR3sf/6/

<section>
    <select>
        <option name='One' value='one'>One</option>
        <option name='Two' value='two'>Two</option>
        <option name='Three' value='three'>Three</option>
    </select>
    <div id='one' class='visible'>This is visible by default.</div>
    <div id='two' class='hidden'>Only shows when "Two" is selected.</div>
    <div id='three' class='hidden'>Only shows when "Three" is selected.</div>
</section>

CSS

.visible {
    display: block;
}
.hidden {
    display:none;
}

JavaScript

$(function () {
    $("select").change(function () {
        $('.visible').removeClass('visible').addClass('hidden');
        var selectedValue = $("select option:selected").val();        
            $("#" + selectedValue).removeClass('hidden').addClass('visible');
    });
});

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

Retrieve the attributes of DOM elements following a successful AJAX request

Is there a way to retrieve the video duration using video.duration following my ajax video upload? Despite achieving ajax success, this function continues to return NaN. I have attempted methods such as $.when().then or $.when.done() but with no success. ...

Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status? <body onload="enableDropdown(false);"> <form name="form1" method="post" onload="enableDropdown(false);"> <input type="checkbox" name="others" oncl ...

The background-color is covering up the pseudo element with a z-index of -1

I am working on a problem regarding a .link class with an ::after pseudo element positioned underneath it to create a box-shadow effect upon hover. .bg { background-color: aqua; height: 100vh; } .link { position: relative; font-weight: ...

Utilizing NPM: downloading various versions of the same library multiple times

Currently, I am heavily involved with Play Framework 2.4 and AngularJs 1.5.8 while also incorporating coffeescript into the mix. As I delve deeper into my project, the use of npm has come under scrutiny. Given that we are utilizing multiple libraries, ea ...

Unable to retrieve post information from Angular using PHP

I've hit a roadblock in my Angular App where I can't seem to access the body of the post data being sent from Angular 4. Despite numerous attempts, I'm unable to retrieve this crucial information. Can anyone lend a hand in identifying the is ...

Applying CSS styles to position the input panel on the left side of the page

On my webpage, I have a layout that consists of a header, a footer, a left panel with inputs, and a right panel with outputs, all designed using bootstrap 4. The left panel is typically shorter than the right panel, and its height may vary in relation to ...

Why does the address bar show value changes in IE when using window.location.hash, but the value doesn't change in the DOM when going

Here is a sample JavaScript code that attempts to detect the back button event: document.location.hash="#1"; document.location.hash="#2"; document.location.hash="#3"; function check() { if("#3"!=window.location.hash) { alert("Back button clic ...

What is the method for shortening the sizable text "Hereisthelargetextbreakwithphp" to "Hereisthelarge..." using PHP?

Modify the large text "Hereisthelargetextbreakwithphp" to "Hereisthelarge..." $string = "Hereisthelargetextbreakwithphp"; $string = strip_tags($string); if (strlen($string) > 21) { $stringCut = substr($string, 0, 21); echo $string = substr($str ...

Examining the functionality of my PHP codes and forms

I'm currently working with two HTML forms and two PHP scripts. The first form is designed to save a user's email to a .txt file, while the second form is a Stripe payment form that processes payments using PHP code. However, I've encountere ...

Steps to trigger the "Confirm form resubmission" prompt when a user attempts to refresh their browser

I am encountering a situation where users are unable to refresh the page by clicking the browser's refresh button or pressing F5. I would like to simulate 'form resubmission' in order to display a prompt message. Could someone please provid ...

What is the best way to determine the total number of classes that come before a specific element

Currently, this is my approach: <script> function Answered(str) { var script = document.getElementsByClassName('Answered')[str]; if(script!==null) {script.setAttribute("style", "");} } </script> <span class=Answered style=" ...

Having trouble properly sending gender value through javascript/ajax functionality

Within my database, the gender_id attribute is configured as an enum with options ('M', 'F') and M serves as the default selection. Gender Selection Form <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <label>Gend ...

Bootstrap Modal with HTML5 validation highlights focusable errors upon form submission

I have a simple form for updating user data: <div class="row"> <div class="col-7"> <h6 class="text-center">User Profile</h6> <hr> <div class="form-group"> <label for="name" cla ...

Prevent time from being structured into hours

In my app, I am successfully using Moment to format times. There is one instance where I need to count hours instead of converting it to a regular time format. The time format I am working with looks like this: 0:00:02 AM However, I am trying to remove t ...

What type of programming language is utilized in creating this online interactive calculator?

I have a strong interest in creating an interactive calculator like the one found on keto-calculator, but I am unsure of where to begin my research on how to develop it. Can you provide insights on the coding language typically used for such calcula ...

What is the best way to choose a random number using jQuery?

<div class="yyy"></div> <p>...</p> <pre><code>let content = $(".xxx").text(); $(".yyy").html(content); http://jsfiddle.net/tQeCv/ I just require this specific input : Number is {1|2|3|4}, and {one|two|three|four} ...

Obtain an array containing only the specific values of each object

Currently, I have the following code snippet: <db.collection>.find({ id : { $exists: true } }) This query retrieves all documents containing an id property. However, I am interested in transforming this result into an array that contains only the va ...

Setting the select option in AngularJS with predefined options can be easily achieved with

I am encountering an issue with a select element that has predefined options. Even though the select element is using ng-model, when the model is set to one of the option values, it fails to be selected. Below is the snippet of HTML code: <select clas ...

Fetch the initial row using a jQuery Ajax request

I am working on a jQuery Ajax call: $.ajax({ type: "POST", url: "http://192.168.0.70:81/MobileService.asmx/FetchData", contentType: "application/json; charset=utf-8", dataType: "json", async: true, cache: fa ...

What is the best way to reset a looping variable in a Node.js application?

I have encountered an issue with an API method in my nodejs app. Within one of my controllers, I am attempting to generate pages upon clicking. However, I have found that when calling the method, my for loop fails to reset the values to their default state ...