Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior accessing a property in a javascript object

I'm trying to access a value in my object:

<input type="text" name="address-search" 
       placeholder="43 Roxling Drive Boston, MA" 
       class="ui-autocomplete-input ui-corner-all" autocomplete="off">

select: function( event, ui ) {
    console.log(ui);
    $('input[name="address-search"]').val(ui.item.label);
}

Here's the result of the console.log call:

enter image description here

Here's the strange bit:

If I console.log(ui.item.label) I get: Boston, Massachusetts, United States.

If I call $('input[name="address-search"]').val(ui.item.label); I only get Boston. Any ideas why this is happening?

like image 774
sergserg Avatar asked Dec 19 '12 14:12

sergserg


People also ask

Why is object property undefined JavaScript?

The JavaScript warning "reference to undefined property" occurs when a script attempted to access an object property which doesn't exist.

Why is my object property undefined?

The undefined property indicates that a variable has not been assigned a value, or not declared at all.

Is property of object JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

Can object properties be numbers JavaScript?

Can JavaScript object property be a number? Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.


1 Answers

From jQuery UI autocomplete doc:

select

Triggered when an item is selected from the menu. The default action is to replace the text field's value with the value of the selected item. Canceling this event prevents the value from being updated. [...]

What happens here: you replace the value in the input wrapped by into 'autocomplete' widget - but then the widget replaces it by itself. ) Add return false; to your function to make it work.

As a sidenote, you don't have to look up the DOM for that element again:

this.value = ui.item.label;

... should do the trick. )

like image 148
raina77ow Avatar answered Sep 20 '22 15:09

raina77ow