ty812
ty812

Reputation: 3323

Get the ID of an element within an autocomplete

I want to get the ID of an element which is

    <input type="text" id='4711_herstellerName' class='hersteller' />
    <input type="text" id='0815_herstellerName' class='hersteller' />
    <input type="text" id='1234_herstellerName' class='hersteller' />

My JQuery Part looks like this:

    $(".hersteller").autocomplete("ajax/getHersteller.php", {
    width: 320,
    max: 4,
    highlight: true,
    scroll: true,
    scrollHeight: 300,
    formatItem: function(data, i, n, value) {

                        alert($(this).attr('id'));

                    var herstellernummer = value.split(" ")[0];
                    var herstellername = value.replace(herstellernummer,"");

                    return herstellername.trim();
    }
});

What I want is an alert box with the content of "4711_herstellerName" (when I change the first input), and "1234_herstellerName" (when I change the last one), but all I get is "undefined" ... I am obviously misinterpreting the documentation. Can some kind soul give me a direction?

Maybe there is another way of doing what I need: The edit in this field (and subsequient select) should change values (that are all delivered by the php script) in different input fields. All these field IDs are created automatically, but all fields of one group are beginning with the same ID in the form

What I am trying to do is get the ID from which the autocomplete has changed, slice off the pid-part, and create the herstellerID and herstellerLogo id names...

Upvotes: 1

Views: 392

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

ipr101's right: jQuery Autocomplete does not set this to the object for which you're providing autocomplete formatting rules.

this is instead merely whatever it was outside of the function expression. So, if you set up the surrounding context properly, you can probably make it work:

$(".hersteller").each(function() {
   var $obj = $(this);
   $obj.autocomplete("ajax/getHersteller.php", {
      width:        320,
      max:          4,
      highlight:    true,
      scroll:       true,
      scrollHeight: 300,
      formatItem:   function(data, i, n, value) {
         alert($obj.attr('id'));

         var herstellernummer = value.split(" ")[0];
         var herstellername = value.replace(herstellernummer,"");

         return herstellername.trim();
      }
   });
});

(Untested but logical)

Upvotes: 3

ipr101
ipr101

Reputation: 24236

I think that the 'this' reference in your callback will not refer to the ".hersteller" textbox; try this -

alert($(".hersteller").attr('id'));

Upvotes: 0

Related Questions