0

I have HTML element as below

<input type="text" id="Search" select-box-search="true" select-box-search-url="testURL" /> 

I have jQuery as below.

 $(":input[select-box-search]").each(function () {
        $(this).autocomplete({
            source: function (request) {
                var url = $(this).attr("select-box-search-url");
                $.ajax({
                    async: false,
                    cache: false,
                    type: "POST",
                    url: url,
                    data: { "term": request.term},
                    success: function (data) {

                        }
                    }
                });
            }
        });
    });

The "url" is always undefined. However "this" is referring to correct element (when debugged in Chrome). Anything missing?

Alan

5
  • Instead of var url = $(this).attr("select-box-search-url"); use var url = $("#Search").attr("select-box-search-url"); and instead of making your own custom attributes use html5 data-* attribute. Commented Mar 3, 2016 at 4:58
  • I am trying to reuse the same function for other input elements too.i.e. #search1, #search2 and etc, So I cant hard code the id . Commented Mar 3, 2016 at 5:00
  • ok..then refer my answer. Commented Mar 3, 2016 at 5:03
  • @Kartikeya Khosla. that works fine . but why the other way didnt work? Commented Mar 3, 2016 at 5:08
  • Please read the explanation given in answer. Commented Mar 3, 2016 at 5:08

3 Answers 3

2

$this gives different context inside the source: function (request).So you need to cache the element before entering into the function

 $(":input[select-box-search]").each(function () {
    var $element = $(this);
    $element.autocomplete({
        source: function (request) {
            var url = $element.attr("select-box-search-url");
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: url,
                data: { "term": request.term},
                success: function (data) {

                    }
                }
            });
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

$(this) will give a different context inside the autocomplete. Try This :-

$(":input[select-box-search]").each(function () {
        var $this = $(this); //store $(this) reference inside a variable
        $(this).autocomplete({
            source: function (request) {
                var url = $this.attr("select-box-search-url"); //change here
                $.ajax({
                    async: false,
                    cache: false,
                    type: "POST",
                    url: url,
                    data: { "term": request.term},
                    success: function (data) {

                        }
                    }
                });
            }
        });
 });

Side Note :- Instead of making your own custom attributes use HTML5 data-* attribute.

Comments

0

As above stated by others two, this val inside autocomplete is different that this outside.

To make your code work replace your code as follows:

$(":input[select-box-search]").each(function () {
        $(this).autocomplete({
            source: function (request) {

var url = $(this.element).attr('select-box-search');

                $.ajax({
                    async: false,
                    cache: false,
                    type: "POST",
                    url: url,
                    data: { "term": request.term},
                    success: function (data) {

                        }

                });
            }
        });
    });

Outside this value: input#Search

accept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMap
autocapitalize: "sentences"
autocomplete: ""
autofocus: false
baseURI: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
checked: false
childElementCount: 0
childNodes: NodeList[0]
children: HTMLCollection[0]
classList: DOMTokenList[0]
className: ""
clientHeight: 15
clientLeft: 2
clientTop: 2
clientWidth: 127
contentEditable: "inherit"
dataset: DOMStringMap
defaultChecked: false
defaultValue: ""
dir: ""
dirName: ""
disabled: false
draggable: false
files: null
firstChild: null
firstElementChild: null
form: null
formAction: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
formEnctype: ""
formMethod: ""
formNoValidate: false
formTarget: ""
height: 0
hidden: false
id: "Search"
incremental: false
indeterminate: false
innerHTML: ""
innerText: ""
isContentEditable: false
labels: NodeList[0]
lang: ""
lastChild: null
lastElementChild: null
list: null
localName: "input"
max: ""
maxLength: 524288
min: ""
minLength: 0
multiple: false
name: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: div#number.abc
nextSibling: text
nodeName: "INPUT"
nodeType: 1
nodeValue: null
offsetHeight: 19
offsetLeft: 8
offsetParent: body
offsetTop: 8
offsetWidth: 131
onabort: null
onautocomplete: null
onautocompleteerror: null
onbeforecopy: null
onbeforecut: null
onbeforepaste: null
onblur: null
oncancel: null
oncanplay: null
oncanplaythrough: null
onchange: null
onclick: null
onclose: null
oncontextmenu: null
oncopy: null
oncuechange: null
oncut: null
ondblclick: null
ondrag: null
ondragend: null
ondragenter: null
ondragleave: null
ondragover: null
ondragstart: null
ondrop: null
ondurationchange: null
onemptied: null
onended: null
onerror: null
onfocus: null
oninput: null
oninvalid: null
onkeydown: null
onkeypress: null
onkeyup: null
onload: null
onloadeddata: null
onloadedmetadata: null
onloadstart: null
onmousedown: null
onmouseenter: null
onmouseleave: null
onmousemove: null
onmouseout: null
onmouseover: null
onmouseup: null
onmousewheel: null
onpaste: null
onpause: null
onplay: null
onplaying: null
onprogress: null
onratechange: null
onreset: null
onresize: null
onscroll: null
onsearch: null
onseeked: null
onseeking: null
onselect: null
onselectstart: null
onshow: null
onstalled: null
onsubmit: null
onsuspend: null
ontimeupdate: null
ontoggle: null
onvolumechange: null
onwaiting: null
onwebkitfullscreenchange: null
onwebkitfullscreenerror: null
onwheel: null
outerHTML: "<input type="text" id="Search" select-box-search="true" select-box-search-url="testURL">"
outerText: ""
ownerDocument: document
parentElement: body
parentNode: body
pattern: ""
placeholder: ""
prefix: null
previousElementSibling: script
previousSibling: text
readOnly: false
required: false
scrollHeight: 15
scrollLeft: 0
scrollTop: 0
scrollWidth: 127
selectionDirection: "none"
selectionEnd: 0
selectionStart: 0
shadowRoot: null
size: 20
spellcheck: true
src: ""
step: ""
style: CSSStyleDeclaration
tabIndex: 0
tagName: "INPUT"
textContent: ""
title: ""
translate: true
type: "text"
useMap: ""
validationMessage: ""
validity: ValidityState
value: ""
valueAsDate: null
valueAsNumber: NaN
webkitEntries: Array[0]
webkitdirectory: false
webkitdropzone: ""
width: 0
willValidate: true
__proto__: HTMLInputElement

Inside this value

    $.(…).(anonymous
    function) {
    element: n.fn.init[1],
    uuid: 0,
    eventNamespace: ".autocomplete0",
    options: Object,
    bindings: n.fn.init[3]…
}
_super: () _superApply: (args) bindings: n.fn.init[3] 0: input# Search.ui - autocomplete - input.ui - autocomplete - loading1: ul# ui - id - 1. ui - autocomplete.ui - front.ui - menu.ui - widget.ui - widget - content.ui - corner - all2: Windowcontext: undefinedlength: 3 prevObject: n.fn.init[2] __proto__: n[0] cancelSearch: falsedocument: n.fn.init[1] 0: documentcontext: documentlength: 1 __proto__: n[0] element: n.fn.init[1] 0: input# Search.ui - autocomplete - input.ui - autocomplete - loadingaccept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMapautocapitalize: "sentences"
autocomplete: "off"
autofocus: falsebaseURI: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
checked: falsechildElementCount: 0 childNodes: NodeList[0] children: HTMLCollection[0] classList: DOMTokenList[2] className: "ui-autocomplete-input ui-autocomplete-loading"
clientHeight: 15 clientLeft: 2 clientTop: 2 clientWidth: 127 contentEditable: "inherit"
dataset: DOMStringMapdefaultChecked: falsedefaultValue: ""
dir: ""
dirName: ""
disabled: falsedraggable: falsefiles: nullfirstChild: nullfirstElementChild: nullform: nullformAction: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
formEnctype: ""
formMethod: ""
formNoValidate: falseformTarget: ""
height: 0 hidden: falseid: "Search"
incremental: falseindeterminate: falseinnerHTML: ""
innerText: ""
isContentEditable: falsejQuery2210183872326975688342: ObjectjQuery2210183872326975688341: Objectlabels: NodeList[0] lang: ""
lastChild: nulllastElementChild: nulllist: nulllocalName: "input"
max: ""
maxLength: 524288 min: ""
minLength: 0 multiple: falsename: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: span.ui - helper - hidden - accessiblenextSibling: span.ui - helper - hidden - accessiblenodeName: "INPUT"
nodeType: 1 nodeValue: nulloffsetHeight: 19 offsetLeft: 8 offsetParent: bodyoffsetTop: 8 offsetWidth: 131 onabort: nullonautocomplete: nullonautocompleteerror: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonprogress: nullonratechange: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonshow: nullonstalled: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "<input type="
text " id="
Search " select-box-search="
true " select-box-search-url="
testURL " class="
ui - autocomplete - input ui - autocomplete - loading " autocomplete="
off ">"
outerText: ""
ownerDocument: documentparentElement: bodyparentNode: bodypattern: ""
placeholder: ""
prefix: nullpreviousElementSibling: scriptpreviousSibling: textreadOnly: falserequired: falsescrollHeight: 15 scrollLeft: 0 scrollTop: 0 scrollWidth: 127 selectionDirection: "none"
selectionEnd: 1 selectionStart: 1 shadowRoot: nullsize: 20 spellcheck: truesrc: ""
step: ""
style: CSSStyleDeclarationtabIndex: 0 tagName: "INPUT"
textContent: ""
title: ""
translate: truetype: "text"
useMap: ""
validationMessage: ""
validity: ValidityStatevalue: "a"
valueAsDate: nullvalueAsNumber: NaNwebkitEntries: Array[0] webkitdirectory: falsewebkitdropzone: ""
width: 0 willValidate: true__proto__: HTMLInputElementcontext: input# Search.ui - autocomplete - input.ui - autocomplete - loadingaccept: ""
accessKey: ""
align: ""
alt: ""
attributes: NamedNodeMapautocapitalize: "sentences"
autocomplete: "off"
autofocus: falsebaseURI: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
checked: falsechildElementCount: 0 childNodes: NodeList[0] children: HTMLCollection[0] classList: DOMTokenList[2] className: "ui-autocomplete-input ui-autocomplete-loading"
clientHeight: 15 clientLeft: 2 clientTop: 2 clientWidth: 127 contentEditable: "inherit"
dataset: DOMStringMapdefaultChecked: falsedefaultValue: ""
dir: ""
dirName: ""
disabled: falsedraggable: falsefiles: nullfirstChild: nullfirstElementChild: nullform: nullformAction: "file:///Users/avagrawal/Desktop/sent/hammer/index.html"
formEnctype: ""
formMethod: ""
formNoValidate: falseformTarget: ""
height: 0 hidden: falseid: "Search"
incremental: falseindeterminate: falseinnerHTML: ""
innerText: ""
isContentEditable: falsejQuery2210183872326975688342: ObjectjQuery2210183872326975688341: Objectlabels: NodeList[0] lang: ""
lastChild: nulllastElementChild: nulllist: nulllocalName: "input"
max: ""
maxLength: 524288 min: ""
minLength: 0 multiple: falsename: ""
namespaceURI: "http://www.w3.org/1999/xhtml"
nextElementSibling: span.ui - helper - hidden - accessiblenextSibling: span.ui - helper - hidden - accessiblenodeName: "INPUT"
nodeType: 1 nodeValue: nulloffsetHeight: 19 offsetLeft: 8 offsetParent: bodyoffsetTop: 8 offsetWidth: 131 onabort: nullonautocomplete: nullonautocompleteerror: nullonbeforecopy: nullonbeforecut: nullonbeforepaste: nullonblur: nulloncancel: nulloncanplay: nulloncanplaythrough: nullonchange: nullonclick: nullonclose: nulloncontextmenu: nulloncopy: nulloncuechange: nulloncut: nullondblclick: nullondrag: nullondragend: nullondragenter: nullondragleave: nullondragover: nullondragstart: nullondrop: nullondurationchange: nullonemptied: nullonended: nullonerror: nullonfocus: nulloninput: nulloninvalid: nullonkeydown: nullonkeypress: nullonkeyup: nullonload: nullonloadeddata: nullonloadedmetadata: nullonloadstart: nullonmousedown: nullonmouseenter: nullonmouseleave: nullonmousemove: nullonmouseout: nullonmouseover: nullonmouseup: nullonmousewheel: nullonpaste: nullonpause: nullonplay: nullonplaying: nullonprogress: nullonratechange: nullonreset: nullonresize: nullonscroll: nullonsearch: nullonseeked: nullonseeking: nullonselect: nullonselectstart: nullonshow: nullonstalled: nullonsubmit: nullonsuspend: nullontimeupdate: nullontoggle: nullonvolumechange: nullonwaiting: nullonwebkitfullscreenchange: nullonwebkitfullscreenerror: nullonwheel: nullouterHTML: "<input type="
text " id="
Search " select-box-search="
true " select-box-search-url="
testURL " class="
ui - autocomplete - input ui - autocomplete - loading " autocomplete="
off ">"
outerText: ""
ownerDocument: documentparentElement: bodyparentNode: bodypattern: ""
placeholder: ""
prefix: nullpreviousElementSibling: scriptpreviousSibling: textreadOnly: falserequired: falsescrollHeight: 15 scrollLeft: 0 scrollTop: 0 scrollWidth: 127 selectionDirection: "none"
selectionEnd: 1 selectionStart: 1 shadowRoot: nullsize: 20 spellcheck: truesrc: ""
step: ""
style: CSSStyleDeclarationtabIndex: 0 tagName: "INPUT"
textContent: ""
title: ""
translate: truetype: "text"
useMap: ""
validationMessage: ""
validity: ValidityStatevalue: "a"
valueAsDate: nullvalueAsNumber: NaNwebkitEntries: Array[0] webkitdirectory: falsewebkitdropzone: ""
width: 0 willValidate: true__proto__: HTMLInputElementlength: 1 __proto__: n[0] eventNamespace: ".autocomplete0"
focusable: n.fn.init[0] hoverable: n.fn.init[0] isMultiLine: falseisNewMenu: trueliveRegion: n.fn.init[1] menu: $.(anonymous
    function).(anonymous
    function) options: Objectpending: 1 previous: ""
searching: 3 selectedItem: nullsource: (request) term: "a"
uuid: 0 valueMethod: (a) window: n.fn.init[1] __proto__: $.(anonymous
    function).(anonymous
    function)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.