はじめに
日付ピッカー・フィールドの年齢をフォームに表示したいですか?この簡潔なガイドでは、日付ピッカーフィールドを通して生年月日を収集するフォームの作成方法を説明します。さらに、JavaScript を活用してフォームの別のセクションで年齢を簡単に計算して表示する方法も紹介します。それでは、順を追って説明していきましょう!
フォームの作成
新しいフォームを作り、フィールドを追加することから始めましょう。少なくとも1つのDateフィールドを含めるようにしてください。
フォームの作成にヘルプが必要な場合は、こちらのドキュメントをご覧ください。
HTMLフィールドの追加
最終的なゴールは、誕生日が選択された時点で年齢を提示することなので、そのために HTML フィールドを作る。このフィールド内に、空のHTMLスパンを埋め込みます。このスパンには "age "というクラスが割り当てられます。この空のスパンはプレースホルダーとして機能し、日付ピッカー・フィールドがユーザーの選択を捕捉すると同時に、年齢を動的に表示します。
<span class="age"></span>
スニペットの追加
さて、いよいよこれらをまとめるスニペットを追加します。あなたのサイトにスニペットを追加する方法と場所についてヘルプが必要な場合は、こちらの役立つガイドをご覧ください。
/** * Calculate age based on date of birth date picker field * * @link https://wpforms.com/developers/how-to-display-the-age-from-a-date-picker-field/ */ function wpf_dev_check_age() { ?> <script> jQuery(function($) { // Update the 3535_9 to match the form and field ID // of your form and date picker field window.wpforms_3535_9 = window.wpforms_3535_9 || {}; window.wpforms_3535_9.datepicker = { mode: "single", onClose: function(selectedDates, dateStr, instance) { // Set the today date as the current date var today = new Date(); // Set the DOB as the selected date of birth from // the date picker field var DOB = selectedDates[0]; // Get the age by subtracting today's date from // the selected date of birth var age = today.getTime() - DOB.getTime(); // Add a string to the message that will appear // showing the age var message = 'Your age is '; // Calculate the date from the age into "years old" age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25)); // Assign the message and age into a variable var totalMessage = message.concat(age); // Display the message into the empty span of "age" // inside the HTML field jQuery('.age').text(totalMessage); } } }); </script> <?php } add_action( 'wpforms_wp_footer', 'wpf_dev_check_age', 10 );
このスニペットには、各ステップを説明する多くのコメントが含まれています。しかし、フォームID3535と 日付フィールドID9を探し、その日付が選択され、日付選択ポップアップが閉じると、入力された日付から現在の日付を差し引いたものを自動的に計算し、この差を年数に変換して空のHTMLスパンに表示します。
このドキュメントでは、フォームIDを3535、日付フィールドのフィールドIDを9とします。IDを見つけるのに助けが必要な場合は、こちらのドキュメントをご覧ください。
日付ピッカー・フィールドから年齢を計算するのに必要なのはこれだけです。日付ピッカー・ポップアップの位置も変更したいですか?日付ピッカー・ポップアップの位置を変更する方法」のチュートリアルをご覧ください。
参考
アクション・リファレンス:wpforms_wp_footer