开发者

Basic Javascript: onclick event not working

Given this simple javascript function:

function update_cart() {
alert("--update--");
document.form1.command.value="update";
document.form1.submit();
}

and this button at the bottom of my form:

<input type="submit" value="Update" onclick="update_cart()" />

The data in the form is 'submitted' to the new URL. but the update_cart function is never called. I know because I never get an alert box, and the URL reads...?c=Albania&m=....

Also, the form element

<input type="hidden" name="command"/>

does not get posted to the URL, either. URL reads ?command=&c=Albania...

I have tried the following: changed onclick to onsubmit, checking $_REQUEST variables, cutting and pasting the code from known working pages.

I'm at my wit's end, and would be grateful for any help!

Oh, yes: same behaviour in firefox 6, Opera 11.5, & IE7. I'm running WinXP SP3.

Than开发者_StackOverflow中文版king you, Sadhu!


Once try

<input type="button" value="Update" onclick="update_cart()" />

instead

<input type="submit" value="Update" onclick="update_cart()" />

if you want that for 'submit' type then go with 'Allen Liu' answer


enter code hereif you wane to change sth when onsubmit, you need to do these changes before form's submitting. so you need to add these opeartion to the "onsubmit" event of the form, rather than the "onclick" event of the submit button.

like this:

<form name="toSubmit" onsubmit="update_cart();"><input type="submit" name="btn" value="hello"/></form>


If you want the script to run on submit of form, use:

<input type="submit" value="Update" onsubmit="update_cart()" />

The onsubmit event is usually used to run some validation script. If the validation returns true, the form will submit. If it returns false, the form does not submit. In your case, the script is coded to submit the form so no return boolean value is necessary.

Otherwise, I would not give your button the submit type if it really doesn't submit the form. You can simply use button tags with the onclick and that should work:

<button onclick="update_cart()">Update</button>


First of all there is no need to change your html; see my demo.
On every click on a submit button, first the click-handler (if exists) will be started, then the submit-handler (if exists) (which should be in the form tag) and then the action of the form will be executed. This procedure will be only stoped, if a handler returns false.
But why will your javascript function update_cart not be called?
I think it could not be found, but I don't why. Can you bind the function to the window dom element only for testing (like in my demo)?

P.s.: you don't need to submit the form in your click-handler (if you don't return false). You can remove the line: document.form1.submit();.

P.s.: it will be better not to use a click-handler on the submit-button, instead use a submit-handler in the form tag (see my demo2).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜