フォームの内容を表に追加するjQuery

jQueryを使い、フォームの内容を一行(tr要素)にまとめ、表(table要素)に最後の行(tr要素)として追加する方法。

実装例

【入力欄】
名前:
地域:
年齢:
コメント:
名前 地域 年齢 コメント

実装例の動作について

「【入力欄】」の「追加」ボタンをクリックすると、「【入力欄】」のフォームの内容を一行にまとめ、「【入力欄】」の下の表に追加する。

ソースコード

JavaScript

<script type="text/javascript">
function appendToTable() {
    var $formObject = jQuery( '#sampleForm' );
    var $tableObject = jQuery( '#sampleTable' );
    var $tr = "<tr>";
    $tr += "<td>" + $formObject.find( '[name=formName]' ).val() + "</td>";
    $tr += "<td>" + $formObject.find( '[name=formArea]' ).val() + "</td>";
    $tr += "<td>" + $formObject.find( '[name=formAge]' ).val() + "</td>";
    $tr += "<td>" + $formObject.find( '[name=formComent]' ).val() + "</td>";
    $tr += "</tr>";
    $tableObject.append( $tr );
}
</script>

主に使用しているAPI

HTML

<div id="wrapSampleForm">
    <form id="sampleForm">
        【入力欄】
        <br />
        名前:<input type="text" name="formName" value="太郎">
        <br />
        地域:
            <select name="formArea">
                <option selected>関東</option>
                <option>東海</option>
                <option>関西</option>
            </select>
        <br />
        年齢:
            <select name="formAge">
                <option selected>10代</option>
                <option>20代</option>
                <option>30代</option>
            </select>
        <br />
        コメント:<textarea name="formComent">コメント</textarea>
        <br />
    </form>
    <button onclick="appendToTable()">追加</button>
</div>
<table id="sampleTable">
    <tr>
        <th id="tableName">名前</th>
        <th id="tableArea">地域</th>
        <th id="tableAge">年齢</th>
        <th id="tableComent">コメント</th>
    </tr>
</table>

CSS

<style>
#wrapSampleForm {
    width: 500px;
    margin: 10px;
    padding: 10px;
    border: 1px solid gray;
    border-radius: 10px;
}
#wrapSampleForm {
    background-color: #f0f8ff;
}
#sampleTable {
    background-color: #ffffcc;
}
#sampleTable th {
    color: #000000 !important;
}
#sampleTable th,
#sampleTable td {
    font-size: 15px !important;
    border: 1px solid gray;
    background-color: #ffffcc;
}
#tableName {
    width: 20%;
}
#formArea {
    width: 15%;
}
#formAge {
    width: 15%;
}
#tableComent {
    width: 50%;
}
#sampleForm * {
    margin: 0 0 7px 0;
    vertical-align: text-top;
}
</style>

スポンサード リンク

カテゴリー: API, JavaScript, jQuery, フォーム, , 逆引き パーマリンク