在提交时,它会添加一行未定义的数据。如何验证提交的表单?

时间:2018-06-22 07:17:26

标签: javascript jquery html

如何验证表格?

我想提交。它不会添加行,也不会提交。

$(document).ready(function() {
  $("#form-submit").on('click', function(e) {
    e.preventDefault();

    var formdata = {
      first_name: $("#first-name").val(),
      last_name: $("#last-name").val(),
      middle_name: $("#middle-name").val(),
      gender: $('input[name="gender"]:checked').attr('value'),
      birthday: $("#birthday").val()
    }

    $("#student_data").append('<tr></tr>');
    $.each(formdata, function(key, value) {
      $('table tr:last').append('<td> ' + value + ' </td>');
    });
    $('table tr:last').append('<button class="dlt" href="#">Delete </button>  <button class="edit" href="#"> edit</button>')
    $("#demo-form1")[0].reset();
  });
});

1 个答案:

答案 0 :(得分:0)

  1. 您首先需要听提交事件
  2. 验证表单
  3. 将有效数据追加到表

// You need to listen to the submit event

$(document).ready(function() {
  $('#form').on('submit', function(event) {
    event.preventDefault();
    console.log('Click Submit form');
    const formData = {
      first_name: $('#first-name').val(),
    };
    // validate the form data
    // For example check that the first name is not empty
    if (formData.first_name.trim().length) {
      console.log('Do something with first name');
    } else {
      // will break the function and not continue
      return;
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <input type="text" id="first-name">
  <button type="submit">Submit</button>
</form>