0

when I load page selText() run only after two click and then it works fine but if refresh page i need to click twice again

<a href="javascript: selText();" class="select">click</a>
<input type="text"  value="value" />

<a href="javascript: selText();" class="select">click</a>
<input type='text'  value='value' />

<a href="javascript: selText();" class="select">click</a>
<input type="text"  value="value" />




function selText() {
        $(".select").click(function () { $(this).nextUntil("a").select(); });
    }
Egor
  • 9
  • 6

4 Answers4

0

put your code in

$(document).ready(function() {
    $(".select").click(function (e) {
        e.preventDefault();
        $(this).nextUntil("a").select();
    });
});
Rasool Ghafari
  • 4,128
  • 7
  • 44
  • 71
0

You are registering the click handler which is calling the select method on a click handler so when the first click happens there is no handler to select the elements, but it merely registers a handler which will do the selection. When the second click happens you will have 2 handlers for the click event one selText and second the handler registered by the first one. But when you do the third click the select() code will get called twice.

So in your case the solution is to remove the inlined handler and register a click handler on a dom ready callback as shown below.

<a href="#" class="select">click</a>
<input type="text"  value="value" />

<a href="#" class="select">click</a>
<input type='text'  value='value' />

<a href="#" class="select">click</a>
<input type="text"  value="value" />

then

jQuery(function () {
    $(".select").click(function (e) {
        $(this).nextUntil("a").select();, e.preventDefault()
    });
})
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

This is because when you add

function selText() {
    $(".select").click(function () { $(this).nextUntil("a").select(); });
}

and then click on the anchor link, what happens, the first time, is the function binds a click event to the ".select" element. This is the reason why the first click doesn't do anything. But the clicks after that will work as expected. The unwanted effect of the above code is, that you are binding the click event the multiple functions which actually do the same thing (no. of functions bound being equal to the no. of times you click the anchor tag)

The answer is, that you need to place

$(".select").click(function () { $(this).nextUntil("a").select(); });

under

$(document).ready(function(){
..// your code here
});
aash
  • 1,323
  • 1
  • 14
  • 22
  • my pleasure. You can upvote the answer or mark it as answered, if your question is answered, :-) – aash Nov 01 '13 at 09:58
0

I don't Know why but in some views in my project the above code don't work and I have to do the following

$(document).ready(function () {
    $(document).on('click', '.tabl-red', function (e) {
        e.preventDefault();
        $(this).nextUntil("a").select();
    });
});

maybe it helps someone

Egor
  • 9
  • 6