簡體   English   中英

如何使用此示例使用javascript將代碼添加到表單標簽中?

[英]How do I add code to my form tag with javascript using this example?

我正在使用重力形式的wordpress插件,並且要將oninput添加到我的表單標簽中...我正在按照此頁面上的說明進行操作: https ://www.gravityhelp.com/documentation/article/gform_form_tag/

但是,他們提供的示例是替換form標記中的內容,而不是在form標記中添加內容。...應該如何編輯以下代碼以將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;
}

好吧,我們這里有XY問題的經典案例。 您在問如何更改標記以包括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

我同意Cale的簡單回答; 但是,在某些情況下,您仍然可能希望將事件屬性(任何事件屬性)放在<form>本身上。 這是一個非常簡單的插件。

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

用法示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM