开发者

JQuery - error with element non-focusable / how to force blur?

开发者 https://www.devze.com 2023-04-10 02:20 出处:网络
I have an html form which uses jquery focus and blur in order to clear and restore some preset field text. However, the form is in a modal dialog which can be hidden and shown using jquery hide() and

I have an html form which uses jquery focus and blur in order to clear and restore some preset field text. However, the form is in a modal dialog which can be hidden and shown using jquery hide() and show(). However, when the form is hidden, it is throwing a javascript error:

an invalid form control with name = 'email' is not focusable

I'm assuming this is because the form is hidden and can't be accessed. Is there a way to force a blur event? Or some way to resolve this error? Here's my code:

$j(开发者_运维百科'.dField').focus(function(){
    clearInput($j(this)[0]); //The [0] seems to be necessary to retrieve the element at the DOM object level
});
$j('.dField').blur(function(){
    restoreInput($j(this)[0]);
});

function clearInput(textField) {
    if (textField.value == textField.defaultValue) {
        textField.value = "";
     }
}

//Restores the default value
function restoreInput(textField){
    if (textField.value == ""){
        textField.value = textField.defaultValue;
    }
}

$j('#dFormBack').click(function(){
        $j('#dContentContainer').show();
        $j('#vehicle_form').hide();
    });


You can activate the function inside the blur event listener, instead of trying to initiate a blur event.

restoreInput($j(".dfield")[0]);

A side note, your first lines can be written more efficiently:

$j('.dField').focus(function(){
    clearInput(this);
}).blur(function(){
    restoreInput(this);
});

this in the event handler refers to the DOM element to which the event listener is attached. It's unnecessary to wrap this inside a JQuery wrapper and get the DOM element again using [0].


As stated here:

Triggering the focus on hidden elements causes an error in Internet Explorer. Take care to only call .focus() without parameters on elements that are visible.

So you should just check if the element is hidden before calling focus()


You are correct. When something is not visible, it cannot be focus()'ed or blur()'ed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号