Getting jQuery autocomplete field

I am using the autocomplete jQuery plugin and have connected an input field to retrieve the values ​​from the database at the back end as I enter the text, which can then be selected.
Then I have a second input field that I connected in a similar way, but I want to pass the first value of the input field as the querystring parameter in the ajax autocomplete call so that the autocomplete results can be filtered out.
I tried using the .val () method for the first input field, but this always returns an empty string if I do not allow the form for postback. I also tried using the value getElementById ('xxx'). But this returns a null value.
Is there a way to get the dynamic value selected in the first field so that I can pass it to my jQuery ajax call to the server?
The code below with some removed for brevity:

<% using (Html.BeginForm()) {%>
    <script language="javascript">
        $(document).ready(function(){
            $("#Make").autocomplete('/MyController/AutoCompleteMake', {
                dataType: 'json',
                parse: function(data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i], result: data[i] };
                    }
                    return rows;
                },
                formatItem: function(row) {
                    return row;
                },
                delay: 40
            });

            $("#Range").autocomplete('/MyController/AutoCompleteRange?Make=' + $('input[name=Make]').val(), {
                same as above .......
            });
        });
  </script>
    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Make">Make:</label>
            <%= Html.TextBox("Make") %>
            <%= Html.ValidationMessage("Make", "*") %>
        </p>
        <p>
            <label for="Range">Range:</label>
            <%= Html.TextBox("Range") %>
            <%= Html.ValidationMessage("Range", "*") %>
        </p>
<% } %>

This is part of $ ('input [name = Make]'). val (), which always returns an empty value, even if it is selected.

I just started working with jQuery and MVC, so any help would be greatly appreciated.

+3
source share
1 answer

You need to use the extraParams function:

$("#Make").autocomplete(url, {
   extraParams: {
       yourValue: function() { return $("input[name=Make]").val(); }
   }
}); 

This will then be passed to the HttpContext for your purpose.

This can be pulled out as follows:

string valueToUse = context.Request.QueryString["yourValue"];

From jQuery Autocomplete Documentation :

Often one autocomplete field depends on the value of another field. In this case, the extraParams option can provide the necessary dynamics. Parameter

, . , .

+5

Source: https://habr.com/ru/post/1723108/


All Articles