Adding a text field on top of a div based on the dropdown value selection

I am working with a dropdown option inside a div. I want to make it so that when the last option is selected, a text box will appear on top of the dropdown. And when a different option is selected, the text box should be disabled. How can I achieve this?

Below is the code snippet I currently have:

<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
  <div class="form-group">
   <select class="form-control input-sm" name="opt_change" >
      <option>Mustard</option>
      <option>Ketchup</option>
      <option>Relish</option>
   </select>
  </div>
</div>

Answer №1

$(this).find('option:selected').text()
will give you the selected option's text

Give this a shot:

$('[name="opt_change"]').on('change', function() {
  if ($(this).find('option:selected').text() == 'Relish') {
    $('#other').show().prop('disabled', false);
  } else {
    $('#other').prop('disabled', true);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id='other' style='display:none'>
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
  <div class="form-group">
    <select class="form-control" name="opt_change">
      <option>Mustard</option>
      <option>Ketchup</option>
      <option>Relish</option>
    </select>
  </div>
</div>

Edit: To check if the last option is selected, use

$(this).find('option:last').prop('selected')
in the if statement

Answer №2

Take a look at this solution that incorporates bootstrap (if you're using it) and jQuery:

http://codepen.io/anon/pen/JGVQNb

JS:

$("div").on("change", "select[name='opt_change']", function() {
  var theLastOption = $("select[name='opt_change'] option:last-child");
  if (theLastOption.is(':selected')) {
    $("#text-box").show();  
  } else {
    $("#text-box").hide();  
  }
});

HTML:

<div class="row">
  <div id="text-box" class="col-xs-6  col-md-offset-1 collapse">
    Hey there! I'm here.
  </div>
</div>
<div class="row">
  <div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
    <div class="form-group">
      <select class="form-control input-sm" name="opt_change">
        <option>Mustard</option>
        <option>Ketchup</option>
        <option>Relish</option>
      </select>
    </div>
  </div>
</div>

Answer №3

If you want to achieve this, you can compare the last option value with the selected value like this:

$("select").change(function () {
    var last = $(this).find('option:last').val();
    var sel = $(this).val();

    if (last == sel) {
        var input = $(this).prev('input[type=text]');
        input.length == 0 ? $(this).before('<input type=text />') : input.prop('disabled', false);
    } else {
        $(this).prev('input[type=text]').prop('disabled', true);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
    <select class="form-control">
        <option>Mustard</option>
        <option>Ketchup</option>
        <option>Relish</option>
    </select>
</div>

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

node.js: The Yahoo weather jQuery plugin fails to display any data

After successfully implementing node.js with jQuery and the plugin from , I now aim to utilize the weather data for a different purpose rather than directly inserting it into the HTML. However, I am encountering difficulties in accessing or displaying the ...

Guide on submitting a form using a custom AJAX function based on the id or class parameter

Instead of writing an ajax call every time with changing API URL, post method, and form id or class name based on the page, I am attempting to develop a custom function that can manage the API call based on the provided parameters. The essential parameters ...

PHP and jQuery: tackling quotation mark problems in output

Need help with PHP output: $this->Js->buffer(" var searchTerm = $(this).html(); var searchId = $(this).attr('data-tag'); $('.tags').append('<input type='text' value='+searchTerm+' name=&apo ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...

How can I execute route-specific middleware in advance of param middleware in Express v4?

Let me share a unique situation in my routing setup where I need to trigger a middleware before the parameter middleware is executed: router.param('foo', function (req, res, next, param) { // Accessing the param value ... next() }) router ...

The controller remains unresponsive when attempting to activate the button on the webpage

I'm a beginner in frontend development and I'm currently working on a website that uses Thymeleaf. On this website, there is a div block with a button. Please take a look at the HTML code below, specifically the button at the last three rows. &l ...

Monitor modifications to documents and their respective sub-collections in Firebase Cloud Functions

Is it possible to run a function when there is a change in either a document within the parent collection or a document within one of its subcollections? I have tried using the code provided in the Firebase documentation, but it only triggers when a docume ...

Utilize jQuery post to send a request to a particular function located at a given URL

Is there a way to accomplish the following: $.post( "functions.php", { name: "John", time: "2pm" }) .done(function( data ) { alert( "Data Loaded: " + data ); }); Instead, is it possible to direct your data to a particular function in "functions.p ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

What is causing the bullets for the unordered list to appear before the items are inserted into the list?

Can you explain why the bullets are showing up before the list items are added? <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>To Do List</title> </head> <body> ...

The css-loader is missing the required dependency peer Webpack5, causing a resolution error

Recently, I've ventured into the world of JavaScript and I'm looking to incorporate vue-audio-visual into my project. However, I encountered a perplexing error in my node console that seems unrelated. The npm error message reads as follows: code ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

What is the best way to activate a JQ function with my submit button?

Is there a way to trigger a JQ function when clicking the submit button in a form? I managed to make Dreamweaver initiate an entire JS file, but not a particular function. ...

Automatically clear out table rows once the maximum row limit is reached, then append new data using the WebSocket data in JavaScript

Recently, I delved into JavaScript and faced a dilemma with my Bitcoin Price update dashboard. The data is streaming in through an external WebSocket, updating the prices every second. But here's the catch - the table rows are going crazy! To maintain ...

HTML5 Division Element Dimensions

I am currently modifying an HTML5 template. The default Bootstrap parameters were set as: col-sm-12 col-md-4 col-lg-4 col-sm-12 col-md-8 col-lg-8 This configuration allotted 20% of the screen width to text and 80% to images, but I want it reversed. Tex ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

Utilizing jQuery to load HTML content into a div restricts my ability to navigate back and forth seamlessly

I am new to jquery and currently working on my first project. In my index.php file, I have included: header.html indexview.html footer.html. The indexview.html file consists of two divs - one for the menu on the left and another (div id="content") f ...

verify whether the image source has been altered

There is an img tag displaying the user's avatar. When they click a button to edit the image and choose a new one, the src attribute of the img changes to the new image src. How can I detect when the src changes? Below is the code for the button tha ...