简体   繁体   中英

JavaScript: .innerhtml error message form validation

I'm trying to enter an error message above a button using .innerhtml. I think I'm close to getting this to work, but I'm stuck. I think there's a really simple semantic error, as I'm new to JS.

Here's my 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';
    }
}

In your fiddle you just forgot to include the function head. After adding that, it worked for me.

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';
    }
}

From your fiddle, this is where it goes wrong.

(Use Chrome and open console, you will see it)

<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");
});//]]>

The var sel is in the wrong place and breaks it ( the 2nd var sel anyway ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM