2012-12-13 19 views
0

嘿我写了一个函数getNewId,返回一个基于时间戳的随机数 我希望能够在空[]中获得该数字,以便当我检查元素看看它看起来像这样如何让函数进入我的空[]

名= “位置[timestamp_from_function] [街]”

这里的代码在
http://jsfiddle.net/d0okie0612/22cTn/

在这里工作的小提琴IM是我的HTML

<div id="container"> 
    <div id="top_form"> 
    <form> 
    Street: <input class="street" name="locations[][street]" id="form_element" type="text"> <br><br> 
     City: <input class="city" name="locations[][city]" id="form_element" type="text"> 
     <select> 
     <option value=" ">State</option> 
     <option value="ca">CA</option> 
     <option value="az">AZ</option> 
     <option value="de">DE</option> 
     </select> 
     Zip: <input name="locations[][zipcode]" type="text"><br /><br /> 
    </form> 
    </div> 
    </div> 

<br /> 
<a href="#" id="awsomeButton">+ Add Location</a> 
    <br /> 


提交

继承人的脚本

 var tpl = "" 
    + "<div id='location_div_<%= id %>'><h1>My Location #<%= id %></h1></div>"; 

     var newId = new Date().getTime(); 
     var template = _.template(tpl); 
     var compiled = template({id: newId}); 

     var addedForm = "<div id='added_form'>" 
     + "<a href='#' class='close_btn'>x</a>" 
     + "Street: <input name='locations[][street]' type='text'>" 
      + "<br /><br />" 
      + "City: <input name='locations[][city]' type='text'>" 
      + "<select>" 
      + "<option value=' '>State</option>" 
      + "</select>" 
      + "Zip: <input name='locations[][zipcode]' type='text'>" 
      + "</div>" 


      function getNewId() { 
      var newId = new Date().getTime(); 
      return newId; 
      } 

      var myArray = []; 
      $('#awsomeButton').on('click', function(e) { 
      $(addedForm).hide().appendTo('form').fadeIn('slow'); 

      }); 


      $('.close_btn').live('click', function (e) { 
      e.preventDefault(); 
      $(this).parents('div#added_form:first').fadeOut('slow', function() { 
      $(this).remove();  

     }); 
     }); 

我还挺想这应该是容易的,但在失去了IM,请帮助

+0

无关,但你拼写'add location'按钮错误 – Luke

+0

为什么你不把它做成一个下划线模板,就像你用'tpl'完成的那样? – Bergi

+0

@BubbaWoop那么你拼写错了,所以它似乎我们有一个拼写警察对峙:) –

回答

0
$("#added_form input[name^=locations\\[\\]]").each(function(input){ 
    var name = input.attr("name"); 
    var match = name.match(/^locations\[\]\[(.*)\]$/) 
    if(match.length > 1) { 
     var newName = "locations["+getNewId()+"]["+match[1]+"]"; 
     input.attr("name", newName); 
    } 
});