---
# System prepended metadata

title: "\U0001F3C5 Day 27 - 表單取值觀念"
tags: [JS 直播班 - 2023 秋季班]

---

---
tags: JS 直播班 - 2023 秋季班
---
# 🏅 Day 27 - 表單取值觀念

今天要來補充一些表單取值的觀念，請大家跟著一起練習

### 1. `.value` 取出的值是「字串」
這邊以 input 的 value 取值為例，請觀看以下範例：

HTML
```htmlembedded=
<input type="text" id="targetInput">
<button type="button" id="triggerBtn">觸發按鈕</button>
```
JS
```javascript=
const el = document.querySelector('#targetInput');
const triggerBtn = document.querySelector('#triggerBtn');

triggerBtn.addEventListener('click', function(e){
    console.log(el.value);
    console.log(typeof(el.value));
})
```
如果在 input 輸入數字 123 以後點選「觸發按鈕」，可以在 console 中觀察到以下結果：

![](https://i.imgur.com/18bzrew.png)
> `.value` 取出來的值為字串

**因此如果要對表單的「數值」進行運算，請記得要先使用 `parseInt` 做型別轉換。**

範例如下：
HTML
```htmlembedded=
<input type="text" id="targetInput">
<button type="button" id="triggerBtn">觸發按鈕</button>
```
JS
```javascript=
const el = document.querySelector('#targetInput');
const triggerBtn = document.querySelector('#triggerBtn');

triggerBtn.addEventListener('click', function(e){
    let newValue = parseInt(el.value);  // 轉為 Number
    console.log(newValue);
    console.log(typeof(newValue));
})
```
結果：

![](https://i.imgur.com/k18ol8z.png)



### 2. `.value`, `.getAttribute('value')` 的差異

HTML
```htmlembedded=
<input type="text" id="targetInput" value="123">
<button type="button" id="triggerBtn">觸發按鈕</button>
```
JS
```javascript=
const el = document.querySelector('#targetInput');
const triggerBtn = document.querySelector('#triggerBtn');
console.log(`el.value: ${el.value}`);

triggerBtn.addEventListener('click', function(e){
    el.value = "任意填入的值";
    console.log(`el.value: ${el.value}`);
})
```

console 結果：

![](https://i.imgur.com/HYHEDTk.png)


看到這邊，同學是不是認為 `<input type="text" id="targetInput" value="123">` 這行程式碼的 `value="123"` 應該已經被修改為 `value="任意填入的值"` 了? 

>不過，如果我們將程式碼修改如下，並一樣的點選「觸發按鈕」觀察結果:

HTML
```htmlembedded=
<input type="text" id="targetInput" value="123">
<button type="button" id="triggerBtn" >觸發按鈕</button>
```
JS
```javascript=
const el = document.querySelector('#targetInput');
const triggerBtn = document.querySelector('#triggerBtn');

triggerBtn.addEventListener('click', function(e){
    el.value = "任意填入的值";
    console.log(`el.value: ${el.value}`);
    console.log(`el.getAttribute('value'): ${el.getAttribute('value')}`);
})
```

可以發現網頁上 input 欄位「輸入的值」的確已經被更改為 "任意填入的值"

![](https://i.imgur.com/dI37ggU.png)

但是 `el.value` 與 `el.getAttribute('value')` 卻是不一樣的，呈現結果如下：

![](https://i.imgur.com/1RXP4aB.png)


**由此可知，修改 `el.value` 不等於修改 HTML 標籤的 value 屬性值**

### 統整：
* `el.value` 對應的是 input 欄位目前「輸入的值」
* `el.getAttribute('value')` 對應的是 input 標籤的「預設屬性值」
* 修改 `el.value` 並不會影響 input 標籤的 value 預設屬性，使用 `setAttribute()` 才會。

### 補充 `e.target.value`
在[前一天](https://hackmd.io/TWaSTJ3lRNaDdK9xanxAkQ)有提到事件監聽內函式有一個參數（這邊以 e 表示），e 是一個物件，其中有一個 target 屬性為觸發事件時的元素，此時就可以直接利用 `e.target` 搭配 `.value` 來取得該表單元素觸發事件時的值。

HTML
```htmlembedded=
<select name="num" class="num">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
```
JS
```javascript=
const num = document.querySelector('.num');
num.addEventListener('change', function(e) {
  // 當 select 選項改變時就會觸發
  // 觀察下方印出的值
  console.log(e.target);  
  console.log(e.target.value);  
  console.log(typeof(e.target.value));
});
```

問題
---
請修改 JS 程式碼來符合下面要求，以下為點擊「觸發按鈕」後所需觸發的程式行為。
（請觀察網頁畫面渲染的變化與 console 結果）


1. 將 newValue 轉型為數字型別。
2. 執行 newValue += 300;
3. 將 `el.value` 重新賦值為 newValue。
4. 用 console.log 輸出 `el.value`。
5. 使用 `getAttribute` 取得 el 的 「value 屬性值」，並透過 console.log 輸出。

HTML
```htmlembedded=
<input type="text" id="targetInput" value="200">
<button type="button" id="triggerBtn">觸發按鈕</button>
```
JS
```javascript=
const el = document.querySelector('#targetInput');
const triggerBtn = document.querySelector('#triggerBtn');

triggerBtn.addEventListener('click', function(){
    let newValue = el.value;
    /* 程式碼撰寫區 */
})
```

**進階題**

監聽下方 select 元素（ `.selectPets` ），當改變 select 選項時，讓 p 標籤內呈現出該選項的文字。
（提示：運用 change 事件及表單取值）

HTML
```htmlembedded=
<select name="pets" class="selectPets">
  <option value="" selected disabled>Choose</option>
  <option value="Dog">Dog</option>
  <option value="Cat">Cat</option>
  <option value="Rabbit">Rabbit</option>
</select>
<p class="choosePet">Pets</p>
```
JS
```javascript=
const selectPets = document.querySelector(".selectPets");
const choosePet = document.querySelector(".choosePet");
/* 程式碼撰寫 */
...
```


## 回報流程

將答案寫在 CodePen 並複製 CodePen 連結貼至底下回報就算完成了喔! 
解答位置請參考下圖（需打開程式碼的部分觀看）

![](https://i.imgur.com/vftL5i0.png)

<!-- 解答：  

const el = document.querySelector('#targetInput');
const triggerBtn = document.querySelector('#triggerBtn');

triggerBtn.addEventListener('click', function(){
  let newValue = el.value;
  /* 程式碼撰寫區 */
  newValue = parseInt(newValue);
  newValue += 300;
  el.value = newValue;
  console.log(el.value);
  console.log(el.getAttribute("value"))
})

進階題：
const selectPets = document.querySelector(".selectPets");
const choosePet = document.querySelector(".choosePet");
/* 程式碼撰寫 */
selectPets.addEventListener("change", function(e) {
  choosePet.textContent = e.target.value;   // 寫法一
  choosePet.textContent = selectPets.value;  // 寫法二
});
-->




回報區
---


|   Discord    |                    CodePen / 答案                      |
|:----------:|:-------------------------------------------------------:|
|lychee_kk|[codepen](https://codepen.io/kakakala/pen/xxMLWKZ)|
|pinyi_9|[codepen](https://codepen.io/Wpypy/pen/yLZovKQ?editors=1011)|
|銀光菇|[CodePen](https://codepen.io/genesynthesis/pen/rNPzdmO)|
|yuan!|[CodePen](https://codepen.io/townyuan/pen/dyazmvz)|
|Peng|[CodePen](https://codepen.io/H-Peng/pen/gOqxeBQ?editors=1010)|
|yuling|[CodePen](https://codepen.io/igzdflpu/pen/GRzvxLP)|
| Alyce |[CodePen](https://codepen.io/alycehwy/pen/gOqxzKb?editors=1010)|
| Winnie |[CodePen](https://codepen.io/codepen-io-winnie/pen/NWovYjo?editors=1011)|
|CPing|[CodePen](https://codepen.io/CPing/pen/mdvMKbe?editors=1011)|
|dodo_6666 |[CodePen](https://codepen.io/MissDouble/pen/xxMLjgj)|
| cest_jessie |[CodePen](https://codepen.io/itsjessiechen/pen/XWOaqwB)|
| hsu0921 |[CodePen](https://codepen.io/HSUANIN0327/pen/vYbJRed)|
| Oria |[CodePen](https://codepen.io/kajing/pen/BaMdVzW?editors=1010)|
| 精靈 |[CodePen](https://codepen.io/justafairy/pen/zYedaKe)|
| Helen |[CodePen](https://codepen.io/milkteamonster/pen/gOqxzjb?editors=1111)|
| Eden |[Codepen](https://codepen.io/iseden/pen/LYqjrLY)|
| yuan2781 |[CodePen](https://codepen.io/ismebir/pen/wvNqXxp)|
| celinelinnn |[CodePen](https://codepen.io/celinephoebe/pen/QWYMxEO)|
| 小夏 |[CodePen](https://codepen.io/michaelhsia/pen/yLZoqam)|
| RX00 |[CodePen](https://codepen.io/llqzknqv-the-styleful/pen/zYedLLo?editors=1011)|
| 維哲 |[CodePen](https://codepen.io/kwz1202/pen/gOqxjKB)|
| Uli |[CodePen](https://codepen.io/uli1313/pen/yLZoqwe?editors=1011)|
| Chia Pin |[CodePen](https://codepen.io/joker-cat/pen/QWYMVpN)|
|Moreene|[CodePen](https://codepen.io/Moreene/pen/qBgXMry)|
| Yijing |[CodePen](https://codepen.io/Yi-Jing-71080635/pen/LYqjJjg?editors=0011)|
| Yijing |[CodePen](https://codepen.io/colorgolden/pen/qBgXMKQ?editors=1011)|
| runweiting |[CodePen](https://codepen.io/weiting14/pen/VwgzEpL)|
| ming0712 |[CodePen](https://codepen.io/StevenHuang/pen/KKJvGvR?editors=1010)|
| Fabio |[CodePen](https://codepen.io/fabio7621/pen/YzBxJaW?editors=1011)|
| kuanju27 |[CodePen](https://codepen.io/Eero-Chiao/pen/yLZoQvL)|
| santu0868 |[CodePen](https://codepen.io/HatsumiSan/pen/rNPzQKL?editors=1111)|
| phyllis |[CodePen](https://codepen.io/gmoxhrmc-the-styleful/pen/WNPEYBe)|
| ann6212 |[CodePen](https://codepen.io/yqmegupa-the-styleful/pen/jOdLQOX?editors=1011)|
| 奔跑吧(GTR150)) |[CodePen](https://codepen.io/Wer-Qwe/pen/yLZoZNv)|
| claire |[CodePen](https://codepen.io/yi-wen-chen/pen/zYedLQw)|
| kawa |[CodePen](https://codepen.io/z83xji6/pen/zYedbov?editors=1011)|
| dora |[CodePen](https://codepen.io/dorayu/pen/JjxyeXR?editors=1011)|
| 保羅 |[CodePen](https://codepen.io/paul-1997/pen/oNmeOMm?editors=1011)|
| 荷菓かのり|[CodePen](https://codepen.io/oogxwkvw-the-builder/pen/poGrBYr?editors=1011)|
| Rogan |[CodePen](https://codepen.io/RoganHsu/pen/XWOaLmW?editors=1011)|
| xin |[CodePen](https://codepen.io/Estherrrrrr999/pen/bGzrmQv)|
| xain |[CodePen](https://codepen.io/ppzigmtg-the-typescripter/pen/ZEwJgWL?editors=1010)|
| gebyman |[CodePen](https://codepen.io/gebyman/pen/NWovQER?editors=1011)|
| yu.t_liu |[CodePen](https://codepen.io/pen/?editors=1010)|
| Ching |[CodePen](https://codepen.io/tzuchingg/pen/jOdGWyW?editors=1011)|
| JUNEW |[CodePen](https://codepen.io/June-W/pen/BaMwWJa)|
| xiaokui_71292 | [CodePen](https://codepen.io/pen?template=JjxrOxN)|
| 郭芙蘭#6374 | [CodePen](https://codepen.io/flora_Kuo/pen/xxMXpNa?editors=1011)|
| Joy-chiang |[CodePen](https://codepen.io/fwysphbw-the-vuer/pen/abXLGYq?editors=1011)|
| Ataraxia |[CodePen](https://codepen.io/ataraxia8888/pen/eYxRedZ)|
| SHUO |[CodePen](https://codepen.io/xrzarxkl-the-reactor/pen/GRzMwqv)|
| MY |[CodePen](https://codepen.io/ahmomoz/pen/zYeEXgW?editors=1111)|
| Mattie |[CodePen](https://codepen.io/mattielin/pen/KKJyzPa)|
| 風羽 |[CodePen](https://codepen.io/Joy-Huang/pen/abXVBqP?editors=1011)|
| stone4584 |[CodePen](https://codepen.io/Royen0506/pen/eYxeRpx?editors=1111)|
| damon0323 |[CodePen](https://codepen.io/swk9eny2/pen/ZEwayEm?editors=1011)|
|yaoling.liang|[CodePen](https://codepen.io/Yao-Ling-L-/pen/poGdKMV?editors=1011)|
| 歐陽龍龍#1061 |[CodePen](https://codepen.io/dizzydog-rgb/pen/PoVOdXv)|
| shcopy |[CodePen](https://codepen.io/shcopy/pen/dyaJGRZ)|
| shuuu |[CodePen](https://codepen.io/afjrvjzl-the-bashful/pen/NWoXRjm?editors=1011)|
| tanuki5863 |[CodePen](https://codepen.io/tanuki320/pen/ExroZar?editors=1011)|
| ⭐️小正 |[CodePen](https://codepen.io/colorgolden/pen/qBgXMKQ?editors=1111)|
| davidtt |[CodePen](https://codepen.io/David-Tsai/pen/XWOVQaX?editors=1011)|
| JasonFu |[CodePen](https://codepen.io/jie-Fu/pen/MWLQjGY?editors=1011)|
| xuan |[CodePen](https://codepen.io/xuan0915/pen/wvNymXq?editors=1011)|
| 依依 |[CodePen](https://codepen.io/Rita-Yang/pen/dyadqgz?editors=1011)|
| ChrisSQR |[CodePen](https://codepen.io/ChrisSQR/pen/JjxpmBZ)|
| Vivian2857 |[CodePen](https://codepen.io/vivian_lin/pen/wvNyLoz?editors=1011)|
|    Jerry |[CodePen](https://codepen.io/ildkosxk-the-encoder/pen/ZEwozWG)|
|Lainie|[CodePen](https://codepen.io/Lainie88/pen/BaMxrza?editors=1011)|
|_shun0130| [CodePen](https://codepen.io/koba60052ww/pen/WNPJYOw?editors=1011)
|Hank._.z| [CodePen](https://codepen.io/linoiaby-the-sans/pen/OJdEyLG?editors=1111)
|nini1202desu| [CodePen](https://codepen.io/tvxq5206/pen/poGZPrG?editors=1011)
|Iris| [CodePen](https://codepen.io/iris831206/pen/GRzBELb?editors=1111)
|macihuang| [CodePen](https://codepen.io/macy1215/pen/abXaoaO)
|bf_tsai| [CodePen](https://codepen.io/BF-Tsai/pen/QWYVbLO?editors=0011)
|Rochel|[Codepen](https://codepen.io/rochelwang1205/pen/bGzxyRo?editors=1011)
|阿賀#3700|[Codepen](https://codepen.io/sungho/pen/poGOMMd?editors=1011)
|NathanJames|[Codepen](https://codepen.io/ufo060204/pen/Jjxmddz)|
|skypassion5000|[Codepen](https://codepen.io/skypassion5000/pen/poGxMov?editors=1111)|
|Daylily|[Codepen](https://codepen.io/daylily/pen/ZEwmyrd)|
| 辣椒 | [Codepen](https://codepen.io/chilichen118/pen/wvNQYbe) |
|阿榮|[Codepen](https://codepen.io/codeitaday/pen/gOqZBrJ)|
|nikkita_3544|[Codepen](https://codepen.io/vanessa7259/pen/VwgqRpL?editors=1111)|
|Andy|[Codepen](https://codepen.io/andy31342/pen/jOddBdN?editors=1011)|
|sponge|[Codepen](https://codepen.io/biunpujm-the-flexboxer/pen/wvNNePe?editors=1111)|