0

I want to be able to submit the form only if the 'my val 2' option is selected. If another option is selected and the submit button is pressed, I want it to just say they cannot submit it. Also, if they submit it, I want it to go to a submission page that says what they submitted. Here is my form:

<form action="formSub.php" method="POST" name="myform" onsubmit="return checkscript()">
            <select name="test_select">
                <option value="1">my val 1</option>
                <option value="2">my val 2</option>
                <option value="3">my val 3</option>
                <option value="4">my val 4</option>
            </select>
            <input type="submit" value="Submit" name="test_button" onClick="submitform(test_select.value)">
        </form>

Here are my javascript functions

function submitform(val) {
    var obj = val;;
    alert("Value =  " + obj);
}

function checkscript() {
    if (obj !== "2") {
        alert('This is not \'my val 2\' so you cannot submit');
        return false;
    }
    return true;
}

Also, my checkscript function doesn't work correctly. The f statement is always false.

4

1 回答 1

2

你的脚本有错误。JavaScript 在函数 checkscript() 的范围内看不到变量 obj。您宁愿尝试将该变量声明为全局变量。您有如何在此处验证表单的示例:http: //www.w3schools.com/js/js_form_validation.asp 以及:Javascript 表单验证 onsubmit as @Noob UnChained 写入您必须通过脚本从字段中获取值。你也有功能submitform(val)

正如我所见,该函数从选择面板中获取值。因此,您可以尝试使用该函数从列表中返回选定的值。

var obj;
function submitform(val) {
    obj = val;
    alert("Value =  " + obj);
}

function checkscript() {
    if (obj !== "2") {
        alert('This is not \'my val 2\' so you cannot submit');
        return false;
    }
    return true;
}

对于第一个函数submitform()集变量 obj 和第二个函数使用 set obj 来检查值。

但如果我是你,我会使用 @Noob UnChained 方法,因为它更简单,而且你可以在一个函数中验证多种形式。也尝试阅读 JavaScripts 教程以编写好的 scipts。

我希望对你有所帮助。

于 2013-04-18T06:40:15.247 回答