Access the immediate selector object using jQuery?

I am trying to learn some jQuery and I am setting up 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 that I can put something in the text box and click either “encode” or “decode”, and it will either run away or undo what I placed in the text box.

This code works fine, but my question is related to how I change the value of the text area. In my code, I select the textarea value twice: once (un) escapes from it, and once again to change the value. IMO this seems awkward and possibly unnecessary. I was thinking, maybe I could do something like this:

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

this, , , , #randomString, , $('#randomString')?

+5
4

, , - . $('#randomString'), . val, JavaScript, jQuery "magic".

, jQuery #randomString, :

$(document.ready(function () {
    var $rndStr = $('#randomString');

    $('#encode').click(function() {
        $rndStr.val(escape($rndStr.val()));
    });

    $('#decode').click(function() {
        $('#rndStr').val(unescape($rndStr.val()));
    });     
});
+1
$('#randomString').val(escape(this));

. :

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

this - .

jQuery ​​ :

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

- ; .

+4

You can try this

$(document.ready(function () {

  $('#encode').click(function() {
    var $randomString =  $('#randomString');
    $randomString.val(escape($randomString.val()));
  });
  $('#decode').click(function() {
    var $randomString =  $('#randomString');
    $randomString.val(unescape($randomString.val()));
  });     
});
+3
source

You can make this somewhat generic:

$.fn.applyVal = function(func) {
    return this.each(function() {
        $(this).val( func( $(this).val() ) );
    });
};

Then the following call is enough:

$('#randomString').applyVal(escape);
+1
source

All Articles