OIM3690 - Web Technologies

contain

JavaScript - Form Processing

Accessing input

  • Use querySelector to access form elements
    • Use name attribute of inputs to access their values
    • Use id attribute to access the element directly
  • Example:
    <form id="form-feedback" action="">
      Your Name: <input type="text" name="userName" id="user-name" maxlength="30"/>
    </form>
    
    In JavaScript:
    // const myForm = document.querySelector("#form-feedback");
    // const nameInput = myForm["userName"];
    const nameInput = document.querySelector("#user-name");
    console.log(nameInput.value);
    
    // You can also modify it:
    nameInput.value = "Michael Scott";
    

Accessing textarea

  • Example:
    ...
    <label>Enter your comments below:<br />
      <textarea name="comments" id="comments" cols="30" rows="10"></textarea>
    </label>
    
    In JavaScript:
    // const myForm = document.querySelector("#form-feedback");
    // const comments = myForm["comments"];
    const comments = myForm["comments"].value; 
    

Accessing select and option

  • Example:
    ...
    Select the browsers you like:
    <select name="browser" id="browser">
      <option value="Chrome">Chrome</option>
      <option value="Safari">Safari</option>
    </select>
    
    in JavaScript:
    // const selectedBrowser = myForm["browser"].value; 
    // const selectedBrowser = document.querySelector("select[name='browser']").value;
    const selectedBrowser = document.querySelector("#browser").value;
    

Exercise: ex16-calculator.html

  • Create a form to implement a simple calculator with the following operations:
    • Addition +, subtraction -, multiplication ×, and division ÷
  • You can design the calculator in any style you like, but it must include:
    • Two input fields for the operands (numbers)
    • A select dropdown or buttons to choose the operation
    • A result display and any other UI elements you find helpful
  • JavaScript Requirements
    • Use JavaScript functions to handle events (e.g., button clicks)
    • Use parseFloat() to convert inputs from strings to numbers
    • No need to validate inputs

Exercise: ex16-calculator-AI.html (cont.)

After building your own version:

  • Ask AI to review your calculator code and suggest improvements.
  • Then ask AI to generate a new version of the calculator using only vanilla JavaScript (no external libraries).
  • Compare your version with the AI's version:
    • What are the differences in structure, readability, or efficiency?
    • What would you keep or change in your own version after the comparison?

Questions?