简体   繁体   English

使用javascript收集表单输入值的捷径

[英]Short cut way of collecting form input values using javascript

I have a form that collects information from a user. 我有一个从用户收集信息的表单。 The form is composed of 10 input text field. 表单由10个输入文本字段组成。 The individual value of input text field is accessed via var first_name = $("#fname").val() as an example and passed to var postdata = {'fname':first_name}; 输入文本字段的单个值通过var first_name = $("#fname").val()作为示例访问并传递给var postdata = {'fname':first_name}; and then passed to ajax with url: "<?php echo base_url(); ?>main_controller/save_data", data: postdata then the controller function again will collect it. 然后用url: "<?php echo base_url(); ?>main_controller/save_data", data: postdata传递给ajax url: "<?php echo base_url(); ?>main_controller/save_data", data: postdata然后控制器函数再次收集它。 If I have 30 input text field and then used this way, it would take me a lot of time. 如果我有30个输入文本字段然后以这种方式使用,那将花费我很多时间。 What is the best way to pass numerous input field values using javascript in miniature way? 使用javascript以微缩方式传递众多输入字段值的最佳方法是什么? Is there a shortcut for this? 这有什么捷径吗? Thanks a lot. 非常感谢。 I have a sample code below. 我在下面有一个示例代码。

Views: 浏览次数:

<input class="input input-large" type="text" name="fname" id="fname" value=""/>
<input class="input input-large" type="text" name="lname" id="lname" value=""/>
<input class="input input-large" type="text" name="address" id="address" value=""/>
<input class="input input-large" type="text" name="age" id="age" value=""/>
<input class="input input-large" type="text" name="height" id="height" value=""/>
<input class="input input-large" type="text" name="gender" id="gender" value=""/>
<input class="input input-large" type="text" name="school" id="school" value=""/>
<input class="input input-large" type="text" name="course" id="course" value=""/>
<input class="input input-large" type="text" name="year" id="year" value=""/>
<input class="input input-large" type="text" name="date_of_birth" id="date_of_birth"
value=""/>

<button class="btn btn-success" id="save" name="save">Save</button>

<script type="text/javascript">
$("#save").click(function(){
    var fname = $("#fname").val();
    var lname = $("#lname").val();
    var address = $("#address").val();
    var age = $("#age").val();
    var height = $("#height").val();
    var gender = $("#gender").val();
    var school = $("#school").val();
    var course = $("#course").val();
    var year = $("#year").val();
    var date_of_birth = $("#date_of_birth").val();

    var postdata = {
            'fname': fname,
            'lname': lname,
            'address': address,
            'age': age,
            'height': height,
            'gender': gender,
            'school': school,
            'course': course,
            'year': year,
            'date_of_birth': date_of_birth
    };

    $.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>main_controller/save_data",
        data: postdata,
        success: function (data) {
            if (data.notify) {
                alert('success');
            } else {
                alert('Failed');
            }
        }
    });

    });
</script>

Controller: 控制器:

function save_data(){
    $fname = $this->input->post('fname');
    $lname = $this->input->post('lname');
    $address = $this->input->post('address');
    $age = $this->input->post('age');
    $height = $this->input->post('height');
    $gender = $this->input->post('gender');
    $school = $this->input->post('school');
    $course = $this->input->post('course');
    $year = $this->input->post('year');
    $date_of_birth = $this->input->post('date_of_birth');
    $this->insert_model->save_data($fname,$lname,$address,$age,$height,$gender,$school,$course,$year,$date_of_birth);
 }

Indeed there is: 确实有:

$("#save").click(function () {

    var postData = $("#idOfYourForm").serialize();

    $.ajax({
        type: "POST",
        url: "<?php echo base_url(); ?>main_controller/save_data",
        data: postdata,

        // it is perhaps better to specify the dataType
        // of the data expected back from the server 
        // for readability
        dataType: 'json',
        success: function (data) {
            if (data.notify) {
                alert('success');
            } else {
                alert('Failed');
            }
        }
    });

    // maybe you need this
    return false;
});

http://api.jquery.com/serialize/ http://api.jquery.com/serialize/

You could do this: 你可以这样做:

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// get inputs[index] element.
}

You can get more information from the NodeList reference. 您可以从NodeList参考中获取更多信息。

Use JQuery serialize() method It effectively turns the form values(input/select..) into a valid querystring. 使用JQuery serialize()方法它有效地将表单值(input / select ..)转换为有效的查询字符串。

$.ajax({
   type:"POST",
   url:"<?php echo base_url(); ?>main_controller/save_data",
   data:$('form').serialize(),
   success: function(data){
   if(data.notify){
   alert('success');
  }
  else{
   alert('Failed');
  }
 }
});

serialize () documentation: link serialize ()文档: 链接

var formelements = {}
$(input).each()
{
formelements[$(this).attr('name')] = $(this).val();
}

now all your values are stored inside the formelements, you can even send this element instead of manually sending all form elements: 现在你的所有值都存储在formelements中,你甚至可以发送这个元素而不是手动发送所有表单元素:

$.ajax({
   type:"POST",
   url:"<?php echo base_url(); ?>main_controller/save_data",
   data:formelements,
   dataType:"json",
   success: function(data){
   if(data.notify=="Success"){
   alert('success');
  }
  else{
   alert('Failed');
  }
 }
});

Non-serialization alternative: 非序列化替代方案:

If you need an array of form fields somewhere else in your script (for example, for client-side validation purposes) you can use the following alternative of .serialize() : 如果在脚本中的其他位置需要一组表单字段(例如,出于客户端验证目的),可以使用以下替代的.serialize()

var postdata = {};
$(".input").each(function () {
  postdata[$(this).attr("name")] = $(this).val();
});

Now postdata contains the array of values (like in your initial code snippet) instead of querystring. 现在postdata包含值数组(比如在初始代码片段中)而不是querystring。

PS: Add some special class attribute to your form fields instead of input which I have used just for example. PS:在表单字段中添加一些特殊的类属性,而不是我刚才使用的input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何填充使用 JavaScript 使用短代码生成的多个联系表单输入字段? - How to populate multiple contact form input fields which are generated with short-codes using JavaScript? 使用JavaScript / jQuery将制表符后的字符串值剪切并粘贴到下一个输入 - Cut and Paste string values to next input after tab character using JavaScript/jQuery 如何在 Javascript 中缩短多个 if else 语句 - How to cut short multiple if else statements in Javascript 使用JavaScript导出具有表格输入值的HTML表格 - Export html table with form input values in it using JavaScript 无法使用javascript从输入表单获取值 - Unable to get values from input form using javascript 如何仅使用 Javascript 将表单输入值存储在 JSON 文件中? - How to store Form Input Values in JSON File Using Only Javascript? PHP - HTML -JAVASCRIPT 将表单 A 中的值复制到表单 B 并将表单 B 中的值用作 DB 的输入 - PHP - HTML -JAVASCRIPT Copying values from form A into form B and using those from Form B as input for DB 使用JavaScript收集AJAX生成的文本框值 - Collecting AJAX generated text box values with JavaScript 从 HTML 收集表单数据并使用 Javascript 作为 Bootstrap 的卡片组件进行渲染 - Collecting Form data from HTML and rendering using Javascript as card component from Bootstrap is used 使用表单中的会话值输入 - Input using session values in the form
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM