mardi 2 août 2016

Extract value from checkbox using index

I'm making a poll page with a few checkboxes. And I have an array results that counts how many each checkbox has been clicked.

<h2>What's your favorite pet</h2>
<form>
<input type="checkbox" name="cb[0]" value="Cats"/>
<input type="checkbox" name="cb[1]" value="Dogs"/>
<input type="checkbox" name="cb[2]" value="Spiders"/>
<input type="checkbox" name="cb[3]" value="Whales"/>
</form>

I also have a "Show Results" button that displays an alert window with a string variable that I have hard coded the options (cats, dogs, ...) to be concatenated with their results. Here's an example:

var myResults = "Cats "+results[0] + " Dogs "+results[1] + " Spiders "+results[2];

My problem is that if I want to add a new option to the poll, I also have to add it manually to the myResults string. How can I make that happen automatically?

I tried a few things, but I couldn't make them work. Here they are:

var allCheckboxes = document.getElementsByTagName("input"); //I only have checkboxes on the page
var resultsReady="";
for(var i=0;i<allCheckboxes.length;i++){
var currentVal = $("input")[i].val(); //this expression is false for some reason
resultsReady.concat(currentVal,results[i]," ");}

why doesn't $("input")[2].val(); work? I know it isn't working because I isolated it and it didn't work.

I also tried $("input").get(i).val(); but it didn't work and I can kinda see why but I don't know how to fix it.

Last thing I tried was $("input['cb[i]']") but I don't know if this expression works.




Aucun commentaire:

Enregistrer un commentaire