表單功能: 點選選項時, 選項內容自動複製到另個文字輸入框

今天在社團看到有人發問, 有人的回答,

讓我認識了onchange & oninput event,


解決方案的完整code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<select name="option" id="option">
<option value="選項1">選項1</option>
<option value="選項2">選項2</option>
<option value="選項3">選項3</option>
</select>
<textarea name="content" id="content" cols="30" rows="10"></textarea>

<script>

console.clear();

var o = document.getElementById("option");
var c = document.getElementById("content");

o.addEventListener("change", function() {

c.value = o.value;

});

</script>
</body>
</html>


最後, 說明一下語法,

onchange定義:

--> occurs when the value of an element has been changed.

--> This event is similar to the oninput event:

- The difference is that the oninput event occurs immediately after the value of an element has changed,

- while onchange occurs when the element loses focus, after the content has been changed.

-The other difference is that the onchange event also works on <keygen> and <select> elements.

onchange Event:
http://www.w3schools.com/jsref/event_onchange.asp



oninput定義:

--> occurs when an element gets user input.

oninput Event:
http://www.w3schools.com/jsref/event_oninput.asp



留言

熱門文章