Answer the question
In order to leave comments, you need to log in
How to parse a string using javascript or just change part of an attribute?
The site has a button to add a product to the cart, each button has an attribute of the form:
onclick="addcart(2,1,27);"
The last variable in the function is the quantity of the product. Without any problems, I implemented the "plus" and "minus" buttons, made in which the number for the user is indicated.
Before that, there was a data-qnt="" attribute and everything was processed by jQuery, but I decided to abandon them in favor of a simple on-click. Actually I can not solve the problem of how to change the last value in the function in onclick. Is there a function in js similar to substr() in php?
I implemented the plus-minus functions as follows:<div id="points"></div>
// В диве points есть по умолчанию какое-то значение кол-ва товара (бывает 1, а бывает только упаковка по 7 штук, например, для этого и юзается qnt)
function inc(qnt){
$("#points").html(parseInt($("#points").html())+qnt);
$('#id кнопки').attr("data-qnt",parseInt($('#id кнопки').attr("data-qnt"))+qnt); // нужно заменить на фун-ю изменения онклика
return false;
}
function dec(qnt){
if (parseInt($("#points").html())>qnt) {
$("#points").html(parseInt($("#points").html())-qnt);
$('#id кнопки').attr("data-qnt",parseInt($('#id кнопки').attr("data-qnt"))-qnt); // нужно заменить на фун-ю изменения онклика
return false;
}
}
Answer the question
In order to leave comments, you need to log in
"abc".substr(1, 1); // "b"
But it's better not to do that. Store a value property somewhere, then just substitute it.
Implemented a little stupid, but everything seems to work fine
function inc(qnt){
var defqnt = parseInt($("#points").html())+qnt;
var defon = $('#id кнопки').attr("onclick").replace(/addcart|[();]/g, "").split(',');
$("#points").html(defqnt);
$('#id кнопки').attr("onclick",'addcart('+defon[0]+','+defon[1]+','+defqnt+');');
return false;
}
function dec(qnt){
if (parseInt($("#points").html())>qnt) {
var defqnt = parseInt($("#points").html())-qnt;
var defon = $('#id кнопки').attr("onclick").replace(/addcart|[();]/g, "").split(',');
$("#points").html(defqnt);
$('#id кнопки').attr("onclick",'addcart('+defon[0]+','+defon[1]+','+defqnt+');');
return false;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question