Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery AutoComplete Combobox

I have been trying to get my head around autocomplete in a short time and am just banging my head against the wall trying to make it work. I've tried numerous examples and none make sense enough for me to use.

I have created an example that I hope explains what I am trying to do. This is an MVC 3 application

I am using the autocomplete code from the jquery site at http://jqueryui.com/autocomplete/#combobox and I have this linked into the header of my _Layout.cshtml file along with all other required js and css files.

The Div which is in my view on Home/Index.cshtml and button with which to perform an action with.

<div id="SearchDiv"></div>
<button id="SearchBtn" type="button" style="float: right">Search</button>

The view includes the js file where I create the SELECT element and also define the button click.

<script src="@Url.Content("~/Scripts/combobox.js")" type="text/javascript"></script>

The JS file contents are as follows.

        var theader = '<table class="tbl">\n';
        var tbody = '';

for (var i = 0; i < 10; i++) {
    if (i % 2 == 0)
        tbody += '<tr>';
    tbody += '<td><select class="SelectionControls"/><option value="0"></option>';
    tbody += '<option value="1">This is a test</option>';
    tbody += '<option value="2">This is a test 1</option>';
    tbody += '<option value="3">This is a test 2</option>';
    tbody += '<option value="4">This is a test 3</option>';
    tbody += '<option value="5">This is a test 4</option>';
    tbody += '<select></td>';

    if (i % 2 != 0)
        tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('SearchDiv').innerHTML = theader + tbody + tfooter;

$(".SelectionControls").combobox();

$("#SearchBtn").click(function () {
    var readtheselectedvalue= $(".SelectionControls")[0].val();
});

Nothing happens when I run the code apart from it putting comboboxes onto the screen in a table but they are all empty. I need the comboboxes to be populated with the textural values above so the selected text is shown in the combobox textfield when an item is selected but when I read the val() I need it to return the value associated with that selection 0 - 5.

I need to be able to read the value 0-5 in javascript as I have further processing I need to do with the value once the Search button is pressed.

If anyone could please tell me how I accomplish this I would be very grateful as I've been struggling with this for ages.

like image 713
user2096992 Avatar asked Jan 14 '23 03:01

user2096992


1 Answers

Just a hint after struggling with so many autocompletion scripts myself.

Chosen is the best autocomplete plugin ever.

like image 135
Timmetje Avatar answered Jan 16 '23 23:01

Timmetje