Harry
Harry

Reputation: 4835

jQuery - String variable being escaped?

I have a fairly simple script designed to hide/unhide various form fields based on customer type. The code looks as follows:


var customerTypeFields = [];
    customerTypeFields['Individual'] = ['First Name(s)', 'Last Name', 'Date of Birth'];
    customerTypeFields['Limited Company'] = ['Name', 'Company Number'];
    customerTypeFields['Partnership'] = ['Name', 'Company Number'];

    $('#customer-type-selector').chosen().change( function() {
        var visibleFields = customerTypeFields[$(this).children("option[value='" + $(this).attr('value') + "']").text()];
        console.log(visibleFields);
        $.each(visibleFields, function(i, field) {
            $('#customer-features').find('input[data-feature-type=' + field + ']').parent().parent().show();
        });
    });

This appears to work to some extent, but I'm getting a strange error when loading an individual, which is:

Uncaught Error: Syntax error, unrecognized expression: input[data-feature-type=First (s)] 

You will note that First (s) is not in my array, and as such it seems like the word Name is being stripped - any idea why the string would be edited like that?

Thanks!

Upvotes: 0

Views: 355

Answers (1)

Adriano Carneiro
Adriano Carneiro

Reputation: 58625

Escape with double quotes:

(...)  .find('input[data-feature-type="' + field + '"]')  (...)

See more on jQuery's Attribute Equals Selector page. It basically defines it as:

jQuery('[attribute="value"]')

Upvotes: 1

Related Questions