How to add errormessages instead of alert boxes in pop up using javascript

喜夏-厌秋 提交于 2019-12-06 07:21:53

Instead of showing alert dialog, you can show the message next to the element using simple and pure JavaScript:

function AddErrorLabel(element, msg) {
    var oLabel = document.createElement("span");
    oLabel.className = "error_msg";
    oLabel.innerHTML = msg;
    var parent = element.parentNode;
    if (element.nextSibling) {
        if (element.nextSibling.className !== "error_msg") {
            parent.insertBefore(oLabel, element.nextSibling);
        }
    }
    else {
        parent.appendChild(oLabel);
    }
}

Usage:

if (! (startdate.value.match(validformat)) && (enddate.value.match(validforamt)) )
{
    AddErrorLabel(startdate, "please enter valid date format");
}

Live test case. (Leave the textbox empty and click submit)

Libraries like jQuery have such features and much better but for simple needs, this should be just enough and it's using basic JavaScript thus cross browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!