How to traverse through other parents with jQuery? -
i have many forms on website , i'd use jquery transverse when press pgup / pgdn go next <textarea>
field. got working when <textarea>
's siblings, if they're in separate form (with different parents) can't figure out.
the html like:
<form action="#" method="post"> <textarea id="numone" name="numone" class="num" ></textarea> </form> <form action="#" method="post"> <textarea id="numtwo" name="numtwo" class="num" ></textarea> </form> <form action="#" method="post"> <textarea id="numthree" name="numthree" class="num" ></textarea> </form>
this worked when siblings:
$('.num').keydown(function (e) { if (e.which == 34) { $(this).next().focus(); e.preventdefault(); return false; } if (e.which == 33) { $(this).prev().focus(); e.preventdefault(); return false; } });
$('.num').keydown(function (e) { if (e.which == 34) { $(this).closest('form').next('form').find('.num').focus(); return false; } if (e.which == 33) { $(this).closest('form').prev('form').find('.num').focus(); return false; } });
as can see used .closest('form')
allow 1 day use textarea
inside fieldset
without taking care of jquery, cause it'll traverse dom right way.
another nice way: demo
$('.num').keydown(function (e) { var k = e.which; if ( k==34 || k==33 ){ $(this).closest('form')[k==34?'next':'prev']('form').find('.num').focus(); e.preventdefault(); } });
another nice demo
var $num = $('.num').keydown(function(e) { var k=e.which, c=$num.index(this); if(k==34||k==33) $num[k==34?++c:--c].focus(); });
let's go through last one:
var $num = $('.num') // create jquery array collection // of .num in dom. .keydown(function(e) { // on keydown pass (e)vent. var k=e.which, // var k "which keycode" c=$num.index(this); // var c index of clicked // element taken collection. if(k==34||k==33) // if pgup/pgdn $num[k==34?++c:--c] // increment or decrement c , el. // out of array ( e.g: $num[1] ) .focus(); // , set focus it. });
Comments
Post a Comment