Printing paths of nested options is incomplete

Is there a way to display the full path of a select with nested options in angular? When I click on an option, currently it only shows the option value.

<select>
    <optgroup label="A">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </optgroup>
    <optgroup label="B">
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </optgroup>
</select>

For example, if I select option 5, the default select will only show "5". Is there a way to make it show "B / 5" instead?

Answer №1

Although I'm not entirely sure of the correct method, I have devised a workaround.

$(function()
{
   $('select').change(changed);
});

function changed()
{   

    var y = $(this).val();
    
    var x = $($($($(this).find("option")).filter(function() {return $(this).text() === y;})).parent()).attr('label');
    console.log(x);
    
    $('#test').text(x + ' / ' + y);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
    <optgroup label="A">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </optgroup>
    <optgroup label="B">
        <option>4</option>
        <option>5</option>
        <option>6</option>
    </optgroup>
</select>
<div id="test"></div>

In simple terms, we first store the selected value in variable y. Then, we search for the children of the select input $(this).find("option"), filter it to find the option with text matching the chosen one

$($(this).find("option")).filter(function() {return $(this).text() === y;})
, and then select its parent (the optgroup) to retrieve the value of its label.

Answer №2

To accomplish this, you can use a directive:

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script>
        var app = angular.module('myapp', []);

        app.directive('getVal', function () {
            return function (scope, ele) {
                var element = angular.element(ele);

                element.change(function (e) {
                    var y = element.val();
                    var selected = angular.element(':selected', element);
                    var optionLabel = selected.closest('optgroup').attr('label');

                    angular.element('#output').text(optionLabel + ' / ' + y);
                });
            };
        });
    </script>
    <body ng-app="myapp">
        <select get-val>
            <optgroup label="A">
                <option>1</option>
                <option>2</option>
                <option>3</option>
            </optgroup>
            <optgroup label="B">
                <option>4</option>
                <option>5</option>
                <option>6</option>
            </optgroup>
        </select>

        <div id="output"></div>
    </body>
</html>

When selecting 5, the output will be "B / 5".

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

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

The displayed value in the text field remains constant even when the object's attribute is modified

My issue involves the Date Text Field component of Material UI. Whenever I pass an attribute from an object, the displayed value in the Text Field does not update even when the object attribute changes. const [data, setData] = useState({ title: new Da ...

What is the method to define a function in express js that is accessible from all views?

Is there a way to develop a function within my Express JS MVC web application that can be accessed from any view? How can I define this function in middleware so it can be directly called from a view? I envision being able to use this function like: < ...

My AJAX function is not functioning as intended

I'm currently developing a time management system for my workplace. As I was coding, I implemented a feature that allows users to configure the database details similar to the setup process in WordPress. Once the data is saved successfully, I aim to d ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

Is there a way to direct the user's cursor to a specific location on the page when they hover over an image?

I'm interested in creating a script that can manipulate the user's mouse position when they hover over an image. For example, if I hover over the image, I want the mouse to be dragged lower towards a specific text. Is there a method to achieve th ...

Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field: <template> <div class="col-l-4"> <p style="text-align: center">Data/day (GB)</p> <div class="form-input-set" style="background: white"& ...

Tips on extracting information from several JSON response objects

I have the following ArrayList: JSONArray JMyDataList= new JSONArray(MyDataList); JSONArray JMyProjectData = new JSONArray(MyProjectData); MyDataList: contains data retrieved from a database with column names and data. response.setConten ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...

I am experiencing an issue with my jQuery loop code not functioning properly when using the .each method within the loop

I am struggling with the following code. <input type="text" name="1" class = "inp<?=$p?>"> <input type="text" name="2" class = "inp<?=$p?>"> <input type="text" name="3" class = "inp<?=$p?>"> <input type="text" na ...

Utilizing $templateCache with ui-router and minifying in AngularJS 1.x

Posting this as a question-answer post. How can one effectively utilize the $templateCache in the templateProvider of a route within ui-router when attempting to refactor the code? Injection is ineffective, and Angular cannot inject by reference. For ins ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

Using Angularjs and PHP: incorporating URL parameters into the $http.get() function

I am currently working on a web project in Eclipse with three main files: "controller.js", "home.html," and "array.php". The goal is for the .php file to echo a PHP array encoded in a JSON string: <?php $arr = array(array(title => "hello", auth ...

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 ...

What are some ways to personalize a scrollbar?

I am looking to customize the scrollbar within a div. I attempted to modify it using the code below, but I encountered difficulties when trying to change the scroll buttons and did not achieve my desired outcome. Additionally, this customization did not wo ...

Incorporating AngularJS Controller to Render Asp.Net MVC 5 View

I am attempting to navigate to the Home page once a user successfully logs in. My current tech stack includes ASP.NET MVC 5, AngularJS, EntityFramework 6, Bootstrap, and repository pattern. Below is the code snippet from my LoginController: public JsonRes ...

Resolving a request timeout: Steps to fix the issue

In the process of developing an API for uploading and processing large Excel files with validation before dumping the data into a database, I have encountered an issue. Whenever I attempt to upload a large file, I receive a Gateway Timeout 504 error. Is ...

Puppeteer and Chromium are ready to go with no need for any configuration

I have a specific HTTP request that I am trying to intercept, but I am encountering issues when chromium is launched through puppeteer. Some flags seem to be causing the requests to not return the expected data. However, everything works fine when I manual ...

Unable to include an additional parameter within a JavaScript function

I'm having trouble adding a parameter to the Openpopup() function - every time I try, I get an error. Can someone help me out with this? Thanks in advance. return "<a onclick='return Openpopup()' class='btn btn-info btn-lg clickBtn& ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...