4.4 表單(Form)相關的操控

text 一般文字框的操作

.val():取值及設定值

html:

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

「取值」語法:

$("input.the_text").val();

「設定值」的語法:

$("input.the_text").val("要設定的值");

範例:

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

textarea 多行文字框取值及設定值

.val():取值及設定值

語法:(取得 textarea 的內容)

$("#the_textarea").val();

語法:(設定 textarea 的內容)

如果要斷行,要用 \n

$("#the_textarea").val("這是文字\n第二行");

範例:

select 下拉選單的操作

.val():取值及設定值

html:

<select name="the_select">
  <option value="1">選項一</option>
  <option value="2">選項二</option>
  <option value="3">選項三</option>
</select>

語法:

$("select[name='the_select']").val(); // 取值

$("select[name='the_select']").val("3"); // 設定值

範例:

.prop("selected", true) 設定值

語法:

$("select[name='the_select'] option[value='2']").prop("selected", true);

或:(使用 .eq(index) ,索引值 0 開始)

$("select[name='the_select'] option").eq(1).prop("selected", true);

範例:

.prop("selected") 及 .eq(index):判斷某選項是否有被選到

語法一:特定值

$("select[name='the_select'] option[value='2']").prop("selected");

語法二:使用 .eq(index),索引值 0 開始

$("select[name='the_select'] option").eq(1).prop("selected");

範例:

:selected 及 .text() 取得被選到的那項及取文字

語法:透過 :selected 取得已選到的那個 option:

$("select[name='the_select'] :selected")

語法:取得該 option 的文字:

$("select[name='the_select'] :selected").text()

語法:取得特定 option 的文字:

$("select[name='the_select'] option[value='3']").text();

範例:

checkbox 的操作

.val() 取值及設定值

語法:

$("#the_check").val(); // 取值

$("#the_check").val("123"); // 設定值

範例:

.prop("checked") 判斷有無勾選

語法:(有無勾選,回傳 true 或 false)

$("#the_check").prop("checked");

範例:

.prop("checked", bool) 勾選或不勾選

語法:

$("#the_check").prop("checked", true);
$("#the_check").prop("checked", false);

範例:

:checked 取得有勾選到的那些選項

語法:(會取到複數個)

$("input.item:checked")

勾選的個數有幾個:

$("input.item:checked").length

留意 :checked 左邊沒有空格;在 select 下拉選項的 :selected 的左邊是有空格的。

範例:

radio 單選框

html:

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

.prop("checked") 判斷有無選取

語法:

$("#check1").prop("checked");

範例:

:checked 取得有選到的那項

語法:取得有選到的那項的值

$("input[name='food_type']:checked").val();

範例:

.prop("checked", bool) 設定某項選取

語法:

$("#check3").prop("checked", true);

範例:

練習:checkbox 全選

建立 practice/check_all.html 來練習,提供 html:

<input type="checkbox" id="check_all"><label for="check_all">全選</label>

<hr>

<input type="checkbox" class="item" id="option1"> <label for="option1">選項一</label>
<input type="checkbox" class="item" id="option2"> <label for="option2">選項二</label>
<input type="checkbox" class="item" id="option3"> <label for="option3">選項三</label>

撰寫 jQuery 語法,完成如下影片示意:( https://youtu.be/7pMgVOY70os )

參考作法:

Last updated