Encountering a problem with fetching data in a dropdown using a hidden select in MVC 4 Razor and Selectpicker

I need to show my hidden select data in dropdown-menu inner selectpicker ul with the default "--choose--" option selected.

ASP.NET MVC Razor Syntax

 @Html.DropDownListFor(model => model.BrandName, Model.CompanyItems, "--Choose Brand--", new { @id = "Brand", @class = "select", required = "required" })

Displaying the result in the Model Name

@Html.DropDownListFor(model => model.ModelName, Model.ModelItems, "--Choose Model--", new { @id = "ModelName", @class = "select", required = "required" })

HTML Result displayed in a Hidden Select in the Browser

<select class="select" data-val="true" data-val-required="Please Choose Model Name." id="Model" name="ModelName" style="display: none;">
  <option value="AQUA i5 HD">AQUA i5 HD</option>
  <option value="Intex AQUA FISH">Intex AQUA FISH</option>
  <option value="Intex AQUA ACE">Intex AQUA ACE</option>
  <option value="Intex AQUA CRAZE">Intex AQUA CRAZE</option>
</select>

Displaying the result in a Hidden Select with option Value="" in ul li

<div class="dropdown-menu open" style="max-height: 107px; overflow: hidden; min-height: 0px;">
  <ul class="dropdown-menu inner selectpicker" role="menu" style="max-height: 105px; overflow-y: auto; min-height: 0px;">
    <li rel="0" class=""><a tabindex="0" class="" style=""><span class="text">--Choose Model--</span><i class="glyphicon glyphicon-ok icon-ok check-mark"></i></a></li>
  </ul>
</div>

JavaScript code for populating hidden Select values

$(document).ready(function() {
  $("#Brand").change(function() {
    $("#Model").empty();
    var v = $(this).val();
    $.getJSON('@Url.Action("GetModelNames")?Brand=' + v, function(data) {
      $.each(data.ModelItems, function(a, b) {
        var option = '<option value="' + b.Value + '">' + b.Text + '</option>';
        $("#Model").append(option);
      });
    });
  });
});

How can I customize

<ul class="dropdown-menu inner selectpicker" role="menu" style="max-height: 105px; overflow-y: auto; min-height: 0px;">
  <li rel="0" class=""><a tabindex="0" class="" style=""><span class="text">--Choose Model--</span><i class="glyphicon glyphicon-ok icon-ok check-mark"></i></a></li>
</ul>

In the JavaScript code mentioned above.

Answer №1

Remember to attach the event listener to the li element every time you add it to the dropdown-menu

Check out the live demo here

HTML

<div class="btn-group">
    <button id="dropdownModel" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    --Select Model-- <span class="caret"></span>
  </button>
    <ul id="dropdownModelList" class="dropdown-menu">
    </ul>
</div>

JS

var data = [{
    Value: "1",
    Text: "text1"
}, {
    Value: "2",
    Text: "text2"
}, {
    Value: "3",
    Text: "text3"
}];

$(function() {
    function createOption(val, text) {
        return '<li rel="0" class="" data-value="' + val + '"><a tabindex="0" class="" style=""><span class="text">' + text + '</span><i></i></a></li>';
    }

    $("#dropdownModelList").html(createOption("-1", "--Select Model--"));
    for (var i = 0; i < data.length; i++) {
        $("#dropdownModelList").append(createOption(data[i].Value, data[i].Text));
    }
    $("#dropdownModelList li").click(function(e) {
        $("#dropdownModel").html($(this).find("a").html());
        $("#dropdownModelList li").find("i").removeClass();
        $(this).find("i").addClass("glyphicon glyphicon-ok icon-ok check-mark");
    });
});

Update

$.getJSON('@Url.Action("GetModelNames")?Brand=' + v, function(data) {
  $.each(data.ModelItems, function(a, b) {
    $("#dropdownModelList").append(createOption(b.Value, b.Text));
  });
  //re-attach event listener $("#dropdownModelList li").click(...)
});

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

A guide on updating the appearance of a list of comma-separated tags using HTML, CSS, and jQuery

Is there a way to replicate the functionality of the tag section on this website for creating question entries? How can this be achieved? ...

Is there a way to transpile a dependency within the node_modules directory when using Nuxt 2?

I have come across challenges when transpiling node_modules with Nuxt, but the latest version of Nuxt (2.0) seems to have addressed this issue by introducing a transpile option in the nuxt.config.js file. https://nuxtjs.org/api/configuration-build/#transp ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

Another approach to utilize JavaScript for populating content into a <div> container?

Upon loading the page, I aim to display a message in the <div> element. Below is the HTML and JavaScript code I have implemented: <body onload="printMsg()"> <div id="write"></div> </body> function printMsg() { var no ...

Utilizing Three.js in your HTML code

Currently, I am using c9.io as my IDE to write and test code for a website. Despite my efforts to import the code outside of c9.io, it is still not functioning properly. (I am confident that the issue is not with the three.js script itself.) My HTML code c ...

Encountering a loading error with r.js while attempting to optimize

In my main.js file, I have the following configuration for Require.js: /*--- Setting up Require.js as the main module loader ---*/ require.config({ baseUrl: '/javascripts/libs/home/', waitSeconds: 0, paths : { jquer ...

How can I efficiently add multiple items to an array and store them in async storage using React Native?

I am trying to store multiple elements in local storage using React Native. I found some helpful documentation on how to do this here. Could someone guide me on the correct way to achieve this? Here's a snippet of my code: My current approach const ...

Struggling to properly interpret the unrefined data from Typeform's webhook

Utilizing the webhook feature of Typeform to convert results to JSON when a user submits the embedded survey is working perfectly when tested with RequestBin. However, after exposing my local app using ngrok with the command ngrok http 3000 and setting t ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...

The function is invoked numerous times

My issue involves using jQuery to handle the mouseenter and mouseleave events. The problem arises when transitioning from one div to another, causing the events to trigger again. I am looking for a solution to only run these events once per mouse enter and ...

Transform a string into a JSON entity

Can JavaScript be used to convert a string such as this: "Product : Bike , 2005 : $12000,2006 : $13000,2007 : $14000,2008 : $15000" into a JSON object like the one below: { "Product":"Bike", "2005" : $12000, "2006" : $13000, "2007" : $14 ...

Creating a visual representation of a JSON tree using nested <ul> elements in AngularJS

Consider a JSON tree structure like the one shown below: var myTree = { "node": { "name": "A", }, "children": [ { "node": { "name": "B", }, "children": [] }, { "node": { "name": "C", }, ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...

Ensure that the Javascript file is included before the CSS file to prevent any margin

I have external files for JavaScript and CSS. According to This question, they suggested that including JavaScript before CSS could enhance performance. However, I noticed a discrepancy in Chrome when I load JS before CSS - the .offset() function returns a ...

Tips for adding a border to an element when hovered over

I am looking to achieve a hover effect that displays a border around an element without actually adding the border to the element itself, as shown in this image: https://i.sstatic.net/iFpCA.png The challenge I'm facing is that I want to allow users ...

eachSeries not executing the callback

I am encountering an issue with async.eachSeries. I am using it to loop through an array and download files using a specific function (refer to the source code provided). However, I am having trouble as the callback never seems to be called. Is there somet ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...