0

Got a question for you javascript gurus out there. I'm creating a sidebar tool that is comprised of a few different text input fields. The purpose of this tool is to edit copy on a template. I've tried to pass the data entered into the field onchange, but I'm running into problems dumping the data into my js object. This is somewhat what I have in mind:

$('myInputField').(function(){
      $(this).onChange(){
          // write to variable X
}
});

Essentially I want to have what I'm typing in the input be mimicked live and then I can parse the changes to my database.

Scott Sword
  • 4,648
  • 6
  • 32
  • 37

4 Answers4

1
$('#myInputField').(function(){
      $(this).onkeyup(){
          x = this.value;
      }
});

or more succinctly:

$('#myInputField').onkeyup(){
    x = this.value;
});
Alex
  • 34,899
  • 5
  • 77
  • 90
1

You're just looking for the value that's in myInputField within that event handler? Something like this?:

$('myInputField').(function(){
  $(this).onChange(){
      x = $(this).val();
  }
});

I don't remember off the top of my head if this is already a jQuery object. If it is, then this should work and perhaps skip a little bit of overhead:

x = this.val();

Additionally, you can explicitly reference the field with a normal jQuery selector if this is ever overridden with a different context, or if you want to reference other fields as well, etc.:

x = $('myInputField').val();
David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    `this` is not a jQuery object, which is why people use `$(this)` :). But you can use `var x = this.value`. Don't forget the `var` keyword otherwise your variable will be global. – Florian Margaine Apr 09 '12 at 17:52
  • @FlorianMargaine: I guess I was assuming that `x` was defined elsewhere based on the question. Good info to add, though! – David Apr 09 '12 at 17:58
1

The problem is, on IE, the onchange event doesn't work on INPUT elements. Thus, you have to use the onkeypress or the onblur event depending on what you want to do.

JS way:

document.getElementById('myInputField').onblur = function() {
    var x = this.value
}

jQuery way:

$('#myInputField').blur(function() {
    var x = this.value
})
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
0

Wouldn't a simply keyup event on the input fields be sufficient?

jQuery:

$('textarea').keyup(function() {
    $('#foo').html($(this).val());
});​

HTML:

<textarea></textarea>
<div id="foo"></div>

jsFiddle example.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Perfect, everyone provided great examples, but I really like the usage of .html and .val in lieu of creating js variables. – Scott Sword Apr 09 '12 at 18:01