2

i am having an add to basket problem.Some products have options like color/size. I draw the select box for color/size and an input for qty.

<select name="productOption[1234][color]">
<select name="productOption[1234][size]">
<input type="text" name="productOption[1234][qty]">

So option is an array that holds the values for each product.In the abov example are the options of product with id=1234.

I tried

var productOptions=$("name^='productOption["+productID+"]'").val();  

expecting to get the array of options for the given productID but its not working. The options are dynamically some products can have extra options

Can anyone help me with the selector so retrieve the array of values for given productID and pass them to serverSide.

Thanks

3 Answers 3

9

I think this is what you want assuming you're using jQuery.

<script type="text/javascript">
function getProductDetails( product_id ) {
    var product_details = [];
    jQuery( '[name*="productOption[' + product_id + ']"]' ).each( function() {
        var option = jQuery( this );
        var type = option.attr( 'name' ).match( /productOption\[\d+\]\[(\w+)\]/ );
        product_details[ type[1] ] = option.val();
    } );

    return product_details;
}
</script>

This will return an associated array. So you could do...

var details = getProductDetails( 1234 );
alert( details['qty'] );
Sign up to request clarification or add additional context in comments.

Comments

4

You forgot the attribute selector ([attr^=value])

var productOptions=$("[name^='productOption["+productID+"]']").val();

Comments

1

scape internal brackets with '\ \' (no space) - a lot easier

$('input[name=items\\[\\]]')

as seen here jquery - select all checkboxes with js array name

1 Comment

Firstly, your technique doesn't help with this question as the OP is already enclosing the text in quotes. Secondly, you are answering a question asked almost 2 years ago, and one that already has an accepted answer. Thirdly, how can adding non-intuitive `\` in code be easier as compared to simply using matching qoutes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.