开发者

HTML Javascript, .click()->.submit() and .submit() returning different results

I have a form in which a button is submitting using the onClick event.

<input type="button" name="couponButton" id="orderNow" value="Apply" onKeyUp="javascript:return false;" onClick="javascript:document.cartFrm.submit();" />"

Also, I have an input that triggers couponButton when the enter key is pressed while the input is in focus.

<INPUT type=text id=coupon name=coupon size=6 value="" onKeyUp="javascript:(ev开发者_运维技巧ent.keyCode == 13)?document.couponButton.click():''}">

While they both trigger the same event (.submit()) the result is different. When you click the button the form's actual submit input is not included in $_POST. While when you press the enter key to trigger the button the form's acutal submit input is inlcuded in $_POST.


That's because you have error in the onkeyup and the default behavior of the Enter key is triggered: submitting the form using the first submit button, same as if you clicked it.

Correct code might be:

<input type="text" id="coupon" name="coupon" size="6" value="" onKeyUp="return AutoClick(event, 'orderNow');" />

Where the function is:

function AutoClick(event, id) {
   event = event || window.event;
   var keyCode = event.keyCode || event.which;
   if (keyCode == 13) {
      var button = document.getElementById(id);
      if (button)
         button.click();
      return false;
   }
   return true;
}

Note that I'm using the id of the button, not its name.


I just messed around with this, and the following seems to work I think.

<form action='#' name='cartFrm' method="get">

    <input type='hidden' name='test' value='testing' />

    <input type="button" name="couponButton" id="orderNow" value="Apply" onKeyUp="javascript:return false;" onClick="javascript:document.cartFrm.submit();" />

    <input type=text id=coupon name=coupon size=6 value="" onKeyUp="javascript:if(event.keyCode == 13){document.cartFrm.couponButton.click();}else{return false;}" />


</form>

I changed the onKeyUp on coupon to do

javascript:if(event.keyCode == 13){document.cartFrm.couponButton.click();}else{return false;}

Rather than

javascript:(event.keyCode == 13)?document.couponButton.click():''}

...as per your original, although I think the bit that does document.cartFrm.couponButton.click(); instead of document.couponButton.click() is probably the most pertinent change i made.

Oh, and I did this with html5 doctype just in case there's any quirks skulduggery going on with what I provided here.

Good luck anyway!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜