Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type field to be displayed when the user selects "uh".

Below is my code snippet:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
<script>

$('#s_designation').on('change',function(){
    if ($(this).val() === "uh") {
        $("#uh").show()
    }
    else {
        $("#uh").hide()
    }
});
</script>

<title>Untitled Document</title>
</head>

<body>

<label for="db">Choose type</label>
<select name="s_designation" id="s_designation">

   <option value="coo">Chief Operating Officer</option>
   <option value="uh">Unit Head</option>
</select>

<div id="uh" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Designation"/>
</div>

</body>
</html>

Answer №1

After testing the code provided, it seems to be working without any issues:

Link:https://jsfiddle.net/g95pyqw6/

Upon further examination, it appears that the code may be functioning correctly due to being tested on JSFiddle. To potentially resolve any issues, try uncommenting the first line of JavaScript - this should provide a solution! :-)

If you require any additional assistance, please don't hesitate to leave a comment. I am happy to help!

Answer №2

It appears that your jQuery code is running before the document fully loads. This means that the select element may not be visible to jQuery, and as a result, jQuery will not throw an error if it cannot find the specified element.

To ensure that your code runs after the document has finished loading, use $(document).ready like this:

<head>
-------
-------
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready(function() {
  $('#s_designation').on('change',function(){
    if( $(this).val()==="uh") {
    $("#uh").show()
    } else {
    $("#uh").hide()
    }
  });
});
</script>
-------
</head>

If you want to execute jQuery code after the page has loaded, simply place your code before the </body> tag like this:

<body>
-------
-------

<script>
$('#s_designation').on('change',function(){
if($(this).val()==="uh") {
$("#uh").show()
} else {
$("#uh").hide()
}
});

</script>

</body>

Answer №3

Below is the solution to your issue, tested on my local machine. Check out this Stack Overflow post for more information.


  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
    <script>
    $(function() {
          $('#s_designation').on('change',function(){
        if( $(this).val()=="uh"){
        $("#uh").show()
        }
        else{
        $("#uh").hide()
        }
    });});
        </script>

    <title>Untitled Document</title>
    </head>

    <body>

    <label for="db">Choose type</label>
    <select name="s_designation" id="s_designation">

       <option value="coo">Chief Operating Officer</option>
       <option value="uh">Unit Head</option>
    </select>

    <div id="uh" style="display:none;">
    <label for="specify">Specify</label>
    <input type="text" name="specify" placeholder="Specify Designation"/>
    </div>

    </body>
    </html>

Answer №4

Your code is missing the $(function() line which should not be commented out:

You also need to include the necessary jQuery library files

Please ensure to add this to your html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

For reference, here is a Fiddle link: http://jsfiddle.net/0mqze5ny/

$(function () {
    $('#s_designation').on('change', function () {
        if ($(this).val() === "uh") {
            $("#uh").show()
        } else {
            $("#uh").hide()
        }
    });
})

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

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Issue with Guild Member Add functionality in discord.js is not functioning as expected

I'm facing an issue with my code where the bot does not send a welcome message when a user joins, despite having everything set up correctly. Even when a user leaves, there is no farewell message being sent either. Here is the code I am using: bot.on ...

Implementing 'Load more...' in Rails for infinite scrolling instead of traditional pagination

I currently have a collection of items and have been utilizing the will_paginate gem. However, I am interested in implementing a "load more..." feature at the end of the list. Is there a straightforward way to achieve this with will_paginate, or should I e ...

Sort the data in Angular JS by one key, but ensure that results with another key set to 0 remain at the end

Here is an array of objects containing information about various car brands: $scope.cars = [ {"brand":"McLaren","price":70,"stock":0}, {"brand":"Renault","price":10,"stock":0}, {"brand":"Ferrari","price":100,"stock":3}, {"brand":"Lamborghini","pri ...

Unable to properly load the Kendo Tree View based on the selected option from the combo box in the Kendo UI framework

I am encountering an issue where the Kendo treeview is not populating with different values based on a selection from the Kendo combo box. I have created a JSFiddle to showcase this problem. http://jsfiddle.net/UniqueID123/sample In the scenario provided ...

"Maximizing Bootstrap Functionality with Angular 2: Step-by

I'm experiencing an issue with Angular2, Bootstrap 3.3.7, and Bootstrap Plugins. I have imported all the necessary stylesheets and JavaScript files in the 'index.html' file. Below is the snippet from the index.html: <!-- Bootstrap & ...

How can I loop through elements and add their ID attributes to an array using jQuery?

I need help identifying a group of <label> elements within a form using an array of element IDs. For example, given the array: [ input#country , input#other-country ], I want to match <label for="country">, <label for="other-country">, a ...

What is the best method for implementing page transitions between components in NextJS?

My goal is to create a form that smoothly slides to the right, similar to the one seen on DigitalOcean's website when you click "Sign up using email" here: . While the transition itself is relatively simple, I noticed that DigitalOcean uses 2 separat ...

Keep the first column of an HTML table fixed as you scroll horizontally

Below is an HTML table that I have created: <table id="customers" class="table table-bordered" width="100%"> <thead> <tr> <th colspan="2">Activities</th> <th>Mon 17</th> <th>Tue 18</th> </thead> ...

When making an AJAX request to an ASP.NET web method, strange characters are appended to the end of the response text. This issue seems

I need assistance with the following code: $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: location, data: JSON.stringify(ajaxData), dataType: 'xml', success: ca ...

What is the best way to extract information from a .txt file and transform it into an integer format?

I am currently working on a project involving a distance sensor that retrieves data from a Raspberry Pi and displays it on a website. The goal is to have the data stored in a .txt file and then transferred to the website for display. I am seeking assistanc ...

Attempting to cycle through rows of a table and triggering setInterval for each row does not appear to be successful

I am attempting to change the value of a cell from Offline to Online (and vice versa) within my DataTable by utilizing a web service. var $myTable = $("#my-table").dataTable(); var $myTableRows = $myTable.fnGetNodes(); for(var i=0; i<$myTableRows.leng ...

Running Python in React using the latest versions of Pyodide results in a malfunction

As someone who is new to React and Pyodide, I am exploring ways to incorporate OpenCV functionality into my code. Currently, I have a working piece of code that allows me to use numpy for calculations. However, Pyodide v0.18.1 does not support OpenCV. Fort ...

Issues with Twitter-Bootstrap Modal Functionality

After creating a modal dialogue: <a href="#myModal" role="button" class="btn" data-toggle="modal" id="LaunchDemo">Click here to launch the demo modal</a> <!-- Modal --> <div id="myModal" class="modal hide fade" tabindex="-1" role="di ...

Limit jQuery script to operate exclusively on a single page

Despite the abundance of answers to similar questions, my lack of JS skills hinders me from implementing them in my specific case. On my WordPress site, I have a script that changes the navigation bar's color when scrolling down to the #startchange CS ...

Setting a div's width to cover 100% of the screen's width

I'm currently working on creating a 2 column layout using divs. The left column has a fixed size of 150 px, while the right column should extend to the right boundary of the browser. I've tried using both width:auto and width:100% values for the ...

Angular - The differ is unable to find support for the object 'Item One' which is of type 'string'. NgFor is only able to bind to Iterables like Arrays and not individual objects

Many questions on StackOverflow share similarities with this one, but I have not been able to find a solution that fits my issue. My code functions correctly when attempting to populate items in a "Select" control. It successfully retrieves data if the it ...

Accordions housing Bootstrap 3 pills in a sleek design

I'm working on integrating pills and an accordion in Bootstrap 3. Everything seems to be functioning correctly, but there are a couple of issues I am encountering: When the accordion is open, clicking on another tab closes the accordion. I would li ...

Avoid interrupting the code execution until it has finished completely

Let's discuss a common scenario: $('button').on('click',function(){ // Performing AJAX requests (which may take some time); }); If the user clicks the button multiple times, numerous ajax requests can be triggered. To prev ...

Is there a way to stop these symbols (♈♉♊♋♌♍♎♏♐♑♒♓) from being substituted with emojis?

I am currently working on a project involving the simulation of the Prague Astronomical Clock (). My goal is to display the glyphs representing signs of the zodiac, which are in the Unicode range U+263C-2653 along with other astronomical symbols. My prefe ...