0

I'm not very good with forms and am having a great deal of difficulty with what should be a simple problem.

I have a form which contains the following:

        <select id="values" name="Choice">
            <option value="choose">Please Choose...</option>
            <option value="01">Value 1</option>
            <option value="02">Value 2</option>
        </select>

All I want to do is stop the form from submitting if neither value-01 or value-02 are selected but the disabled option doesn't work.

How can I achieve this?

UPDATE:

I'm already using javascript to check the form, but this does not seem to work.

function submitForm() {
        if (formObj.Choice.value == '') {
            alert("Please select a value");
            return false;
        }
        return true;
    }

UPDATE 2: In answer to @h4b0 question:

<input type="submit" value="Search" class="screen-reader-text button cf" name="SubmitButton" onclick="return submitForm();">
4

2 回答 2

1

In the form tag, use something like

<form name='myForm' method='post' id='myForm' onsubmit='return submitForm()'>
....
</form>

When the form is submitted, it will run that JavaScript function, and then return the value of the result to the form. If it's true, it posts the data. If the results are false, it will cancel the submit.

You're really close with what you have in your submit button, but change the onclick to onsubmit, and move the event binding to the form tag.

[EDIT]

Your form will never return false with how you are checking for values in the select. Since none of the options have value='', your if statement will never evaluate to true and return false to the function caller.

于 2012-04-23T12:34:08.307 回答
0

Try this, While Submitting the form call a method to check your condition by selectedIndex and return false to cancel the submit.

<script>
function validateMe(){
    var x=document.getElementById("Choice").selectedIndex;
    var y=document.getElementById("Choice").options;
    if(y[x] != "01"|| y[x] != "02"){
       return false;
    }
    return true;
}
</script>
<form name="YourForm" id ="YourForm" onSubmit="return validateMe()">
<select id="values" name="Choice" id="Choice">
        <option value="choose">Please Choose...</option>
        <option value="01">Value 1</option>
        <option value="02">Value 2</option>
    </select>

<input type="submit" value="Search" class="screen-reader-text button cf" name="SubmitButton">

</form>
于 2012-04-23T12:35:44.390 回答