3

I'm aware by going over the jQuery traversal documentation that there isn't a jQuery function that will do what I'm looking for so I'm asking what combination (if there is one) will do the trick.

If we have 1 <span> for every <textarea> on a page, and without having to get creative by adding id's or classes or data-attributes etc. would like to get the closest previous <span> to the <textarea> that is the target of the current keydown event.

What combination of jQuery traversal functions can we use to solve this problem? I've researched and tried everything I know to.

Check out this Fiddle to better visualize this problem.

id.ot
  • 3,071
  • 1
  • 32
  • 47

2 Answers2

4

there isn't a jQuery function that will do what I'm looking for

Actually, all you want is prev.

Use prev('span') to get the previous element matching the given selector.

$('div').on('keydown', 'textarea', function () {

        $(this).prev('span').text($(this).val())

})

See http://jsfiddle.net/aQ83s/2/

Note that, in the keydown event, the value of the textarea hasn't changed yet.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • this answer is wrong. if you add the `
    ` tag which the answerer removed, it no longer works, which according to the op was the original point. see here: http://jsfiddle.net/r3wt/aQ83s/16/
    – r3wt Jul 05 '14 at 01:04
  • @r3wt That's not the question being asked. This answer didn't "remove" anything, it's based on the fiddle provided: http://jsfiddle.net/id_0t/aQ83s/1/ – user229044 Jul 05 '14 at 22:47
  • @meagar it was the original question. – r3wt Jul 05 '14 at 22:48
0

An alternative, using custom data attributes and targets:

http://jsfiddle.net/r3wt/aQ83s/15/

Jquery

$('div').on('keyup', 'textarea', function() {
    var target = $("span[extra-data='"+$(this).attr('target')+"']");
    target.text($(this).val());
});

html

<div>
    <span extra-data="1">1</span>
    <br />
    <textarea target="1"></textarea>

    <span extra-data="2">2</span>
    <textarea target="2"></textarea>

    <span extra-data="3">3</span>
    <textarea target="3"></textarea>
</div>
r3wt
  • 4,642
  • 2
  • 33
  • 55
  • 1
    Thank you for your input on this @r3wt. The reason my question states that it's important not to use `id` or `class` or `data-` attributes is to confirm through the community that there isn't a function in jQuery that I've overlooked or am misusing (which is can be easy to do when chaining functions) or to hopefully alleviate using that extra functionality when generating dynamic blocks of HTML. Again, thank you for your input. – id.ot Jul 01 '14 at 02:44