Skip to content

Instantly share code, notes, and snippets.

@K90j1
Last active November 6, 2018 02:22
Show Gist options
  • Save K90j1/8623850 to your computer and use it in GitHub Desktop.
Save K90j1/8623850 to your computer and use it in GitHub Desktop.
どんどん増えるフォーム - recursive input form
# よくあるどんどん入力欄が増やせるフォーム
* フォームに入力してフォーカスが離れるともうひとつフォームができる
* 入力を削除すると空のフォームが消える
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #fdd;
font: 30px sans-serif;
}
<form role="form">
<div id="exampleEmailArea">
<div id="exampleEmailBlock1">
<div class="col-xs-12">
<div class="form-group">
<label for="exampleInputEmail1">Email address1</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email1">
</div>
</div>
</div>
</div>
</form>
jQuery(function () {
jQuery('#exampleInputEmail1').on('focusout', '', function () {
recAddingForm('exampleInputEmail', '#exampleEmailBlock', '#exampleEmailArea', emailAddressTag(), jQuery(this).attr('id'));
});
});
/**
* フォームを増やす
*
* @param {string} strElement 追加する要素
* @param {string} deleteElement 削除する要素
* @param {string} targetArea 追加するDIVエリア
* @param {string} addHtml 追加するHTML
* @param {string} idNum カウント
* @return {void}
*/
function recAddingForm(strElement, deleteElement, targetArea, addHtml, idNum) {
// idから番号をとる
var countId = parseInt(idNum.replace(strElement, ''));
if (jQuery('#' + strElement + countId).val() == ''
&& jQuery('#' + strElement + (countId + 1)).size() > 0
&& jQuery('#' + strElement + (countId + 1)).val() == '') {
// 入力後削除したのでフォームを消す
jQuery(deleteElement + (countId + 1)).fadeOut('fast', function () {
jQuery(this).remove();
});
return;
} else if (jQuery('#' + strElement + countId).val() == '') {
// 未入力
return;
} else if (jQuery('#' + strElement + (countId + 1)).size() > 0) {
// 次のフォームがある
return;
}
countId++;
jQuery(targetArea).append(addHtml.replace(/\?/g, countId.toString()));
jQuery('#' + strElement + countId).on('focusout', '', function () {
recAddingForm(strElement, deleteElement, targetArea, addHtml, jQuery(this).attr('id'));
});
}
function emailAddressTag() {
return '<div id="exampleEmailBlock?">' +
'<div class="col-xs-12">' +
'<div class="form-group">' +
'<label class="sr-only" for="exampleInputEmail?">Email address?</label>' +
'<input type="email" class="form-control" id="exampleInputEmail?" name="exampleInputEmail?" placeholder="Enter email?" maxlength="256">' +
'</div>' +
'</div>' +
'</div>';
}
@mahaman6715
Copy link

英語ryeえ

@mahaman6715
Copy link

えいぇry

@mahaman6715
Copy link

えりぇry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment