Displaying different content inside a div based on the selection made in a dropdown menu

I'm experiencing difficulties with a jQuery script that should display the content of a div based on selected options in a drop-down menu.

The drop-down menu is supposed to provide numerical values for a calculator to determine a loan amount. However, when I input numerical values for both option value and corresponding div id, the code fails to work. Surprisingly, if I change these values to words, it works perfectly fine.

Is there a workaround to make this function using numerical values?

 <select name="apr" id="apr" class="loan-calculator__input" >                   
            <option value="">Select</option>
              <option value="4.7" class="good">Good</option>
              <option value="14.9" class="fair">Fair</option>
              <option value="29.9" class="poor">Poor</option>
            </select>
          </div>
          <div id="4.7"  style="display:none;" class="rating" ><p>Good - </p>
</div>
<div id="14.9" style="display:none;"class="rating" ><p>Fair</p>
</div>
<div id="29.9"   style="display:none;" class="rating"><p>Poor  </p>
</div>

(function($) {
$(document).ready(function() { 
    $('#apr').change(function(){
        $('.rating').hide();
        $('#' + $(this).val()).show();
    });
    });
})(jQuery);    

A jsfiddle has been set up to demonstrate the issue - http://jsfiddle.net/nineseven/W37np/

Answer №1

It's recommended to utilize the data attribute instead of using a number as an object identifier.

<div data-value="4.7"/>

$("[data-value='"+$(this).val()+"']").display()

Answer №2

Using decimal IDs may cause issues with this functionality.
I would advise against using this method to display content.
Nevertheless, here is a working example using string IDs:

http://jsfiddle.net/W37np/11/

(function($) {
$(document).ready(function() { 
        $('#apr').change(function(){
            $('.rating').hide();
            $('#' + $( "#apr option:selected" ).attr("value")).show();
        });
        });
    })(jQuery);

Answer №3

The functionality is not operational due to being interpreted as an expression.. avoid incorporating numerical values

Issue: Syntax error, unidentified expression: #14.9'

inspect the browser's error console for further information

Answer №4

It's important to extract the value from the option that is selected. Also, consider changing your ids as they may not be appropriate. In my demonstration, I have replaced them with dashes for clarity.

$('#' + $(this).find('option:selected').val()).show();

Check out the demo here

Answer №5

To assign specific values to certain options and modify the div's id accordingly, you can link the id with the option's class attribute. This way, you can extract the class and display it using the following code:

$('#' + $( "#selectedOption").attr('class')).show();

demo link

Answer №6

    $(document).ready(function () {
                    $('#apr').change(function () {
                        $('.rating').hide();
                        var prefix = "section-";
                        $('#' + prefix + $("#apr option:selected").attr("value")).show();
                    });
                });


<select name="apr" id="apr" class="loan-calculator__input" >                
                <option value="-1">Select</option>
                  <option value="321" class="excellent">Excellent</option>
                  <option value="654" class="average">Average</option>
                  <option value="987" class="poor">>Poor</option>
                </select>
              <div id="section-321" style="display:none;" class="rating" ><p>Excellent - You have a strong credit history and stable financial situation with no missed payments.</p>
</div>
<div id="section-654" style="display:none;" class="rating" ><p>Average - You may carry some debt and have had occasional late payments.</p>
</div>
<div id="section-987" style="display:none;" class="rating" ><p>Poor - You may have frequent missed payments, CCJs, and unstable job history.</p>
</div>

Using a prefix on the div tag is necessary to avoid using numeric values in IDs.

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

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

Positioning an image at the bottom left of the page using absolute positioning is simply not effective

Can anyone help me figure out how to make an image stay just above the footer on the bottom left-hand side of the main content? I've tried using floats, margins, and positioning on left nav elements without success. Here's a link to see what I me ...

Adding HTML and scripts to a page using PHP and JS

Currently, I am utilizing an ajax call to append a MVC partial view containing style sheets and script files to my php page. Unfortunately, it seems that the <script> tags are not being appended. After checking my HTTP request on the network, I can ...

Stop users from inputting dates beyond the current date in Angular 4

Encountering an issue with comparing the date of birth object and today's date object using Moment.js. Even if the entered date is smaller than today's date, it still throws an error. Below is the HTML code: <div class="form-group datepicker ...

Are there any available proxy server or Apache modules for converting XML SOAP responses to JSON format upon installation?

Lately, I have been trying to connect to a remote web service using Ajax, but I realized that the service (FedEx Services API) does not seem to support JSON responses. Is there a proxy server or an Apache solution that can help convert the XML/SOAP respo ...

Is it possible to retrieve data from a database using jQuery and store it in separate variables?

I am able to print out one field from a table, but I want to display all fields in separate tables. How can I achieve this? Below is my save/load code: // Save/Load data. $('').ready(function() { if($.cookie('code')) { $.aj ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

Displaying a project in the same location using jQuery

Struggling with jQuery and positioning hidden items that need to be shown? I have two white boxes - the left one is the Client Box (with different names) and the right one is the Project Box (with different projects). My goal is to show the projects of a c ...

What is the best way to conceal a div within every occurrence of a component when I activate my current target?

One of the challenges I'm facing involves displaying a div when a child component is clicked. This component is rendered multiple times on the page without any kind of loop. The tricky part is that when I show the div in one specific instance of the c ...

How can one quickly display a confirmation dialog box within react-admin?

Looking for a way to implement a confirmation dialog in my react-admin project, similar to JavaScript's alert function but more visually appealing. I want the user to only proceed with certain database operations if they click OK on the dialog. I cou ...

Error encountered in jquery.d.ts file: Unresolved syntax issue

I am currently in the process of transitioning my jQuery project into a Typescript project. I encountered an issue when attempting to include the jQuery typings from the DefinitelyTyped Github by using the following method: ///<reference path="../../ty ...

rotate a game embedded in a website by 90 degrees

Need assistance in rotating this embed code by 90 degrees. Can you provide some guidance? <div class="miniclip-game-embed" data-game-name="8-ball-pool-multiplayer" data-theme="0" data-width="750" data-height="520" data-language="en"><a href="http ...

Maintaining the selected option on page refresh with React Remix

I have a dropdown menu with 2 choices (en, no) for switching the language when onChange event occurs. To save the selected language, I am using localStorage. Due to the server-side rendering in Remix, direct access to localStorage is not possible. Therefo ...

Protractor's count() function fails to execute properly when called outside of a promise loop

var alerts = element.all(by.xpath("//div[@class='notification-content']")); alerts.count().then(function (val) { console.log(val); }); let compareValue = val; Is there a way to access the 'value' outside of the promise l ...

Is there an advantage to pre-rendering a circle on an HTML5 canvas for improved performance?

Is it more efficient to pre-render graphics for a basic shape like a circle on an off-screen canvas? Would there be noticeable improvements in rendering performance when dealing with 100 circles at game-like framerates? What about 50 circles or just 25? ...

Populate DataGrid using an input through AJAX and jQuery technology

I've been grappling with a persistent issue that's been bothering me for days now. Here's the scenario: Currently, I have a DataGrid that is empty and an Input Text field in place that utilizes AJAX and jQuery to display a list of available ...

Utilizing Jade to access and iterate through arrays nested in JSON data

Take a look at this JSON data: { "Meals": { "title": "All the meals", "lunch": ["Turkey Sandwich", "Chicken Quesadilla", "Hamburger and Fries"] } } I want to pass the array from this JSON into a jade view so that I can iterate over each item in ...

Query will be filtered based on user input, if available

I am working on a SQL query that needs to filter results based on user input. The current query works, but if the user does not provide any values, it returns incorrect results. How can I modify the SQL query to only filter results using the values provid ...

Using jQuery to apply a CSS border to an image within a textarea

Working with TinyIMCE, I am looking to incorporate a border around all images within the textarea whenever a user submits the form. $("form").submit(function() { var content = $("#edit-message1-value").val(); // Afterwards, I want to manipulate the cont ...