Barrrdi
Barrrdi

Reputation: 1161

Source of a jQuery autocomplete being the value of a hidden input variable

I'm using jQuery's autocomplete, but I'm having problems getting the source to refer to the value of a hidden input on the page.

This is the hidden input field:

<input type="hidden" id="array_activities" value="[{ label: 'Football', value: '1' }, { label: 'Tennis', value: '2' }, { label: 'Running', value: '3' }]">

And this is the javascript:

$("#search").live("focus", function (event) {
    $(this).autocomplete({
        close: function( event, ui ) { area_input(); },
        source: $("#array_activities").val()
    });
});

But nothing auto-completes.

If I change the value of the source option to explicitly be the value of the hidden input (i.e. replace '$("#array_activities").val()' with

'[{ label: 'Football', value: '1' }, { label: 'Tennis', value: '2' }, { label: 'Running', value: '3' }]'),

it works fine.

Any ideas?

Upvotes: 1

Views: 409

Answers (1)

Sushanth --
Sushanth --

Reputation: 55740

Parse it before assigning it as a source

source: JSON.parse( $("#array_activities").val() )

As the source is expected to be an array of objects and not a string.

EDIT

JSON string with single quotes is not a valid syntax. All the properties have to be enclosed in double quotes for a valid syntax.

So change your value to something like this

value='[{ "label": "Football", "value": "1" },
      { "label": "Tennis", "value": "2" }, { "label": "Running", "value": "3" }]'

Fiddle

If you want your code to run as is, then you can try with

var arr = eval($("#array_activities").val());

But using eval is considered a bad practice.

For more Info

Upvotes: 1

Related Questions