2

I made this as simple as I could

Here is my HTML code:

    <div id="outsideCounter"><p></p></div>

    <div id="clickToAdd"><p>Click me</p></div>

    <div id="insideCounter"><p></p></div>

And here is the javascript:

$(document).ready(function(){

    var level = 1; // start the counting at 1

    $('#outsideCounter > p').html(level); // show value of the first counter


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

            level++; // I want this to add both counters, not just the insideCounter

            $('#insideCounter > p').html(level); // show value of the second counter
        });

});

Now the problem is that when you click 'clickToAdd' it adds 1 only to the insideCounter. How could I get that same updated level to the outsideCounter? I've been struggling with this for hours now and my brains are so jammed I can't figure this out on my own.

I have been exercising javascript only for a week now so please try to keep it as simple as possible because I couldn't even find anything useful from the previous answers about 'getting variable from function'.

I made jsfiddle if that helps to understand my problem.

4 Answers 4

4

You can separate the selectors by a comma , but since both ids end with Counter, you could just make use of that pattern, by combining ends-with which works with attribute selector.

$('[id$=Counter] > p').html(level);
Sign up to request clarification or add additional context in comments.

1 Comment

this will remove the <p> tags!
2

Simply add outsideCounter > p to your selector:

$('#insideCounter > p, #outsideCounter > p').html(level);

Fiddle

Comments

1
$(document).ready(function(){

    var level = 1; // start the counting at 1

    $('#outsideCounter > p').html(level); // show value of the first counter


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

            level++; // I want this to add both counters, not just the insideCounter 

            $('#insideCounter > p, #outsideCounter > p').html(level); // show value of the second counter
        });

});

Comments

0
$(document).ready(function () {

var level = 1; // same variable for both counter

$('#outsideCounter > p').html(level); // show first counter

$('#clickToAdd').click(function () {
    level++; // this only adds insideCounter
    $('#insideCounter > p, #outsideCounter > p').html(level);
  }); 
});

Comments

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.