The default choice vanishes once a non-empty option is chosen

Here is a simple example illustrating my issue: JSFiddle.

Initially, I have an empty/default option, but when I select something else from the drop-down, this default option disappears.

How can I keep this default option visible after making a selection?

<label for="mySelect">Make a choice:</label>
 <select name="mySelect" id="mySelect"
      ng-options="option.name for option in data.availableOptions"
      ng-model="data.selectedOption"></select>

Angular-controller:

.controller('ExampleController', ['$scope', function($scope) {
   $scope.data = {
    availableOptions: [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ],
    selectedOption: {id: '2', name: 'Option B'} //This sets the default value of the select in the UI
    };

I attempted to use ng-init to set the default option to null, but unfortunately, it didn't work as expected.

Answer №1

Make sure to include an empty option element within the select element.

 <select name="mySelection" id="mySelection"
  ng-options="option.name for option in data.availableChoices"
  ng-model="data.selectedChoice">
    <option></option>
  </select>

Answer №2

Follow these steps:

HTML

<div ng-app="customDefaultValueSelect">
  <div ng-controller="CustomExampleController">
  <form name="myForm">
    <label for="mySelect">Choose an option:</label>
    <select name="mySelect" id="mySelect"
      ng-options="opt.value as opt.name for opt in data.selectOptions"
      ng-model="data.selectedOpt"></select>
  </form>
  <hr>
  <tt>selected option = {{data.selectedOpt}}</tt><br/>
</div>

AngularJS

angular.module('customDefaultValueSelect', [])
 .controller('CustomExampleController', ['$scope', function($scope) {
   $scope.data = {
    selectOptions: [
      {value: '1', name: 'Option X'},
      {value: '2', name: 'Option Y'},
      {value: '3', name: 'Option Z'}
    ],
    selectedOpt: '2' //This defines the default value for the select element
    };

}]);

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

Issues encountered when using Three.js raycasting to position objects above a plane

My heightmap-based plane is not working with raycasting, and I'm also having trouble placing an object above the hovered triangle. UPDATE: By commenting out the height section (pgeo.vertices[i].z = heightmap[i] * 5;), it seems to work inconsistently. ...

The focusable attribute in SVG is malfunctioning

I've utilized the focusable attribute to ensure SVG elements receive focus within an HTML document. My goal is to navigate through SVG elements in the SVG tag using the TAB key, as indicated in this resource (http://www.w3.org/TR/SVGTiny12/interact.h ...

What is the best way to link this information to access the data attribute?

Currently, I am looking to streamline the data retrieved from firebase so that it can be easily displayed in a FlatList component. How can I transform my data into a simple array that can be iterated over in the FlatList? UPDATE! I have multiple other coi ...

Styling images and text in CSS within a jQuery UI autocomplete widget

I am currently using an autocomplete widget that displays text along with images. The results I have right now are not meeting my requirements. I want to customize the appearance of my results so that the words 'test' and either 'Federico&a ...

Encountering Err_Connection_Refused while working with MVC WebAPI 2 and AngularJS

Seeking guidance on WebAPI, AngularJS, and .NET Authentication, I am currently following a tutorial mentioned HERE. The tutorial is brief (~under 10 mins), but I encountered an error stating Failed to load resource: net::ERR_CONNECTION_REFUSED. Typically, ...

Is there a way to change a weather api into local time using ReactJS/JavaScript?

In order to display time in a specific format like 12:00 or 20:00 and change the background with images, I need to convert it to local time. This is essential for achieving my desired output. The JSON data structure that I am working with looks as follow ...

I encountered an issue when trying to launch my React application, as the CMD displayed an npm error message stating 'npm error! missing script:start'. Can someone offer assistance with this problem?

view image details Despite spending countless hours searching through past responses and attempting to resolve this issue, I have been unsuccessful. Upon entering 'npm create-react-app' in the terminal and navigating to the correct directory, I ...

Fade out a dynamically loaded content block using jQuery

I am currently developing a small app and encountering issues with deleting (fading out) dynamically loaded div elements using jQuery. The problem occurs when adding a new content box. If the page is reloaded and the content box is rendered normally (from ...

What is the solution to resolving the problem indicated by the error message "at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"?

I encountered an issue while attempting to send a token to the user for password reset. The error message I received is as follows: Error: there was an error sending the email, try again later at exports.forgotPassword (C:\\Users\\Abdur ...

When using `parseInt` on the string "802.11 auth", the result did not match my expectations

I am developing a data parser that transforms the output of a command into a JSON object for sending to a live logging and graphing platform. All data extracted by the parser is returned as strings, but I need numerical values to be preserved as numbers. H ...

Is there a way to determine if a JavaScript method is compatible with my current Node.js version?

Looking to implement the reduce() method in my Node.js application, but I'm unsure if it's compatible with my current version 4.2.6. Is there a way to safely determine if I can use this method without causing any issues? Appreciate any help on t ...

Troubleshooting compatibility issues between AngularJS and a rails_api in a production environment

I have a Rails API and I've placed my angularjs index.html file, along with its entire directory structure, into the public folder of my API. It works perfectly in development environment, but when I try to run it in production, I get a 404 error in t ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Fixed position scrollable tabs with Material UI

I recently implemented material-ui scrollable tabs in my project, referencing the documentation at https://mui.com/material-ui/react-tabs/#scrollable-tabs. Here is a snippet of the code I used: <Tabs value={value} onChange={handleChange ...

Error: Your Discord bot is unable to send a message as it is empty. Please check Discord

I have been developing a Discord Bot to verify Roblox accounts. Although my script is prepared and the command "-verify" can be executed, an error arises: (node:22872) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use `n ...

Is there a way to dynamically apply the "active" class to a Vue component when it is clicked?

Here is the structure of my Vue component: Vue.component('list-category', { template: "#lc", props: ['data', 'category', 'search'], data() { return { open: false, categoryId: this.category ...

Query modifier contains an unexpected token ":"

For my API project, I have opted to use sailsjs as my framework. The documentation at provides a list of query modifiers that can be used. User.find({ or: [ name: { startsWith: 'thelas' }, email: { startsWith: 'thelas' } ] ...

Customize your error messages in AJAX requests

The form on my index.php page submits to process.php, triggering the execution of the code below: $(document).ready(function() { $('#login_button').click(function() { event.preventDefault(); var formData = { 'email' ...

Why does xpath insist on choosing spaces instead of actual elements?

Here is a list of countries in XML format: <countries> <country> <code>CA</code> <name>Canada</name> </country> ... etc... </countries> I am looking to extract and loop through these nodes, so ...

Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object: var o = { prop: 3, method: function() {return this.prop} } My expectation was that calling (o.method)() would result in undefined, but instead it returned 3, indicating that the reference of this ...