6.1 取得表單資料
Last updated
Last updated
html:
<input type="text" id="the_text">
<button type="button" id="the_btn">取得值</button>
JavaScript:
var el_the_btn = document.getElementById("the_btn"); // 取得 button 元素
el_the_btn.addEventListener("click", function(){ // button 的 click 事件綁定
var el_the_text = document.getElementById("the_text"); // 取得欄位元素
console.log(el_the_text.value); // 取得值
});
例:
html:
<textarea id="the_textarea"></textarea>
<button type="button" id="the_btn">取得值</button>
JavaScript:
var el_the_btn = document.getElementById("the_btn");
el_the_btn.addEventListener("click", function(){ // button 的 click 事件綁定
var el_the_textarea = document.getElementById("the_textarea");
console.log(el_the_textarea.value);
});
例:
html:
<select id="the_select">
<option value="1">選項一</option>
<option value="2">選項二</option>
</select>
<button type="button" id="the_btn">取得值</button>
JavaScript:
var el_the_btn = document.getElementById("the_btn"); // 取得 button 欄位
el_the_btn.addEventListener("click", function(){ // button 的 click 事件綁定
var el_select = document.getElementById("the_select"); // 取得 select 下拉選單
console.log(el_select.value); // 取得 select 目前所選的值
console.log(el_select.options[el_select.selectedIndex].text); // 取得 select 目前所選的文字
});
例:
html:
<input type="radio" name="food_type" value="1" checked> 葷
<input type="radio" name="food_type" value="2"> 素
<button type="button" id="the_btn">取得值</button>
JavaScript:
var el_the_btn = document.getElementById("the_btn");
el_the_btn.addEventListener("click", function(){
var food_type = document.querySelector("input[name=food_type]:checked");
console.log(food_type.value);
});
例:
html:
<input type="checkbox" class="habits" value="1"> 興趣1
<input type="checkbox" class="habits" value="2"> 興趣2
<input type="checkbox" class="habits" value="3"> 興趣3
<button type="button" id="the_btn">取得值</button>
JavaScript:
var el_the_btn = document.getElementById("the_btn");
el_the_btn.addEventListener("click", function(){
var all_checked = document.querySelectorAll('.habits:checked'); // 取得有勾選的所有元素
var all_value = []; // 空陣列,預計用來存放每個有勾選的值
all_checked.forEach(function(item, index){ // 跑迴圈
all_value.push(item.value);
});
console.log(all_value);
});
例: