6.2 設定表單資料

text 一般文字框的設定值

html:

<input type="text" class="the_text" id="the_text">

「設定值」的語法:

var the_text = document.getElementById("the_text");

// 以下三種方式皆可
the_text.value = "測試"; // 這個較常見,但不會改變到標籤上的屬性

//the_text.setAttribute("value", "測試二");
//the_text.defaultValue = "測試三"; // 極少見

範例:

type 等於 password、hidden 等類似一般文字框,操作都一樣。

textarea 多行文字框設定值

html:

<textarea id="the_textarea"></textarea>
<button type="button" id="the_btn">按鈕</button>

JS:

如果要斷行,要用 \n

var the_textarea = document.getElementById("the_textarea");
the_textarea.innerHTML = "這是文字\n新的一行";

範例:

select 下拉選單的設定值

html:

<select name="the_select" id="the_select">
  <option value="a">選項一</option>
  <option value="b">選項二</option>
  <option value="c">選項三</option>
</select>

JS:

var the_select = document.getElementById("the_select");
the_select.value = "c"; // 設定值

範例:

checkbox 的勾選

判斷有無勾選

html:

<input type="checkbox" id="the_checkbox">
<button type="button" id="the_btn">取文字</button>

JS:

var the_checkbox = document.getElementById("the_checkbox");
if(the_checkbox.checked){
  alert("有勾選");
}else{
  alert("沒有勾選");
}

範例:

設定勾選或不勾選

JS:

var the_checkbox = document.getElementById("the_checkbox");
if(the_checkbox.checked){ // 判斷目前有無勾選
  the_checkbox.checked = false; // 不勾選
}else{
  the_checkbox.checked = true; // 勾選
}

範例:

radio 單選框的選取

判斷有無選取

html:

<input type="radio" class="food_type" name="food_type" id="check1" value="1" checked>
<input type="radio" class="food_type" name="food_type" id="check2" value="2">
<input type="radio" class="food_type" name="food_type" id="check3" value="3">

<button type="button" id="the_btn">取文字</button>

JS:

var food_type = document.querySelectorAll("input[name='food_type']");
food_type.forEach(function(item, i){ // 執行迴圈
  console.log(item.checked); // 該項是否有勾選
});

範例:

設定某項選取

JS:

var food_type = document.getElementById("check3");
food_type.checked = true;

範例:

Last updated