Is the JavaScript click event ineffective for <select> <option>s?

It seems like there's a problem with the code below that is causing it to not work as expected. I'm trying to figure out why the onclick events on the <option>s are not triggering, but everything else seems fine.

function displayInput() {
  document.getElementById('inputField').value = "";
  document.getElementById('inputField').style.display = 'block';
  document.getElementById('lineBreak').style.display = 'block';
}

function hideInput() {
  document.getElementById('inputField').style.display = 'none';
  document.getElementById('lineBreak').style.display = 'none';
}
#inputField {
  display: none;
}
#lineBreak {
  display: none;
}
<select name="" id="dropdown">
  <option value="choose" onclick="hideInput();">Please choose</option>
  <option value="Allure" onclick="hideInput();">Allure</option>
  <option value="Elle" onclick="hideInput();">Elle</option>
  <option value="In-Style" onclick="hideInput();">In-Style</option>
  <option value="other" id="otherOption" onclick="displayInput();">Other</option>
</select>
<input type="text" name="additional_field" id="inputField" placeholder="Other" />
<br id="lineBreak" />

Answer №1

Implement this JavaScript function in your code:

function toggleOther(){
    if (document.getElementById('drop_down').value == 'other') {
         showOther();   
    } else {
         hideOther();   
    }
}

Update your select element like so:

<select name="" id="drop_down" onchange="toggleOther();">
        <option value="choose">Please select</option>
        <option value="Allure">Allure</option>
        <option value="Elle">Elle</option>
        <option value="In-Style">In-Style</option>
        <option value="other">Other</option>
</select>

function toggleOther() {
  if (document.getElementById('drop_down').value == 'other') {
    showOther();
  } else {
    hideOther();
  }
}

function showOther() {
  document.getElementById('other').value = "";
  document.getElementById('other').style.display = 'block';
  document.getElementById('otherBR').style.display = 'block';
}

function hideOther() {
  document.getElementById('other').style.display = 'none';
  document.getElementById('otherBR').style.display = 'none';
}
#other {
  display: none;
}
#otherBr {
  display: none;
}
<select name="" id="drop_down" onchange="toggleOther();">
  <option value="choose">Please select</option>
  <option value="Allure">Allure</option>
  <option value="Elle">Elle</option>
  <option value="In-Style">In-Style</option>
  <option value="other">Other</option>
</select>
<input type="text" name="fields_where" id="other" placeholder="Other" />
<br id="otherBR" />

Answer №2

An example of using JavaScript without jQuery:

The onclick event in the option tag is only supported by Firefox. For a solution that works across all browsers including IE and Chrome, you can utilize the onchange event on your "Select" element.

Here is an example in HTML:

<select name="" id="drop_down" onchange="showHideOther(this.value);">
    <option value="choose">Please choose</option>
    <option value="Allure">Allure</option>
    <option value="Elle">Elle</option>
    <option value="In-Style">In-Style</option>
    <option value="other" id="otherOption">Other</option>
</select>

Including the following JS code in the html head section as a script:

function showHideOther(value){
    alert(value);
    if (value==='other'){
        document.getElementById('other').value = "";
        document.getElementById('other').style.display = 'block'; 
        document.getElementById('otherBR').style.display = 'block';
    }
    else{
            document.getElementById('other').style.display = 'none'; 
            document.getElementById('otherBR').style.display = 'none';
    }
}

A working example on JSFiddle: http://jsfiddle.net/amontellano/gLML3/14/

I hope this information is useful.

Answer №3

VIEW DEMO

var dropdownList = document.getElementById('drop_down'); 

dropdownList.onchange = function() { 
  var selectedOption = dropdownList.options[dropdownList.selectedIndex].value; 

  switch(selectedOption) {
    case 'other':
      document.getElementById('other').value = "";
      document.getElementById('other').style.display = 'block'; 
      document.getElementById('otherBR').style.display = 'block';
      break;
    default:
      document.getElementById('other').style.display = 'none'; 
      document.getElementById('otherBR').style.display = 'none';
      break;
  }
}

Answer №4

To integrate this functionality into your existing code, simply include the following functions:

$('#drop_down').on('change', function(){
    ($(this).val() == 'other') ? displayOther() : hideAdditional();
});

You can view a live example of this implementation here: http://jsfiddle.net/gLML3/7/

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

How can Angular prevent displaying 404 errors in the console by utilizing fallback mechanisms?

I have implemented a custom directive that loads a backup image source if the initial one returns a 404 error. Here is the code for the directive: .directive('errSrc', function() { return { link: function(scope, element, attrs) { ...

A method using JQuery and Javascript to retrieve Highcharts data in JSON format, properly structured, by leveraging Selenium with C# programming

I am currently working on extracting the JSON equivalent of a highchart graph using Selenium and C# but have encountered a few obstacles along the way. To retrieve the JSON data for a specific highchart, follow these steps: Visit the URL Log in using th ...

Creating a user-friendly form in a Nuxt/Vue application that enables dynamic attribute creation

I am currently working on designing a form that enables users to create different variations for a product within a Nuxt/Vue application. The goal is to provide users with the ability to specify attributes for each variation using a text field. These attr ...

Alignment dilemmas

I'm experimenting with HTML and CSS and have a query concerning the text-align properties. As I work on constructing my personal website, I aim to align text content to start while having it centered in the middle of the page. Currently, I've ma ...

I am unable to utilize the map function as it results in a TypeError: The property 'map' is undefined and cannot be read

I recently delved into the world of "REACT" in order to work on the front-end of my own project. I encountered a problem for 2 days with the map function while getting data from my back-end and saving the IDs in the Cuartos array. I couldn't figure ou ...

Updating the navigation with a dynamic CSS class using jQuery

Hey there, I'm on the lookout for a simple and discreet method to dynamically add an "active" class to a navigation menu based on the current directory. Unfortunately, I am unable to modify the body tag with a custom class, ruling out a pure CSS solut ...

Adjust the vertical position of the image with HTML and CSS

I want to adjust the positioning of the image below the blue navigation bar so that it aligns with the main content area below, creating the appearance of a shaded box around the webpage's content. The image in question is boy_top.png. Is there a way ...

Retrieving the most recent HTML bookmark that was clicked

Is there a way to retrieve the most recently clicked html bookmark using javascript/jquery? Here is the html code: <a href="#div1">div1</a> <a href="#div2">div2</a> and the content of DIV1: <div id="div1"> DIV 1 - Lore ...

Can anyone guide me on how to retrieve a popup validation message on a webpage using Selenium with Python?

Is there a way to use Selenium Python to trigger the popup validation message "Please tick this box if you want to continue" shown in the image? <input oninvalid="this.setCustomValidity('Please tick this box if you want to proceed')" onin ...

Issue with BootstrapValidator preventing successful submission of Ajax form with a confirmation message

Working on submitting a form with AJAX using jQuery and validating it with bootstrapValidator. Currently facing issues with getting a success message upon form submission. The form submits without validation, but the success message is missing. When using ...

Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet: ngOnInit(): void { this.categories = this.categoryService.getCategories(); var example = this.categories.flatMap((categor) => categor.map((categories) = ...

When trying to install express using Node.js npm, an error message 'CERT_UNTRUSTED' is preventing the installation of express

My goal is to set up express on Raspberry Pi for the purpose of using it in a REST API. However, I keep encountering an issue with SSL certification when trying to install it through npm. Despite attempting various solutions found on different forums, I ha ...

How can we set up Node JS to automatically trigger events when a specific future date and time from the database is reached?

I have taken on the challenge of providing users with a feature where they can select a date and time in the near future while placing an order. This chosen time and date will be saved in the database. How can I set up a function to automatically execute ...

Do not activate hover on the children of parents using triggers

Check out my demonstration here: http://jsfiddle.net/x01heLm2/ I am trying to achieve two goals with this code. Goal number one is to have the mini thumbnail still appear when hovering over the .box element. However, I do not want the hover event to be tr ...

Exploring the functionality of the onblur HTML attribute in conjunction with JavaScript's ability to trigger a

How do the HTML attribute onblur and jQuery event .trigger("blur") interact? Will both events be executed, with JavaScript this.trigger("blur") triggering first before the HTML attribute onblur, or will only one event fire? I am using ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...

I've been struggling with this javascript error for three days, how can I finally resolve it?

Currently developing a website using react js, but encountering an error every time I try to push to my github repository. Run npm run lint npm run lint shell: /bin/bash -e {0} <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

The tooltip in Amcharts malfunctions when incorporating the DurationAxis

I've been grappling with getting tooltips to work in amCharts4 when using a DurationAxis(). It seems like there might be a bug, as the tooltips sometimes get stuck in the top left corner. Here's an example: https://jsfiddle.net/jamiegau/fpye3bkv ...

The iOS website won't fully load until the button is tapped two times

- (IBAction)saveButton:(id)sender { NSURL *yourWebURL = [NSURL URLWithString: webpageURLLabel.text ]; NSURLRequest *webRequest = [[NSURLRequest alloc] initWithURL:yourWebURL]; if ([self checkIfValidURL] == YES) { [webpagePreview loadReq ...

How can the threejs Box3().getSize() method be effectively utilized?

There seems to be a discrepancy in the proper usage of the Box3() getSize() method, as discussed on various platforms including stackoverflow. const geometry = new THREE.BoxGeometry( 10, 10, 10 ); const material = new THREE.MeshBasicMaterial( {color: 0x00f ...