Hai Truong IT Hai Truong IT - 1 month ago 5
jQuery Question

Error Uncaught Error: Syntax error, unrecognized expression

<div class="mt-repeater-item">
<div class="row mt-repeater-row">
<input type="text" name="product[0][price]" value="2" oninput="update_total(this)">
</div>
</div>
<div class="mt-repeater-item">
<div class="row mt-repeater-row">
<input type="text" name="product[1][price]" value="3" oninput="update_total(this)">
</div>
</div>


And my script

function update_total(input) {
var sum = 0;
$('.mt-repeater-item').each(function(index) {
var product_price = $("input[name=product["+index+"][price]]").val() ? $("input[name=product["+index+"][price]]").val() : 0;
sum = sum + product_price;
});
alert(sum);
}


Error Uncaught Error: Syntax error, unrecognized expression
=> How to fix it?

Answer

You have missing quotation for name --

function update_total(input) {
    var sum = 0;
    $('.mt-repeater-item').each(function(index) {
        var product_price = $("input[name='product["+index+"][price]']").val() ? $("input[name='product["+index+"][price]']").val() : 0;
        sum = sum + product_price;
    });
    alert(sum);
}

Link - https://jsfiddle.net/80op2y19/

Comments