2

I've been trying to get the value from a text input, but for some reason, it's not working.

Essentially, I have a text input. The user types inside of the input, and I'd expect the .value property to change (which chrome says it does), but when I click to save it, and read my JSON output, it returns as a blank string.

Here's the HTML for this bit:

<input id="eventName" name="efrm" type="text" value="" />
<button type="button" id="okEvent">Save Event</button>

Here's the JS that you'll need to see:

document.querySelector("#okEvent").addEventListener("mousedown", applyEvent(event), false);

function applyEvent(event) {
    var eventName = document.querySelector("#eventName").value;

    event.data = {
        name: eventName,
        img: null,
        type: 1,
        fov: 0,
        orientation: 1,
        trigger: 1
    };
}

The JSON output says that the name property of the event.data object is an empty string, though. I'm really not understanding what's going on here.

Stefan
  • 5,203
  • 8
  • 27
  • 51
ndugger
  • 7,373
  • 5
  • 31
  • 42
  • At least in ie, event is a global variable. By using event in your applyEvent function, you are masking over the global variable. Probably should change the variable name. – Bindrid Dec 14 '15 at 16:50
  • See [How to pass arguments to addEventListener listener function?](https://stackoverflow.com/q/256754/4642212). – Sebastian Simon Aug 30 '20 at 14:44

1 Answers1

2

You are calling applyEvent immediately and pass the return value to addEventListener (which is undefined). Since the input element doesn't have a value yet at that moment, .value will return an empty string.

Pass a function instead:

....addEventListener("mousedown", function() {
    applyEvent(event);
}, false);

(I don't know where event is coming from in your code, but I assume it is a custom object, not the actual event object).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Yes, it worked! Thank you very much. Stack overflow said I have to wait 7 minutes to accept the answer, but I will when the time comes. Thanks! – ndugger Jan 30 '14 at 21:00