2

I have a form with several different types of input (checkboxes, text,number etc)I want to be able to find the ID of the current element of the form the user is clicking on/typing on and the value they are inputting.

I currently am using surprisingly undefined for the value. I really have no idea where to start with this(I don't wish to use jQuery)

the HTML

<form id = "myForm" >           
        <input type="text" id="name"  name="name"  placeholder ="Name" />       

        <input type="email" id="mail"   name="email" placeholder ="Email" />

        <input type="number" id="phoneNumber" name ="phone" placeholder = "Phone Number" />

        <label for ="emailFormat">Email Signup Format:</label>
        <select name="newsletter" id = "plain">
            <option value = "Plain">Plain Text</option>
            <option value = "HTML">HTML</option>
        </select>

        <label for="pets">Cars owned:</label>
        <input type = "checkbox" id="mini" class = "ck" name ="mini">I have a mini.
        <input type = "checkbox" id="motorbike" class = "ck" name ="motorbike">I have a motorbike.
        <input type = "checkbox" id="thundercar" class = "ck" name ="thundercar">I have a thundercar.
        <input type = "checkbox" id="brum" class = "ck" name ="brum">I have a brum.
        <input type = "checkbox" id="roadrunner" class = "ck" name ="roadrunner">I have a roadrunner.

       <button type="submit" id ="button">SUBMIT</button>
</form>

the JavaScript

var form = document.getElementById("myForm");

form.addEventListener("keyup", store);
form.addEventListener("click",store);

function store() {
  console.log(this.id);
  console.log(this.value);
}
tharindu_DG
  • 8,900
  • 6
  • 52
  • 64
Dalek
  • 111
  • 4
  • 12
  • As you can see, you're getting `myForm` and `undefined` - this is because you're targetting the form itself with the `click` listener - `form.addEventListener("click",store);`- the `undefined` is because a form has no `keyup` - you'll have to set listeners for each form element to know where the user currently is – StudioTime Dec 24 '15 at 13:13
  • `document.activeElement` gives the DOM which has the current focus, extract its ID from it then. But it may not be as good as it sounds. One way is by adding "focus" event handler to all that you require and record the last focused field in a variable. – krozaine Dec 24 '15 at 13:14

2 Answers2

6

When binding the event to the form, and relying on bubbling of events, this will be the form inside the event handler.

To get the element the event was triggered on, you'd use event.target instead

function store(event) {
    console.log(event.target.id);
    console.log(event.target.value);
}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

cross-browser solution:

function store(e) {
    var target = (e.target)? e.target : e.srcElement;
    console.log(target.id);
    console.log(target.value);
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105