简体   繁体   中英

Grails - jQuery Autocomplete with Multiple Values

The single value autocomplete is working fine ( thanks to people who helped me with it .) but when I tried the jQuery UI's multiple value example , it is not getting the source I need.

This is my controller.

def courseList = {
    def cList = Course.withCriteria {
        ilike 'course', params.term +'%'
    }
render (cList.'course' as JSON)
}

This is my _form view.

<div class="fieldcontain ${hasErrors(bean: studentInstance, field: 'courses', 'error')} required" >
<label for="course">
    <g:message code="student.courses.label" default="Courses" />
    <span class="required-indicator">*</span>
</label>
<g:textField name="course" id="coursetags" required="" value="${course?.course}"/>

This is my jQuery script (exactly from jQuery UI demo).

function split( val ) {
    return val.split( /,\s*/ );  
}

function extractLast( term ) {
    return split( term ).pop();  
}

var courses = ["English", "Music", "Science"];

$( "#coursetags" )
    // don't navigate away from the field on tab when selecting an item
    .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
              event.preventDefault();
        }
    })
    .autocomplete({
        minLength: 2,
        source: function( request, response ) {
        // delegate back to autocomplete, but extract the last term
        response( $.ui.autocomplete.filter( courses, extractLast( request.term ) ) );
        },
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function( event, ui ) {
            var terms = split( this.value );
            // remove the current input
            terms.pop();
            // add the selected item
            terms.push( ui.item.value );
            // add placeholder to get the comma-and-space at the end
            terms.push( "" );
            this.value = terms.join( ", " );
            return false;
        }
    }); 

When I have var courses tag inside the script, the multiple-values-autocomplete works. How would I connect autocomplete's source to my controller?

For the single value, this is what I had in my script.

$("#coursetags").autocomplete({
    source: "/myApp/student/courseList",
    minLength: 2
});

Thank you in advance.

I found this demo. https://github.com/jquery/jquery-ui/blob/master/demos/autocomplete/multiple-remote.html

source: function( request, response ) {
    $.getJSON( "/myApp/student/courseList",
               {term: extractLast( request.term )},
               response );},

I replaced source part and it works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM