admin管理员组

文章数量:1336142

I have a modal that I pop up with jQuery with a textfield on which I want to trigger the focus() event.
Problem is the fextfield IS allready focused.. In most browsers it is even highlighted. (I have no idea why?)

How can I de-focus or de-select the text so I can use the focus() event?

<input type="text" class="shortcut" id="input-shortcut" value="<?= $shortcut_url; ?>" />

$(".shortcut").focus(function() { 
    $(this).addClass("focus");
    $(this).select();
}).blur(function() { 
    $(this).removeClass("focus"); 
});

I have a modal that I pop up with jQuery with a textfield on which I want to trigger the focus() event.
Problem is the fextfield IS allready focused.. In most browsers it is even highlighted. (I have no idea why?)

How can I de-focus or de-select the text so I can use the focus() event?

<input type="text" class="shortcut" id="input-shortcut" value="<?= $shortcut_url; ?>" />

$(".shortcut").focus(function() { 
    $(this).addClass("focus");
    $(this).select();
}).blur(function() { 
    $(this).removeClass("focus"); 
});
Share Improve this question edited Jan 6, 2011 at 21:32 TunaFFish asked Jan 6, 2011 at 21:16 TunaFFishTunaFFish 11.3k34 gold badges98 silver badges137 bronze badges 5
  • It seems to be no problem to trigger the focus event if the input element already has focus: jsfiddle/fkling/uT9d9 (at least in Chrome and Firefox). Where are you trying to trigger it? You know that $('.shortcut') won't select your input element? – Felix Kling Commented Jan 6, 2011 at 21:21
  • mmm it doesn't seem to work for .select() though? – TunaFFish Commented Jan 6, 2011 at 21:24
  • Raising select works too: jsfiddle/fkling/uT9d9/1 – Felix Kling Commented Jan 6, 2011 at 21:29
  • Ok I just want one of them "copy the link" textfields, no Flash. When they click in the field (focus) select all the text. I also have the focus class for styling the field. I just don't get why the text is selected in my modal? – TunaFFish Commented Jan 6, 2011 at 21:31
  • Just found a good solution for selecting the text, old skool JS: javascript-array./scripts/onclick_select_all_text_in_field – TunaFFish Commented Jan 6, 2011 at 21:43
Add a ment  | 

2 Answers 2

Reset to default 5

Use $("#element").blur();

jQuery documentation of blur

Use Jquery's blur() function. Which is basically like "out of focus"

本文标签: jqueryJavascript defocus textfield inputStack Overflow