Nellinel
Nellinel

Reputation: 33

I am working with jQuery to count the number questions

I am having trouble coding this correctly to have it count how many questions there are. Here is my code. I am using jQuery for this. I am not sure where I went wrong. When I run this I get 0 as the answer.

  <fieldset id="question-1">
<p>
      <label>Question 1</label>
   </p>
    <p>How many questions are there on this page?</p>
    <p class="output"></p>
  </fieldset>
<fieldset id="question-2"> 
<p>
      <label>Question 2</label>
   </p>
    <p>Make the word "Disappear" disappear after two seconds.</p>
    <p class="target">Disappear</p>
    <p class="output"></p>
  </fieldset>
<fieldset id="question-3">
<p> 
      <label>Question 3</label>
    </p>
    <p>Make the word "Fade" fade after two seconds.</p>
    <p class="target">Fade</p>
    <p class="output"></p>
  </fieldset>

$(document).ready(function(){
var n = $(".question-").find("fieldset").length;
  alert(n);
});

$(document).ready(function(){
$("#question-2 .target").hide(2000);
});
$(document).ready(function(){
$("#question-3 .target").fadeOut(2000);
});

Upvotes: 0

Views: 53

Answers (2)

firevirus
firevirus

Reputation: 1

the most easy way to do this is to give each question the same class. and than use the length function in jquery to count those with that class.

$("#button_count").click(function(e){
    alert("there are: " + $(".question").length) + "questions";
});

http://jsfiddle.net/hfzvgauy/

Upvotes: 0

caramba
caramba

Reputation: 22480

$(".question-") will be looking for elements with a class="question-" but you have an ID so you should try at least with $('#question-1') which points already the next problem: if you have a class or an id like "question-1" you can not have a selector without that number cause it is part of the selector.

Maybe the best way is like raina77ow mentiones in the comment bellow using

$('fieldset[id^=question]').length

Updated fiddle http://jsfiddle.net/h6h20qam/1/

Upvotes: 1

Related Questions