开发者

Javascript function for checking form values on submit

Modified question so you can stop taking the michael!

Ok i want use jquery to validate it.

The form values are from hidden inputs. So if any hidden inputs == 0, i want to alert the开发者_Python百科 user to complete the form. If all == 1 i want the form to be submitted.

I want to submit via input button type with an onclick event.

<script>
jquery function
if all hidden == 0
alert
else 
location.href='submit2pd.php
</script>
<input onclick="(the jquery function)" type="button" value="Submit" />


Removing the entire else block will probably do the trick (if your <form> has a target). As for the rest of your code, well... Never mind.


Do yourself a favor and learn some jQuery (or other js library of your choice). You can replace your function to something like this:

$('#formId').submit(function(e){
    $(this).find('checkbox').each(function(){
        if($(this).val() == '0') {
            alert('Please complete the form before submitting.');
            e.preventDefault();   
        }  
    });
});


An example of what you want to do that works can be found here: http://www.shiningstar.net/articles/articles/javascript/checkboxes.asp

I'll give you a specific answer and a more conceptual answer about why what you have doesn't work.

Specifically, you want to replace all those items with checklist.whatever.checked==false

More conceptually, that long chain of or statements is not good software engineering and you will make yourself miserable maintaining that. You need to use a for loop to make it work because it is just too easy to introduce typos into that code.

I agree with Andre that you should use jQuery, because it's API for interacting with the HTML elements is easier than the native JavaScript API. Second, get firebug and learn to use console.log. Third go to the JavascriptLint site and learn how to use that tool.


In your function checklist is the input element so checklist.taccept would not find an element. You need to pass through your form as checklist in order for this to work.

I think the jQuery solution by Andre is a lot more elegant and just as easy to implement. Instead of the submit handler, just add that as a click even to your button and change $(this) to $("#formid")


Try sticking in an alert('in function...bla'); or two in that jscript block, then you can tell that its being called successfully, then you can deal with what you are trying to do in the block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜