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:
- Stack Overflow:
- JavaScript:
- jQuery: