What is the method for retrieving the chosen option from a dropdown menu?

I'm currently working on an angularjs form where I need to pass definition.clazz to a js function. In my controller, I have the following js function:

$scope.createData=function(clazz){
// do stuff
}

Below is a snippet of the form:

<select  class="form-control" id="type" name="type" ng-model="definition.clazz">
    <option value="PrimitiveType" 
            ng-selected="type.type=='PRIMITIVE'">
        PrimitiveType
    </option>
    <option value="EnumerationType"
            ng-selected="type.type=='ENUM'">
        EnumerationType
    </option>
</select> 
<button type="button" 
        class="btn btn-primary"
        ng-click="createData(definition.clazz)">
    Create Data   
</button>

However, when I click the "Create Data" button, the ng-model is not set and even printing definition.clazz in console log shows nothing. How can I retrieve the selected value from the select element? Any help would be appreciated.

Answer №1

Perhaps you should consider utilizing ng-options as an alternative approach. It is likely that ng-model necessitates its use within the select element.

Answer №2

Give this a shot:

<select class="form-control" 
          id="type" 
          name="type" 
          ng-model="definition.clazz" 
          ng-options="option in ['PrimitiveType','EnumerationType']">  

</select>

Answer №3

Hello @Pracede, do you believe this solution is the one you're aiming for?

Check out how the ng-model value appears in the console:

 

       var app = angular.module("app", []).controller('appCtrl', ['$scope',
          function($scope) {
            //$scope.type ={type="PRIMITIVE"}; // the tricky part?
            
            $scope.type = {};
            $scope.type.type="";
               
            $scope.createData = function(clazz) {
    if(clazz==undefined)
      {
        console.log("SELECT THE TYPE");
        return;
      }              

if(clazz=='PrimitiveType')
              {
                 $scope.type.type='PRIMITIVE';
                 console.log(clazz +  ' ' + $scope.type.type); 
              }
              else
              {
                $scope.type.type='ENUM';
                console.log(clazz +  ' ' + $scope.type.type);
              }    
    }
      }
    ]);
   

  <!DOCTYPE html>
    <html ng-app="app"> 
    <head>
      <title></title>
    </head>
    
    <body ng-controller="appCtrl"> 
      <select class="form-control" id="type" name="type" ng-model="definition.clazz">
<!--<option value="PrimitiveType" ng-selected="type.type=='PRIMITIVE'">PrimitiveType</option>
    <option value="EnumerationType" ng-selected="type.type=='ENUM'">EnumerationType</option>-->
        <option value="PrimitiveType">PrimitiveType</option>
        <option value="EnumerationType">EnumerationType</option>
      </select>
      <button type="button" class="btn btn-primary" ng-click="createData(definition.clazz)">
        Create Data
      </button>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    </body>   
    </html>

UPDATE: For more guidance, check out similar issues on SO: How does ng-selected work? Updating model with ng-options and ng-selected

This approach reflects my perspective and offers a potential solution to your dilemma.

You have the flexibility to adjust the type based on the option's value and determine the type within the controller's function. Thus, the use of ng-selected may not be necessary in this context (in my view).

I trust this additional insight will help propel you forward.

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

Steps to resolve the Uncaught SyntaxError: Unexpected token o in JSON at position 1 issue

$.ajax({ url: "/url/url.ajax?length=100000&startDate=2018-07-01", method: "get", dataType: "json", success: function (jdata) { var jsonData=JSON.parse(jdata.data); ...

Whenever I refresh my website after deployment, I encounter an empty error using the MERN stack

Here is a question I previously posted: How can I properly use the res.sendFile for my MERN APP, as I encounter an error every time I refresh, and it was resolved there. I encountered a similar issue here, even after following the same steps that worked b ...

Extract the necessary fields from the JSON Schema

I am in search of a solution to extract the required fields from a JSON Schema and Data combination. Currently, we are utilizing AJV for getting error messages in our forms using JSON Schema, and it has been performing really well. I am looking for a met ...

Is there a way to program JavaScript to automatically close a webpage?

Despite encountering similar questions on different forums, I have yet to find a solution that resolves my specific issue. In essence, I am looking to open a URL via the command prompt which will launch a browser, navigate to a webpage, and then automatic ...

What is the best way to display data retrieved from an API in HTML using handlebars?

I am facing an issue with rendering API data obtained from a GET request and displaying it on my website using handlebars. The data includes an image and a description. Below is the snippet of code in my index.js: var express = require('express' ...

Is there a way to send me the result of the radio input (Yes/No) via email?

Is it feasible to send the results of a radio input (Yes/No) back to my email directly using HTML, CSS, and Javascript? ...

Overlapping pinned columns in ng-grid

I designed a view using ng-Grid where I pinned the first three columns. However, when scrolling in the unpinned 4th column, it appears under the pinned headers. I suspect this may be due to a z-index problem somewhere in the code. (I specified a custom hea ...

Node.js is having trouble locating a module that has been installed

Upon transferring my node.js application to a different PC (where it functioned flawlessly on the development machine) and manually installing all the necessary dependencies, I encountered an error when attempting to run it: C:\Users\myself>n ...

Tips for concealing the background HDR map display in three.js without compromising the HDRI's contribution to the lighting effects

In my code, I have implemented the following example: Source: https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_gltf.html#L53 While HDRI lighting works perfectly, I am struggling to hide the HDR map from the background. Is there a way ...

What is the best way to align an InputAdornment IconButton with an OutlinedInput in Material-UI?

Struggling to replicate a text input from a mockup using Material-UI components. Initially tried rendering a button next to the input, but it didn't match. Moving on to InputAdornments, getting closer but can't get the button flush with the input ...

Transmit a document via ajax jquery and retrieve it on the server side with Flask

I am currently working on sending a file using ajax jquery from the front end. HTML <label>Upload File </label> <form method='post' enctype="multipart/form-data"> <input type='file' id='uploade ...

Tips for retrieving values from CheckBox in Asp.net MVC using Jquery

I'm currently facing a dilemma while working on an MVC web application. I have dynamically generated checkboxes from my database, but I am uncertain about how to extract the value of the selected checkbox and store it in the database. Any suggestions? ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Is it true that the Spring MVC <input:form> does not support the use of the name attribute? This limitation could potentially pose challenges when utilizing javascript document.getElementsByName

Check out my Spring MVC JSP snippet below: <c:forEach var="trackRecord" varStatus = "number" items="${contractDetails.trackRecordEntries}" > <tr class="tafont"> <td class="varcar"><form:input readonly = "true" name = "install ...

Create a form that calculates results using user-inputted values

I am currently developing a Cardio Test calculator that assesses the risk of heart attacks. My aim is to assign a score-based value for each input provided. The algorithm for generating results is already functional, I just need assistance in obtaining the ...

Adjusting size of a div as you scroll - Java Script

Using the codepen provided at http://codepen.io/anon/pen/fDqdJ, I am looking to enhance the functionality by implementing a feature where, upon reaching a specific distance from the top of the page, an already animated div undergoes a change in scale while ...

"Implementation of clearInterval function may not always result in clearing the interval

The scrolling process within the div element flows smoothly in both directions, however, it seems to encounter an issue when executing the scrollBack() function. Despite including a clearInterval() statement at the intended point, the interval does not a ...

Node.js display a comprehensive list of currently active threads

Currently, I am diving into the world of synchronous and asynchronous writing in node.js. With curiosity driving me, I decided to explore all active threads while experimenting with writing a random line to a txt file using fs.writeFile(). Any insights o ...

Tips for implementing validation in a multi-step form as outlined in w3schools tutorial

I came across a multistep form creation tutorial on w3schools. However, the tutorial only covers generic validation (checking if a field is empty), which is not sufficient for my needs. How can I implement HTML validation (e.g., min, max, length) for text ...

Tips for choosing the default tab on Bootstrap

I have a question about an issue I am facing with my Angular Bootstrap UI implementation. Here is the code snippet: <div class="container" ng-controller='sCtrl'> <tabset id='tabs'> <tab heading="Title1"> ...