【问题标题】:How to define a jQuery-function which is called with an html button attribute onClick?如何定义一个使用 html 按钮属性 onClick 调用的 jQuery 函数?
【发布时间】:2018-02-14 18:18:38
【问题描述】:

我的问题是。我想在发送之前更改所需的表单字段。当从没有 php number_format 的后端加载时,它们将 periots 显示为十进制分隔符,这是我不想要的,但该字段需要这个。 magento 类验证字段,我不想自己改回数字或让客户自己做。在(模糊)或单击时进行更改(更改)是没有问题的。

但我希望在提交表单时更改该字段。这是html:

<form>
  <input id="price" value="
     <?php if (isset ( $productPrice )) {
      echo number_format($productPrice, '2', ',', '.');
      } ?>" class="validate-zero-or-greater input-text validation-passed" 
     type="text"> 
</form>

<button class="button" id="actionbutton" 
 onclick="function(),checkTextarea()" type="submit" title="<?php echo $this-
 >__('Save Product') ?>">
</button>

和第一行有我的问题的 jQuery 脚本:

 $("#price").(function(){
  event.preventDefault();
if (jQuery('#price').val().includes(','))  {

    var varwithComma = jQuery('#price').val();
    varwithoutComma = varwithComma.replace(",",".");

    jQuery('#price').val(varwithoutComma);
} else {
    console.log('No Comma');
};

我猜,由于 on change 事件,第一行的代码运行良好。

 jQuery('form').on('change', '#price', function(event){

【问题讨论】:

    标签: jquery onclick magento-1.9


    【解决方案1】:

    //bind on the submit of the form
    $('#whateverMyFormSelectorIs').on('submit', function(e){
      //cancel the form submit so we can manipulate the inputs
      e.preventDefault();
      
      var $price = $('#price');
      
      //replace any comma in the price with a decimal
      //will do nothing if there are no commas
      $price.val($price.val().replace(',', '.'));
      
      //make other changes to the form
      
      //finally, submit the raw dom element
      //doing this bypasses the jQuery submit handler which should not
      //run again
      this.submit();
    });

    【讨论】:

    • 感谢您的回答!事实上,我不需要 if 语句。我还尝试了 jQuery on('submit'。不知何故,这对我不起作用。但我也不知道,你的第二行中的 Formselector 是什么。你的意思是我要更改的元素的 Id (#price)?表单是否应该获得一个 ID,然后我选择它还是 $('form') 是必需的条目?提到的选择器都没有对表单进行更改。我发现,Magento 也是接受或转换带有逗号作为小数分隔符的数字。所以对我来说这不再是问题了。仍然想知道,我怎样才能做到这一点。
    • '#whateverMyFormSelectorIs' 是您要用于定位将要提交的表单的任何选择器,无论是表单 ID,还是仅在该表单上的类,或者它是唯一的表单页面只是 tagName。
    • 啊,好吧,我刚刚使用了jQuery('form') 作为选择器。所以我可以排除这个错误。你的最后一行也没有让它工作。还是谢谢你。至少我知道 Magento 和整个 php-template 结构是一个更复杂的问题。也许提交事件发生了一些事情,导致代码无法正常运行。
    猜你喜欢
    • 2016-02-25
    • 2019-11-06
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多