Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to immediate selector object with jQuery?

I'm trying to learn some jQuery, and I setup a test page with the following code:

<a id='encode' href='javascript: void(0)'>encode</a> |  
<a id='decode' href='javascript: void(0)'>decode</a> | 
<br/>
<textarea id='randomString' cols='100' rows='5'></textarea>

<script type='text/javascript'>
$(document.ready(function () {
  $('#encode').click(function() {
    $('#randomString').val(escape($('#randomString').val()));
  });
  $('#decode').click(function() {
    $('#randomString').val(unescape($('#randomString').val()));
  });     
});
</script>

The idea is I can put something in the textarea and click either "encode" or "decode", and it will either escape or unescape what I put into the textarea.

This code works just fine, but my question has to do with how I am changing the value of the textarea. In my code, I am selecting the textarea value twice: once to (un)escape it, and once again to change the value. IMO this seems clunky and maybe unnecessary. I thought maybe I could do something like this instead:

$('#randomString').val(escape(this));

But this seems to refer to the object of the link I clicked, not the #randomString selector, so is there some other magic word I can use to reference that $('#randomString')?

like image 785
slinkhi Avatar asked Dec 12 '11 18:12

slinkhi


1 Answers

$('#randomString').val(escape(this));

This does not get the object you want. It is effectively the equivalent of doing this:

var foo = escape(this);
$('#randomString').val(foo);

this only means something different when you start a new scope with a function definition.

jQuery does offer this kind of functionality with a callback option:

$('#randomString').val(function (idx, oldVal) {
    return escape(oldVal);
});

The second parameter is the current value of the element; the return value sets a new value for the element.

like image 129
lonesomeday Avatar answered Oct 10 '22 00:10

lonesomeday