如何使用此示例使用javascript将代码添加到我的表单标记中?

时间:2016-02-25 21:49:54

标签: javascript jquery wordpress

我正在使用重力形式wordpress插件,我想在我的表格标签上添加oninput ... 我按照此页面上的说明操作: https://www.gravityhelp.com/documentation/article/gform_form_tag/

但是,他们提供的示例是替换表单标记中的内容,而不是向表单标记添加内容....如何编辑以下代码以将oninput事件添加到标记而不是替换内部的内容标签?我不知道该用什么而不是pregreplace ......

add_filter( 'gform_form_tag', 'form_tag', 10, 2 );
function form_tag( $form_tag, $form ) {
    if ( $form['id'] != 3 ) {
        //not the form whose tag you want to change, return the unchanged tag
        return $form_tag;
    }
    $form_tag = preg_replace( "|action='(.*?)'|", "action='custom_handler.php'", $form_tag );
    return $form_tag;
}

2 个答案:

答案 0 :(得分:1)

嗯,我们这里有XY Problem的经典案例。您正在询问如何更改标记以包含oninput属性,但实际上您正在尝试完成其他操作。

所以,首先我会直接回答你的问题:

add_filter( 'gform_form_tag', 'form_tag', 10, 2 );
function form_tag( $form_tag, $form ) {
    if ( $form['id'] != 3 ) {
        //not the form whose tag you want to change, return the unchanged tag
        return $form_tag;
    }
    // We know the form has the 'form ' in it, so replace that with 'form' plus the oninput you want
    $form_tag = str_ireplace( "<form ", "<form oninput='myFunction() ", $form_tag );
    return $form_tag;
}

但实际上,可能有更好/更简单的方式。

写一些javascript - 因为你明确地要使用 javascript - 它与表单连接:

// Since WordPress loads jQuery in no-conflict mode, this is the preferred "document ready"
jQuery(function($) {
    // "gform_3" represents the form you want to target.
    $('#gform_3 input, #gform_3 textarea').on('change', function() {
        // Do your "oninput" work here
    }
});

只需更改ID即可与您要定位的表单的ID相匹配 - 如果您的表单为ID 23,则将其设为#gform_23,例如。

答案 1 :(得分:0)

我同意Cale更简单的回答;但是,在某些情况下,您仍然可能希望将事件属性(任何事件属性)放在&lt; form&gt;上。本身。这是一个非常简单的插件。

http://gravitywiz.com/gravity-forms-tag-editor/

使用示例:

new GW_Tag_Editor( array(
    'tag'          => 'form',
    'form_id'      => 123,
    'oninput'      => 'myFunction()'
) );