javascript - assigning values to multiple js objects from the same form in a DRY fashion on each click -


i making typing game. 4 players can play game. here's html.

<!-- avatar select --> <div class="select container col-sm-6" id="avatar">   <h4 id="playerselector">player 1</h4>   <h4>please enter name.</h4>   <div class="input-group">     <input type="text" class="form-control" id="playername">   </div>   <button class="btn" id="submitplayer">submit</button>  </div> 

i want save each persons name, , avatar , score each player object. thought below function it. doesn't work.

$(document).ready(function(){    //define players   var player1 = {     name: "player 1",     avatar: "",     score: 0,   }   var player2 = {     name: "player 2",     avatar: "",     score: 0,   } 

... there's 2 more, skipped them

  //submit player info button   var playernum = 1;   var tempplayer = "";   $("#submitplayer").on("click", function () {     tempplayer = "player" + playernum;     tempplayer.name = $("#playername").val();     playernum += 1;     if (playernum > numplayers) {       $("#avatar").hide();       $("#instructions").show();     } else {       return     }   });  }); 

when console log it, tempplayer looks correct, same string variable player1, when try set value of input box doesn't take it. i'm assuming because it's looking object of name tempplayer opposed player1, though @ point tempplayer same string player1. true? , if so, what's method achieve same action without having write function each player?

you need use json object achieve this, , code below

var jsonarr = [];  $("#submitplayer").on("click", function () { jsonarr.push({     name: $("#playername").val();,     avatar: '',     ... //other values }); }); 

you need tweak works 4 times , things that. main reason above doesnt work because not possible concatenate string create pre defined variable in js.


Comments