简体   繁体   中英

Pass input id to url in jquery ui autocomplete

I need to pass the id of the input to the url of a remote datasource.

I have got it working via a hack but I feel I am doing things twice, is there any way I can get the input id without using the keypress function?

I need the input id passed to the url because there is some logic in the PHP file depending on which input is being used.

the html

<input id="input1" class="selector" type="text">

the js

    $(".selector").keypress(function() {
        var param2id = $(this).attr('id'); // this id needs to pass to the url


        $(".selector").autocomplete({
            minLength: 1,
            max: 10,
            source: "source.php?param2=" + param2id + "", // passed from the keypress
            focus: function(event, ui) {
                $(this).val(ui.item.value);
                return false;
            },
            select: function(event, ui) {
                $(this).val(ui.item.value);
                return false;
            }
        });


    });

It's actually a bit more complex, since autocomplete won't reference the element it's set on. So you can wrap them via an each function, so you don't have to use keypress . This will set the reference only once.

 $('.selector').each(function(i, el) { param2id = $(el).attr("id"); $(el).autocomplete({ minLength: 1, max: 10, source: "source.php?param2=" + param2id + "", focus: function(event, ui) { $(this).val(ui.item.value); return false; }, select: function(event, ui) { $(this).val(ui.item.value); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script> <input class="selector" id="input1"> 

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