Chage form action based on user input
I have this form:
<form action"url.aspx">
</form>
The user has to be able to choose pro or nonpro. If t开发者_如何学编程he user chooses pro it has to choose action="url1.aspx" If the user chooses pro it has to choose action="url2.aspx".
It would be best to always post to the same page and let that page decide which code to execute based on the choice of 'pro' or 'nonpro'. Advantage: Less error prone. I think your form should always function properly, even without javascript, although you can use JavaScript to make it more usable. By using JavaScript, you will allow the user under some circumstances to post data to the wrong page.
You can manipulate the "action" attribute of a form via JavaScript/jQuery
$( your-form ).attr( 'action', 'url1.aspx' );
$( your-form ).attr( 'action', 'url2.aspx' );
So whatever mechanism the user is using to choose "pro" or "nonpro" (you don't mention and I don't see any code), manipulate the action attribute of the form appropriately.
you can hide and show divs based on your choice, that would be simplest way to do that
I agree with charliegriefer's answer. That's is the simplest and efficient way.
I do not agree with GolezTrol's point that "it will be always best to post to the same page and the ..." Only if you need to do some common post processing action, then may be but still you should better call a reusable function for that. As a beginner you may stick to what you feel is easy but that does not mean it is best.
Redirecting to wrong page
I don't agree again to this point "By using JavaScript, you will allow the user under some circumstances to post data to the wrong page."
If it goes to wrong page due to your logic error (in some complex cases which you did not properly think would come up) then it is your fault and you will just be hiding your mistake by ignoring javascript and there will be more delays due to multiple page redirects, unecessary page loads which could be avoided etc.
It is a very important point to follow proper validation of all parameters at all entry points (variable type checking, mandatory parameters checking). That will guarantee security in case of posting to wrong pages, if it happens at all.
In the absence of javascript
All modern browsers support javascript. If user has turned off, a message can be displayed but that would happen in fewer cases. Users can be shown a message "For better experience/ease of usage turn on javascript".
The best approach here would be keeping a provision for the form to work normally using server side logic (submitting to the same url and then redirecting). So normally and in most cases, users will get better UI.
It is a very common practise among beginners to ignore such things or follow in some places and not in others. Proper and maximum possible code reuse is the key to majority of problems. Yes it takes time to prepare the most reusable code but time spent here always pays off later.
精彩评论