LoginSignup
6
8

More than 5 years have passed since last update.

フォームのデータを取得する関数

Posted at

jQueryで $.ajax $.post $.get を使う際、
毎回作っているformのデータを抽出する関数です。

関数

getPostData.js
function getPostData(selector) {
    var postData = {};
    $(selector).find(':input').each(function(){
        if ($(this).attr("type") == 'checkbox' || $(this).attr("type") == 'radio') {
            if ($(this).is(":checked")) {
                postData[$(this).attr('name')] = $(this).val();
            }
        }
        else {
            postData[$(this).attr('name')] = $(this).val();
        }
    });
    return postData;
}

使い方

functions.js
$(document).ready(function() {
    $('.submit').click(function() {
        var postData = getPostData('.test_form');
        $.post('/target/url', postData, function() {
            // TODO 処理
        });
    });
});
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8