Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เปลี่ยนค่า Input เมื่อ Submit Form ใน JavaScript

ใช้ document.formName.inputName.value = newValue ในฟังก์ชัน onsubmit

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form name="studentForm" onsubmit="submitForm();">
        <input type="hidden" name="txtInput" value="10000" />
        <input type="submit" value="Submit Form"/>
    </form>

    <script>
        function submitForm() {
            document.studentForm.txtInput.value = 'STUDENT-100';
        }
    </script>
</body>
</html>

วิธีรันโปรแกรม

  1. บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
  2. คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor

ผลลัพธ์

กด Submit จะเปลี่ยนค่า Hidden Input จาก 10000 เป็น STUDENT-100 แล้วส่ง Form