Reputation: 363
How do I add an auto value after a user adds text to an input in a text/email field. For example, the user enters their cell phone number and a custom @domain.com is entered after user input. Please see code below:
<div class="email">
<input class="gift_receiver_email" type="text" placeholder="<?php _e( 'Email address', WC_SC_TEXT_DOMAIN ); ?>..." name="gift_receiver_email[0][0]" value="" />
</div>
Note: I am not referring to the set value when user sees the field (example value="text displayed") and should set the function to only run when a minimum of 10 characters is entered by the user
Upvotes: 2
Views: 3992
Reputation: 5947
Here is a Simplest Example
function addDefault(tag)
{
if(tag.value.length != 10) //to check if characters length is not 10
return; //exit the function
tag.value += '_someValue';
}
<input type="text" id="myInput" onblur="addDefault(this)">
Upvotes: 2
Reputation: 843
<input id="gift_receiver_email" class="gift_receiver_email" type="text" placeholder="<?php _e( 'Email address', WC_SC_TEXT_DOMAIN ); ?>..." name="gift_receiver_email[0][0]" value="" /
var gift_receiver_email = document.getElementById("gift_receiver_email");
gift_receiver_email.addEventListener("blur", function( event ) {
var value = event.target.style.background = "";
value += '@domain.com';
gift_receiver_email.value = val(value);
}, true);
Upvotes: 1
Reputation: 74
use the onchange event. blur event is fired everytime you focus and leave the input text.
change event is fired only when its content changes. (browser do the work for you)
in either case, you have to check to not stack with '+ @domain.com' like this: [email protected]@domain.com.
this is a simple task to solve, i can leave it to you.
Upvotes: 0
Reputation: 1502
UPDATE: onChange
is more better than onBlur
and updated my answer accordingly.
Using onChange
:
function updateInput(inputElm) {
inputElm.value = inputElm.value+'@domain.com';
}
<div class="email">
<input class="gift_receiver_email" type="text" placeholder="<?php _e( 'Email address', WC_SC_TEXT_DOMAIN ); ?>..." name="gift_receiver_email[0][0]" value="" onchange="updateInput(this)"/>
</div>
Using onBlur
:
function updateInput(inputElm) {
inputElm.value = inputElm.value+'@domain.com';
}
<div class="email">
<input class="gift_receiver_email" type="text" placeholder="<?php _e( 'Email address', WC_SC_TEXT_DOMAIN ); ?>..." name="gift_receiver_email[0][0]" value="" onblur="updateInput(this)"/>
</div>
Upvotes: 0
Reputation: 2300
Following on from my comment. You can use 'onBlur' to call a javascript function which will give the illusion of an automatic call. Another alternative would be to use onChange however I would suggest against this as this will call the javascript function EVERY time the user enters a character
Upvotes: 0