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

Arrange data in JSON file based on job title (role name) category

My current code successfully outputs data from a JSON file, but I'm looking to enhance it by organizing the output based on the "Role Name". For example, individuals with the role of Associate Editor should have their information displayed in one sect ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...

In Node.js, I encountered an issue where req.body was returning as undefined, despite the fact that when I logged req, I could

I am having trouble logging the req.body to the console in my Twilio text app. When I try console.log(req), the body and its contents show up, but it says that the body is undefined when I try to log it on its own. Any help would be greatly appreciated. ...

The matMul function encountered an error due to a mismatch in the inner shapes of the Tensors. The shapes provided were 684,1 and 2,1, and the transposeA and transposeB parameters were both set

I am completely new to the world of AI and tensorflow.js. Currently, I am following a Machine Learning course by Stephen Grider. I was expecting an output after running the code below, but instead, I encountered an error. Can someone please assist me? Her ...

What is the best way to create a sequential number pattern of 1, 2, 3, 4 in Mongoose?

Is there a way to create a similar pattern without coding experience? I'm not familiar with coding, so looking for guidance. Here is the code snippet in question: array = 1,2,3,4,5 const note = new notedModel ({ _id: array, note: args[1] ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

Guide on setting up a shortcut key for an input field

Currently, I have a collection of images each with its own HTML page. I added an input button that when clicked, takes you to the next image. However, I would like to enhance user experience by allowing them to use keyboard arrows for navigation. Being new ...

Pass data from JavaScript to PHP using AJAX

Using Leaflet to display a map, I have incorporated ajax into my onEachFeature function in order to retrieve variables to pass to PHP. Here is the code snippet: function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.IDLo); layer. ...

Using Next.js: What is the process for dynamically registering the quill-blot-formatter to react-quill that has been imported on the client side rendering exclusively

Currently, I am dynamically importing the react-quill library on the client side only by setting ssr: false. My functional component is functioning properly, but I now want to integrate the quill-blot-formatter package into the modules section of my quill ...

Getting to grips with accessing HTML elements within a form

<form name="vesselForm" novalidate> <input type="text" id="owner" name="ownerEdit" required ng-blur="vesselForm.btnCC.attr('value', 'Change Customer')"/> <input type="button" name="btnCC" value="Customer" /> </fo ...

The user score tracking database, cataloging personal scoring history

In my database, I have a table called User. Each user in this table has a field named score. I am looking to display how the score of each user has evolved over time. My dilemma is whether to store this score separately. Should I create a new database t ...

mongodb cannot locate the schema method within the nested container

Trying to access a method of a schema stored inside a mixed container has presented a challenge. The scenario is as follows: var CaseSchema = mongoose.Schema({ caseContent : {}, object : {type:String, default : "null"}, collision : {type : Boo ...

issues encountered with sending a multidimensional array using ajax, specifically with the index[0]

I'm struggling with sending a multidimensional array from PHP to Javascript/jQuery, encountering a peculiar issue. Upon transmitting index 0 through json_encode($array);, the desired response format is successfully received by the client: [[0,0],[1, ...

After the decimal point, there are two digits

My input field is disabled, where the result should be displayed as a product of "Quantity" and "Price" columns ("Quantity" * "Price" = "Total"). However, I am facing an issue where the result often displays more than 2 digits (for example: 3 * 2.93), desp ...

Switch out the specific content within the p tag

Looking to update the highlighted text within a p tag. The code below addresses handling new line characters, but for some reason the replacement is not working as expected. Check out the HTML snippet: <p id="1-pagedata"> (d) 3 sdsdsd random: Subj ...

Looking for jQuery bbq... is the grill fired up yet?

In my exploration of the jQuery bbq plugin, I noticed that there is no reference to document.hash in the code. I believe that the function for retrieving the hash is located at line 1094: function get_fragment( url ) { url = url || location.href; ...

Is it possible to transfer .NET backend functions to a frontend framework like React or Vue for client-side execution?

For instance, imagine a scenario where there is a login page requiring a username and password to meet specific criteria for validation: the username must contain a capital 'A' and the password should be exactly 8 characters long. The challenge l ...

Repeater employs Endless Scrolling feature within DotNetNuke

I've integrated DotNetNuke into my custom module and I'm following the standard ASP.NET programming techniques (dragging/dropping). The project involves a posting service that uses a repeater with infinite scrolling and a masonry effect. I have f ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

Angular 2 Typeface Delivery to the Server

I'm experiencing an issue with the font when trying to access it from the server. It works fine on localhost, but on the server with a different directory structure, it fails to load properly. The same problem occurs with the logo as well. @font-face ...