jQuery: modify hidden form field value before submit

Posted by Jason Miesionczek on Stack Overflow See other posts from Stack Overflow or by Jason Miesionczek
Published on 2010-04-02T13:58:24Z Indexed on 2010/04/02 14:03 UTC
Read the original article Hit count: 278

I have the following code in a partial view (using Spark):

<span id="selectCount">0</span> video(s) selected.
  <for each="var video in Model">
    <div style="padding: 3px; margin:2px" class="video_choice" id="${video.YouTubeID}">
      <span id="video_name">${video.Name}</span><br/>
      <for each="var thumb in video.Thumbnails">
        <img src="${thumb}" />
      </for>      
    </div>    
  </for>

  # using(Html.BeginForm("YouTubeVideos","Profile", FormMethod.Post, new { id = "youTubeForm" }))
  # {
  <input type="hidden" id="video_names" name="video_names" />
  <input type="submit" value="add selected"/>

  # }

  <ScriptBlock>
    $(".video_choice").click(function() { 
      $(this).toggleClass('selected');
      var count = $(".selected").length;      
      $("#selectCount").html(count);
    });

    var options = {
      target: '#videos',
      beforeSubmit: function(arr, form, opts) {
        var names = [];
        $(".selected").each(function() {

          names[names.length] = $(this).attr('id');
        });
        var namestring = names.join(",");
        $("#video_names").attr('value',namestring);
        //alert(namestring);
        //arr["video_names"] = namestring;
        //alert($.param(arr));
        //alert($("#video_names").attr('value'));
        return true;
      }
    };

    $("#youTubeForm").ajaxForm(options);

  </ScriptBlock>

Essentially i display a series of divs that contain information pulled from the YouTube API. I use jQuery to allow the the user to select which videos they would like to add to their profile. When i submit the form i would like to populate the hidden field with a comma separated list of video ids. Everything works except that when i try to set the value of the field, in the controller on post, the field comes back empty. I am using the jQuery ajax form plugin.

What am i doing wrong that is not allowing the value i set in the field to be sent to the server?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about asp.net-mvc-2