1

I am using MVC3 on my project.

I have a view with tables and a textarea. Each row have "Name" Column and a ID that is not displayed in the rows.

Also I have:

@Html.HiddenFor(model => model.SelectedQuestions)

When a user clicks on a row I want that my SelectedQuestions that is a string gets filled by the ID of the row.

This is inside my controller for my tables:

 foreach (var player in playerGroupedByTeam)
                {
                    var playerViewModel = new playerViewModel();

                    playerViewModel.PlayerId = player.Id;
                    playerViewModel.PlayerName = Player.PlayerName;

                    TeamPlayer.Player.Add(playerViewModel);
                }

Any suggestions how I can solve this with jquery?

Thanks in advance!

ps__
  • 365
  • 1
  • 4
  • 19
  • 1
    Do you want `SelectedQuestions` to contain a unique list of the Ids of the clicked rows, or just that of the most recently-clicked row? – Steve Wilkes Mar 28 '12 at 12:47
  • It should contaain a string of Ids of the clicked rows – ps__ Mar 28 '12 at 12:51
  • I have only done some .Net but I believe it would be easier with an `On Click` even in .Net. With that said, do you want the ids to have a separator? – kwelch Mar 28 '12 at 13:06

1 Answers1

0

This should work:

<table id="player-table">
    @foreach(var player in this.Model.Players)
    {
    <tr><td data-player-id="@player.PlayerId">@player.PlayerName</td></tr>
    }
</table>
@this.Html.HiddenFor(model => model.SelectedQuestions)

<script type="text/javascript">
    $(function() {
        var selectedQuestions = $("#SelectedQuestions");
        $("#player-table").find("td").click(function() {
            var clickedId = $(this).attr("data-player-id");
            var currentIds = selectedQuestions.val().split(",");
            if (!$.inArray(clickedId, currentIds)) { 
                currentIds.push(clickedId); 
            }
            selectedQuestions.val(currentIds.join(","));
        });
    });
</script>

Please note it doesn't include removing already-clicked Ids if you wanted it to do that.

Steve Wilkes
  • 7,085
  • 3
  • 29
  • 32