user3033194
user3033194

Reputation: 1821

Set HTML div value using JavaScript

I have an HTML page with 2 divs (among other things) - "person" and "person-success", in which "person" is visible and "person-success" hidden. When a button in "person" is clicked, the visible div hides and the previously-hidden div "person-success" shows. The code is given below:

<div id="person">
    <br><br>
    <div id="counterNum" class="counter-color" l10nID="M_AC_UT_TXT_20"></div>
    <div role="form">
        ...

        <button type="submit" id="addPerson" class="btn btn-success" l10nID="M_LG_BTN_1"></button>
    </div>
</div>
<div id="person-success" class="hide">
    ...
    <p>
        <span l10nID='M_AC_UT_TXT_19'></span>
        You can add <span id="limit"></span> more people. <a href='<?php echo $root; ?>edituseraccount.php?action=addPerson'>Add another person?</a>
    </p>
</div>

The JavaScript:

$('#addPerson').click(function() {

    var counter = 0;
    var limit = 10;
    var args = {

    ...

    $.post("addperson.php",args,function(data){  
        var response = JSON.parse(data);    
        if(response.status == 0){
            counter += 1;
            if (counter < limit){
                $('#counterNum').text(counter);
                $('#person').hide();
                $('#limit').text(limit-counter);
                $('#person-success').show();
            }
        }
        console.log(data);      
    });
});

Now, when the button is pressed, while "person-success" will show, clicking on "Add another person?" should show "person" and hide "person-success" again. Only this time, the div "counterNum" should be updated with the value of "counter" from the JavaScript. With my code, clicking the link reopens the "person" div and hides the other, but counterNum is not updated, or even shown. Does anyone know how I could do that?

I hope I could explain my problem. Would be grateful for any help!!

Upvotes: 0

Views: 86

Answers (2)

Sudharsan S
Sudharsan S

Reputation: 15393

Var counter Make it as global. Because each time when you click on the addPerson button when counter resets to zero.

var counter = 0;
var limit = 10;

$('#addPerson').click(function() {

    var args = {

    ...

    $.post("addperson.php",args,function(data){  
        var response = JSON.parse(data);    
        if(response.status == 0){
            counter += 1;
            if (counter < limit){
                $('#counterNum').text(counter);
                $('#person').hide();
                $('#limit').text(limit-counter);
                $('#person-success').show();
            }
        }
        console.log(data);      
    });
});

Upvotes: 1

Prasad
Prasad

Reputation: 211

The variable you declare is local scope. Declare variable globally outside the click event called. On each click it resets counter to 0.

Hope it helps !!!

Upvotes: 0

Related Questions