0

I have a form input field where some of the input string contains brackets, such as:

ducks[quack]

Note that this is not the name, class, anything like that. This is the value.

When I attempt to select this value with jquery, using the field class and val(), it returns an empty object. The same field with a string without brackets as the value, is selected fine.

I cannot modify the dataset which contains the brackets, is there some way to enable jquery to pull the value for these fields of strings?

http://jsfiddle.net/V8XP2/10/

mrpatg
  • 10,001
  • 42
  • 110
  • 169

1 Answers1

1

The following approach works, using the attribute-equals notation:

jQuery('#create_suborder').click(function (event) {
    event.preventDefault();

    var product = jQuery('#products').val(),
        product_id = jQuery('input[id="product_id_' + product + '"]').val(),
        total_units = jQuery('input[id="total_units_' + product + '"]').val();

    console.log(product, product_id, total_units);

    jQuery('#result').html(product_id + ', ' + total_units);
});

JS Fiddle demo.

Though using CSS notation: #product_id_' + product does not; I'm assuming that this is due to the need to escape [ and ] in CSS, which should be a back-slash, followed by the unicode character-point of the relevant characters. This is in contrast to the attribute-equals approach, which finds the elements and then iterates through the named attribute for the string-value supplied to the selector.

After some revision, the following works:

jQuery('#create_suborder').click(function (event) {
    event.preventDefault();

    var product = jQuery('#products').val().replace(/\[|\]/g, function(a){
        return '\\' + a.charCodeAt(0).toString(16) + ' ';
    }),
        product_id = jQuery('#product_id_' + product).val(),
        total_units = jQuery('#total_units_' + product).val();

    jQuery('#result').html(product_id + ', ' + total_units);
});

JS Fiddle demo.

This retrieves the value of the select element, then replaces any (and all) [ and ] characters, using the anonymous function of the replace() method. In this function a is the character that was found.

We return the string that begins with two \\ characters (since the \ is otherwise an escape character, and we want the literal \, we have to escape the escape); we concatenate that with the character-code of the found character (a.charCodeAt()) and, because CSS requires the Unicode character-points to be in hexadecimal format, we use toString(16) to convert from the decimal Unicode (91 and 93) to the hexadecimal format (5b and 5d); we then append a space as well, in order to delimit/end the escaped character-sequence.

References:

Community
  • 1
  • 1
David Thomas
  • 249,100
  • 51
  • 377
  • 410