Alexandru Alexandru - 3 months ago 13
jQuery Question

Click event runs only one time

I have this jquery code

var nr = Math.floor(Math.random()*10 + 1);
nr = '' + nr;
var qID = '#' + 'nr' + nr;


$(document).ready(function(){
$('button').click( function(){
$('#qHome').hide();
$(qID).show();
})

})


When I click on 'button' it hides one div and show qID div, but this happens only one time, when I try to click again it doesn't work, I have to refresh the page.

**Note that qID is an id generated with math random that looks like this: '#nr1', '#nr2', .... '#nr9', '#nr10' where those ID are assigned to divs.

Answer

You should get a new QID for button click evry time.

Try this:

$(document).ready(function(){
  $('button').click( function(){
    $('#qHome').hide();
    $(getQID()).show();
  })     
})

function getQID()
{
   return "#nr" + Math.floor(Math.random()*10 + 1);
}