将数据从JavaScript数组传递到HTML表单

时间:2015-05-27 15:10:12

标签: javascript html json

我正在尝试学习JavaScript,并且在我购买的一本书中遇到了一个练习题,我似乎无法破解。任务是充实javascript formBuilder函数,从JavaScript数组动态生成HTML表单。我已将书中的代码复制到CodePen页面上,用于视觉和测试目的。

CodePen:http://codepen.io/anon/pen/gpwZMX

HTML示例:

<div>
  <button data-sample='1'>Run 1</button>
  <button data-sample='2'>Run 2</button>
  <button data-sample='3'>Run 3</button>
</div>

<hr>
<div id='spec'>
  <i>This div will display the currently-processed spec</i>
</div>
<br>Output:
<div id='result'>
  <i>I sure wish I had a cool html form in me...</i>
</div>

<!--here are some test cases in docblock form-->
<div class='testcase' id='1'>
  /** Comment Form
     * Make a comment on the blog post!
     * @param  string[100] title
     * @param  email email
     * @param  text body
     * @param  bool subscribe Email me when someone comments on my comment!
     */
</div>

JavaScript示例:

var samples = [
  {
    title:"Comment Form",
    desc:"Make a comment on the blog post!",
    params:[
      { 
        type: 'text',
        max_length: 100,
        name: 'title'
      },
      {
        type: 'email',
        name: 'email'
      },
      {
        type:'textarea',
        name:'body'
      },
      {
        type:'checkbox',
        name:'subscribe',
        label:'mail me when someone comments on my comment!'
      }
    ]
  }]

formBuilder示例:

//builds an HTML form using all information present in `spec` and places the resulting HTML in jquery element `$el`
function formBuilder(spec,$el){
  $el.html("<i>I still wish I had a cool html form in me...</i>");
}


$("button").on("click",function($e){
  var specIndex = $($e.target).data('sample');
  var specData = samples[specIndex-1];

  $("#spec").html("Sample spec "+(specIndex)+" looks like: <br>"+JSON.stringify(specData));

  formBuilder(specData, $("#result"));
});

1 个答案:

答案 0 :(得分:-1)

存在codepen代码中的错误,将下面的代码粘贴到您的项目中:

var samples = [
{
    title:"Comment Form",
    desc:"Make a comment on the blog post!",
    params:[
      { 
        type: 'text',
        max_length: 100,
        name: 'title'
      },
      {
        type: 'email',
        name: 'email'
      },
      {
        type:'textarea',
        name:'body'
      },
      {
        type:'checkbox',
        name:'subscribe',
        label:'mail me when someone comments on my comment!'
      }
    ]
  },
  {
    title:"Car Order Form",
    desc:"Choose your car!",
    params:[
      { 
        type:'select',
        values:['red','blue','green','black','white','taupe'],
        name: 'color'
      },
      {
        type: 'checkbox',
        values:['fog-lights','radio','a-c','wheels','headlights'],
        name: 'options'
      },
      {
        type:'string',
        minLength:7,
        maxLength:7,
        name:'vanityPlate',
        optional:true
      },
      {
        type:'int',
        name:'price',
      }
    ]
  },
  {
    title:"New User Creator",
    desc:"Create a new user account",
    params:[
      { 
        type:'string',
        maxLength:20,
        name:'fname',
        label:'First Name'
      },
      { 
        type:'string',
        maxLength:20,
        name:'lname',
        label:'Last Name'
      },
      { 
        type:'date',
        name:'dob',
        label:'Date of Birth'
      },
      {
        type:'email',
        multiple:true,
        maxCount:4,
        name:'emails',
        label:'Email Addresses'
      },
      {
        type: 'string',
        name: 'addr1',
        label: 'Street Address'
      },
      {
        type: 'string',
        name: 'city'
      },
      {
        type: 'state',
        name: 'state',
      },
      {
        type: 'int',
        name: 'zipcode',
        maxValue: 99999,
        minValue: 0,
        label: 'ZIP'
      },
    ]
  }
]

//builds an HTML form using all information present in `spec` and places the resulting HTML in jquery element `$el`
function formBuilder(spec,$el){
  var inputs = getInputs(spec);
  $el.html("<form title='"+spec.title+"'><fieldset><legend>"+spec.desc+"</legend>"+inputs+"</fieldset></form>");
}

function getInputs(spec) {
  var inputs = "";
  for(var i = 0; i < spec.params.length; i++) {
    var input = "<input ";
    var attributes = JSON.stringify(spec.params[i]).split(",");
    console.log(attributes);
    for(var j = 0; j < attributes.length; j++) {
      $.each(spec.params[i], function(key, value) {
        input += key + "='" + value + "' ";
      });
    }
    inputs += input + "/><br/>";
  }
  return inputs;
}


$("button").on("click",function($e){
  var specIndex = $($e.target).data('sample');
  var specData = samples[specIndex-1];

  $("#spec").html("Sample spec "+(specIndex)+" looks like: <br>"+JSON.stringify(specData));

  formBuilder(specData, $("#result"));
});

数组中的最后一项没有附加逗号。始终确保使用分号结束一行代码。这些是我对您的代码所做的更改,现在它正如我所假设的那样运行,除非您有任何其他问题?