JavaScript:.innerhtml错误消息表单验证

时间:2012-12-06 16:09:24

标签: javascript

我正在尝试使用.innerhtml在按钮上方输入错误消息。 我想我已经接近这个了,但是我被困住了。我认为这是一个非常简单的语义错误,因为我是JS的新手。

这是我的jsfiddle:http://jsfiddle.net/ajX2U/

var sel  = document.getElementById("stateType");

    switch(sel.value) {
        case "VA":
            location.href = "http://www.test1.com";
            break;
        case "MD":
            location.href = "http://www.test2.com";
            break;
        case "IL":
            location.href = "http://www.test3.com";
            break;
        case "TX":
            location.href = "http://www.test4.com";
            break;
        case "other":
            location.href = "http://www.test5.com";
            break;
        // oh dear we have selected a wrong option
        default:
            document.getElementById('error').innerHTML = 'Fred Flinstone';
    }
}

2 个答案:

答案 0 :(得分:0)

在你的小提琴中,你忘了包括功能头。添加之后,它对我有用。

updated fiddle

function validate(){
    var sel  = document.getElementById("stateType");

    switch(sel.value) {
        case "VA":
            location.href = "http://www.test1.com";
            break;
        case "MD":
            location.href = "http://www.test2.com";
            break;
        case "IL":
            location.href = "http://www.test3.com";
            break;
        case "TX":
            location.href = "http://www.test4.com";
            break;
        case "other":
            location.href = "http://www.test5.com";
            break;
        // oh dear we have selected a wrong option
        default:
            document.getElementById('error').innerHTML = 'Fred Flinstone';
    }
}

答案 1 :(得分:0)

从小提琴中,这就是出错的地方。

(使用Chrome并打开控制台,您会看到它)

<script type='text/javascript'>//<![CDATA[ 
window.addEvent('load', function() {
var sel  = document.getElementById("stateType");

switch(sel.value) {
    case "VA":
        location.href = "http://www.test1.com";
        break;
    case "MD":
        location.href = "http://www.test2.com";
        break;
    case "IL":
        location.href = "http://www.test3.com";
        break;
    case "TX":
        location.href = "http://www.test4.com";
        break;
    case "other":
        location.href = "http://www.test5.com";
        break;
    // oh dear we have selected a wrong option
    default:
        document.getElementById('error').innerHTML = 'Fred Flinstone';
}
}
var sel  = document.getElementById("stateType");
});//]]>

var sel位于错误的位置并打破它(无论如何都是第二个变种)。