1

I'd like to change the value of a <h2> with its id within a "on" function but it doesn't change.

Here's the code:

<div id="boardGame">
</div>

<script type="text/javascript">

    json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}

    var score = 0
    var nb = 0
    var iter = 0
    var song
    var start
    var click
    var listSongs = []

    getHome()

    $(document).on("click", '.calc_btn', function() {

        iter++
        $("#valueIter").html(iter+"/10")
        if(iter == 10)
        {
            gameOver(score)
        }
        else 
        {
            click = new Date()
            time = (click.getTime() - start.getTime())/1000
            if($(this).val() == song){
                if(time <= 15)
                    score += parseInt((-1000/14)*time+929)
                $("#valueScore").html(score)
                $("#valueScore").css( "color", "green" )
            } 
            else
            {
                $("#valueScore").html(score)
                $("#valueScore").css( "color", "red" )
            }
            nb += 1
            getSong()
        }
    })

    function getHome()
    {
        score = 0
        iter = 0
        listSongs = []
        $("#boardGame").html("<h2>Welcome to The Game of Monkeys</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' class='stres' value='Start' onclick='getSong()'></td></tr></tbody></table")
    }

    function getSong()
    {
        var keys = [];
        for (var prop in json_dic) {
            if (json_dic.hasOwnProperty(prop)) {
                keys.push(prop);
            }
        }

        song = keys[ keys.length * Math.random() << 0 ];
        listSongs = [ song ]
        url = json_dic[song]

        while(listSongs.length <= 4)
        {
            var keys = [];
            for (var prop in json_dic) {
                if (json_dic.hasOwnProperty(prop)) {
                    keys.push(prop);
                }
            }

            song_random = keys[ keys.length * Math.random() << 0 ];
            listSongs.push(song_random)
        }

        $("#boardGame").html('<table class="calculatrice" id="calc"> '+
            '<tbody>' +
            '<tr>' +
            '<td class="calc_td_btn">' +
            '<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
            '<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
            '</div>' +
            '</div>' +
            '</td>' +
            '</tr>');

        for(var i = 0; i <= 4; i++)
        {
            var randomIndex = Math.floor(Math.random() * listSongs.length);
            var randomString = listSongs[randomIndex];
            $("#boardGame").append('<tr>'+
                '<td class="calc_td_btn">' +
                '<input type="button" class="calc_btn" value="'+randomString+'">' +
                '</td>' +
                '</tr>')
            var index = listSongs.indexOf(randomString);
            listSongs.splice(index, 1);
        }

        $("#boardGame").append('<tr>' +
            '<td class="calc_td_btn">' +
            '<h2 id="valueScore">0 points</h2>' +
            '<h2 id="valueIter">0/10</h2>' +
            '<input type="button" class="stres" onclick="getHome()" value="Restart">' +
            '</td>' +
            '</tr>' +
            '</tbody>' +
            '</table>')

        var nb = getRandomInt(0,100)
        $("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")

        start = new Date()

    }

    function getRandomInt (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function gameOver(score){
        $("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
    }

</script>




</body>
</html>

And it's the value of #valueScore that doesn't want to change. I think it it a scope problem but I can't get my way around it.

I can the value of #valueScore in the console or if I put the piece of code $("#valueScore").html(score) somewhere else in my JavaScript.

EDIT : added the whole code

antoine
  • 115
  • 7
  • So your issue is not here `$("#valueScore").html(score)` but somewhere else before calling it. Any error in console? Are you sure the first ELSE statement is reached? – A. Wolff Mar 07 '14 at 19:20
  • Show the HTML as well. (are you sure it's `

    `)

    – erapert Mar 07 '14 at 19:20
  • 2
    First off, you're missing semicolons throughout what you've posted. Any errors in the console? Have you stepped through the code or adding log statements? – Jason P Mar 07 '14 at 19:23
  • If you could setup a jsfiddle, that would be helpful. Obviously we're not seeing all of the javascript, and none of the html, so it's hard to diagnose where the problem is. – Ted Mar 07 '14 at 19:30
  • i added my whole html file for a easier comprehension. – antoine Mar 07 '14 at 20:53
  • Jason P, semicolons are somewhat optional in JS: http://www.codecademy.com/blog/78-your-guide-to-semicolons-in-javascript though I would agree that the proper choice is to use them: http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript – erapert Mar 07 '14 at 21:30

2 Answers2

0

The problem is that you're blowing away the DOM of all the elements at line 93-106 and you're re-creating them all. So the element that you're setting the score on is being destroyed and replaced with a completely different <h2>.

Instead of destroying everything (line 82 is where you replace the html of '#boardGame') you need to use JQuery to modify the buttons that already exist to give them the names of the song list.

As an alternative, try doing this:

  1. Give all the multiple-choice buttons a class: '.choice_button'
  2. Put a <div id="button_wrapper"> around all the buttons so that you have something to insert the new buttons into.
  3. Instead of replacing the HTML for '#boardGame' simply destroy all the buttons: $('#button_wrapper .choice_button').remove()
  4. Now you can insert the new buttons using that for loop just like you're doing on line 93
  5. Now $('#valueScore') hasn't been blown away so the score should remain.

I've modified your code to get it to where I think it's what you're after:

<div id="boardGame">
</div>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

    json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}

    var score = 0
    var nb = 0
    var iter = 0
    var song
    var start
    var click
    var listSongs = []

    getHome()

    $(document).on("click", '.calc_btn', function() {

        iter++
        $("#valueIter").html(iter+"/10")
        if(iter == 10)
        {
            gameOver(score)
        }
        else 
        {
            click = new Date()
            time = (click.getTime() - start.getTime())/1000
            if($(this).val() == song){
                if(time <= 15)
                    score += parseInt((-1000/14)*time+929)
                $("#valueScore").html(score)
                $("#valueScore").css( "color", "green" )
            } 
            else
            {
                $("#valueScore").html(score)
                $("#valueScore").css( "color", "red" )
            }
            nb += 1
            getSong()
            return false;
        }
    })

    function getHome()
    {
        score = 0
        iter = 0
        listSongs = []
        $("#boardGame").html(
            '<h2>Welcome to The Game of Monkeys</h2>'+
            '<table class="calculatrice" id="calc">' +
                '<tbody>' +
                '</tbody>' +
            '</table>' +
            '<div id="gameButtons" style="display: none;">' +
                '<h2 id="valueScore">0 points</h2>' +
                '<h2 id="valueIter">0/10</h2>' +
                '<input type="button" class="stres" onclick="getHome()" value="Restart">' +
            '</div>' +
            '<input type="button" class="stres" value="Start" onclick="getSong()">'
        )
    }

    function getSong()
    {
        var keys = [];
        for (var prop in json_dic) {
            if (json_dic.hasOwnProperty(prop)) {
                keys.push(prop);
            }
        }

        song = keys[ keys.length * Math.random() << 0 ];
        listSongs = [ song ]
        url = json_dic[song]

        while(listSongs.length <= 4)
        {
            var keys = [];
            for (var prop in json_dic) {
                if (json_dic.hasOwnProperty(prop)) {
                    keys.push(prop);
                }
            }

            song_random = keys[ keys.length * Math.random() << 0 ];
            listSongs.push(song_random)
        }

        // adds the music player, of course
        $('#calc tbody').html (
            '<tr>' +
            '<td class="calc_td_btn">' +
            '<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
            '<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
            '</div>' +
            '</div>' +
            '</td>' +
            '</tr>');

        // adds the multiple choice buttons
        for(var i = 0; i <= 4; i++)
        {
            var randomIndex = Math.floor(Math.random() * listSongs.length);
            var randomString = listSongs[randomIndex];
            $("#calc tbody").append('<tr>'+
                '<td class="calc_td_btn">' +
                '<input type="button" class="calc_btn" value="'+randomString+'">' +
                '</td>' +
                '</tr>')
            var index = listSongs.indexOf(randomString);
            listSongs.splice(index, 1);
        }

        // shows the score and the restart button
        $('#gameButtons').show();

        var nb = getRandomInt(0,100)
        $("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")

        start = new Date()

    }

    function getRandomInt (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function gameOver(score){
        $("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
    }

</script>
</body>
</html>
erapert
  • 1,383
  • 11
  • 15
-2

Oh I think I see the problem. You do not need to use the .html function.

Using jQuery:

$("#valueIter").val(iter+"/10");
$("#valueScore").val(score);

The html function is used to populate an element with raw html. The difference here is that jQuery provides .val() and .text() as getters and setters for any element which equate to the javascript equivelent of

element.value = score;
Anthony Mason
  • 165
  • 1
  • 12