A
A
Alexey Medvedev2015-11-10 15:33:30
JavaScript
Alexey Medvedev, 2015-11-10 15:33:30

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;
    }
}


Thanks in advance for your reply =)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivanq, 2015-11-10
@Ivanq

"abc".substr(1, 1); // "b"
But it's better not to do that. Store a value property somewhere, then just substitute it.

A
Alexey Medvedev, 2015-11-11
@medvedhack

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 question

Ask a Question

731 491 924 answers to any question