-
ID:ZAM7h4 さんの質問

htmlで作成したフォームの内容をページ遷移なしで同じページの特定要素に反映させたいのですが、チェックボックスで選択した内容がうまく表示されません。

javascriptのまったくの初心者なのですが、どなたか教えていただけないでしょうか。

javascriptコード
-------------------------------------------------
<script type="text/javascript">
window.onload = function () {
getValue();
var $formObject = document.getElementById( "sampleForm" );
for( var $i = 0; $i < $formObject.length; $i++ ) {
$formObject.elements[$i].onkeyup = function(){
getValue();
};
$formObject.elements[$i].onchange = function(){
getValue();
};
}
document.getElementById( "sampleOutputLength" ).innerHTML = $formObject.length;
}
function getValue() {
var $formObject = document.getElementById( "sampleForm" );
document.getElementById( "sampleOutputName" ).innerHTML = $formObject.formName.value;
document.getElementById( "sampleOutputArea" ).innerHTML = $formObject.formArea.value;
document.getElementById( "sampleOutputAge" ).innerHTML = $formObject.formAge.value;
document.getElementById( "sampleOutputComent" ).innerHTML = $formObject.formComent.value;
document.getElementById( "sampleOutputfood" ).innerHTML = $formObject.formfood.value;
document.getElementById( "sampleOutputsei" ).innerHTML = $formObject.formsei.value;
}
</script>
-------------------------------------------------

html
-------------------------------------------------
<form id="sampleForm">
【入力欄】
<br />
名前:<input type="text" name="formName" value="太郎">
<br />
相談内容:
<input type="hidden" name="formfood" />
<input type="checkbox" name="formfood[1]" />小児歯科<br>
<input type="checkbox" name="formfood[2]" />性別<br>
<br />
</form>
<div id="sampleOutput">
【出力欄】
<br />
名前:<span id="sampleOutputName"></span>
相談内容:<span id="sampleOutputfood"></span>
<br />
</div>

みんなの回答 1 件

ID:ofimVC さんの回答

checkboxの値はそれだと取得できない。
また今の書き方だとvalueが無いので、値がどのみち取れない。

checkboxの値の取得は下記が参考になると思う。
ttp://qiita.com/kazu56/items/0f3858d6af20bfd8f818
上記urlを参考にするのであれば、
1:まずチェックボックスに値とクラスを設定してあげて、
<input class="area" type="checkbox" name="formfood[1]" value="小児歯科" />小児歯科<input class="area" type="checkbox" name="formfood[2]" value="性別" />性別

2:下記コードでチェックボックスの値を拾って書き出す。
area = $(’[class="area"]:checked’).map(function(){
return $(this).val();
}).get().join(’,’);
document.getElementById( "sampleOutputfood" ).innerHTML = area;

こんな感じで出来ると思うがどうなんかな・・・

ID:8UCIw2

$.mapって知らなかったけど、超便利ですね

最終更新日:2015-04-09 (3,188 views)

関連するトピックス

ページ上部に戻る