简体   繁体   中英

Pass data from a JavaScript array to an HTML form

I am trying to learn JavaScript and I came across a practice problem in a book I purchased that I cannot seem to crack. The task is to flesh out a javascript formBuilder function to generate HTML forms dynamically from a JavaScript array. I have copied the code from the book onto a CodePen page for visual and testing purposes.

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

HTML sample:

<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 sample:

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 sample:

//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"));
});

Errors in the codepen code exist, paste the code below into your project:

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"));
});

The last item in an array does not get a comma appended to it. Always ensure to end a line of code with a semi-colon as well. Those are the changes I made to your code, now it runs, as I assume, correctly unless you have any other issues?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM