Strange behavior accessing a property in a javascript object
Asked Answered
P

1

10

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?

Pumping answered 19/12, 2012 at 14:0 Comment(9)
Maybe input has maxlength set and value is trimmed when setting value that is too long?Freud
Check input size attribute.Colza
Is the label stored as a string? If not then I have a funny feeling the commas are up to no goodFarrison
@Tal size attribute has nothing to do with it. maxlength is, though.Mating
I've edited in the html for the input into the question. There is no max length attribute.Pumping
A demo please, we can't reproduce without more informationQuietude
Also try to pass that value to any other input and check the result. Maybe it's the autocomplete widget interfere here.Freud
" I only get Boston" - when you console.log($('input[name="address-search"]').val()) or inside the input field?Attractant
It works in this demo I made; jsfiddle.net/RLGkNGiavani
M
8

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. )

Mating answered 19/12, 2012 at 14:7 Comment(2)
Ugh +1, you beat me to it :)Freud
This was the solution. Thank you!Pumping

© 2022 - 2024 — McMap. All rights reserved.