Auto generate email based on username in WordPress - javascript

I've had some trouble getting this to work in the new user registration form, what I want is to have the email field automatically filled with a dummy email generated based on the username.
For example, if the user inputs user1 the generated email should be user1#test.com
I want it to be done in the new user form in case a user has a real email it can be specified instead of the dummy one.
What I've tried was some javascript and jQuery, but I can't get it to work, you can see the code below.
jQuery('#user_login').on('input propertychange paste', function()
{
var x = $('#user_login').val();
$($email).val( x + '#test.com');
});
Current javascript
<script>
$("user_login").change(function AutoEmail() {
var x= $('#user_login').val();
$('#email').val(x+'#test.com');
});
</script>
Also, where should this code be placed?, I'm a bit lost on the way things are organized in WordPress.

Try this.
$(document).on( "input", "#user_login", function AutoEmail() {
var x= $('#user_login').val();
if( x != "" ) {
$('#email').val(x+'#test.com');
} else {
$('#email').val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
Username: <input type = "text" id = "user_login"><br>
Email: <input type = "text" id = "email">

Related

Why isnt my javascript function being run?

I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:
<div class = mainInfo>
<?php include "header.php"; ?>
<form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
username: <input type = text name = "userName">
password: <input id= "p1" type = password name = "password">
reenter password: <input id ="p2" type = password name = "passwordConfirmation">
<input type="submit" name =" submitButton" value ="submit">
</form>
<div id="feedback">
</div>
</div>
<script>
function validate()
{
document.getElementById("feedback").innerHTML = "functionbeingcalled";
var p1 = document.getElementById("p1").value,
p2 = document.getElementById("p2").value);
if( ! p1===p2 )
{
document.getElementById("feedback").innerHTML = "passwords dont match";
}
if(p1==="")
{
document.getElementById("feedback").innerHTML = "Must have a password";
}
}
window.setInterval(validate(),1000);
</script>
<?php include "footer.php"; ?>
I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all. This line:
document.getElementById("feedback").innerHTML = "functionbeingcalled";
isn't working either.
Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.
Pass the function instead of calling it.
// no parentheses!
window.setInterval(validate, 1000);
And this is wrong.
if( ! p1===p2 )
it should be this
if( p1!==p2 )
because of the higher precedence of the prefix !
I would suggest that you add listeners on your input fields! ;)
It will then only run the validation code when changes are made. In other words; only when necessary.
It will run the validation code "immediately" when input is changes. Instead of validation every 1000 ms.
I see you are not using jQuery (yet)? If you want to validate on 'change' using plain js, here is a solution: Plain js solution
If you are okay with adding the jQuery library to you code, then it can be done very easy like this jQuery solution
Well, you've got several issues...
First, with setInterval(), you only pass a reference to the function that should be called (validate in your case), you don't actually invoke it as you are doing (validate()). This essentially runs validate immediately and then sets the return value from it as the function to be called every second. Since validate() doesn't return a value, nothing happens every second thereafter.
You also have a typo with: if( ! p1===p2 ), which indicates that the Boolean opposite of p1 is being tested against p2. What you want is: if(p1 !== p2 ), which is how you express "not strictly equal to".
Now, really you are going about validation the wrong way. Instead of running a validation function on a timer, which is inefficient, you'd want to validate in one or more of these cases:
just before the entire form is submitted
just after the user leaves a form field
as the user is entering data
some combination of all 3
Each of those scenarios is handled through event handlers and a working example of each is shown below.
// Get the DOM references you'll need just once:
var feedback = document.getElementById("feedback");
// Don't set variables equal to property values of DOM elements because
// if you decide you need a different property value, you have to re-scan
// the DOM for the same element all over again.
var p1 = document.getElementById("p1")
var p2 = document.getElementById("p2");
var form = document.querySelector("form");
// Use this to validate when submit is pressed (causing form to be submitted):
form.addEventListener("submit", function(evt){
// If validate function returns false, don't submit
if(!validate()){
evt.preventDefault(); // cancel the form submission
feedback.textContent = "Can't submit. Form is not valid!";
}
});
// Get the elements that need to be validated:
var inputs = document.querySelectorAll("input[type=text],input[type=password]");
// Convert that node list into an array:
inputs = Array.prototype.slice.call(inputs);
// Loop over array and set up event handlers for inputs
inputs.forEach(function(input){
input.addEventListener("blur", validate); // Used to validate when user moves off of each element
input.addEventListener("input", validate); // Used to validate as data is being entered
});
function validate() {
// Keep track of whether the form is valid or not. Assume that it is by default
var valid = true;
// .innerHTML is for when you want to assign a string containing
// HTML to a DOM element. This invokes the HTML parser and renders
// the HTML. If you don't have HTML in the string, use .textContent
// instead, which doesn't invoke the HTML parser and is more efficient
// See if the password was typed in both boxes before telling the user
// that the passwords don't match
if(p1.value && p2.value){
// Are they the same?
if(p1.value !== p2.value){
feedback.textContent = "passwords dont match";
valid = false;
} else {
feedback.textContent = "passwords match";
}
} else {
// If both password fields aren't filled in, the form can't be valid
valid = false;
}
if(p1.value === "") {
feedback.textContent = "Must have a password";
valid = false;
}
// Send a result to the caller so it can be known by other code if the form is valid
return valid;
}
<div class = "mainInfo">
<form name="SignUpForm" action="signUpHandler.php" method='POST' class="inputLists">
<div>username: <input type="text" name="userName"></div>
<div>password: <input id="p1" type="password" name="password"></div>
<div>reenter password: <input id="p2" type="password" name="passwordConfirmation"></div>
<!-- Any form element that has a "name" attribute will submit its name/value as
part of the form data when the form gets submitted. You probably don't want
the actual submit button to be included in this, so don't give the button
a "name" attribute. -->
<input type="submit" value="submit"> <input type="reset" value="reset">
</form>
<div id="feedback"></div>
</div>

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

JavaScript - How to assign user input value to variable inside script

Using widget script--http://socialmention.com/tools/-- from Social Mention. Tried to modify by adding input box to allow user to change social media topic (var smSearchPhrase). I created a function [smSearch()] to retrieve user data (smTopic), assign it to a new variable (var newTopic) and then assign that value to var smSearchPhrase. The assignment does not work.
The function appears to work based on values observed via alerts, however, I cannot figure out how to assign the value from var newTopic to var smSearchPhrase inside the script. I experimented by placing script inside the function, but that didn't work either. Any assistance is appreciated.
If I failed to include all necessary information, please advise. Thanks for any assistance.
HTML:
<form>
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button onclick="smSearch()">Submit</button>
<input type="reset">
</form>
Function: (includes alerts to check values)
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
Script: var smSearchPhrase in original has value assigned, e.g. var smSearchPhrase = 'social mention';
<script type="text/javascript">
// search phrase (replace this)
var smSearchPhrase;
// title (optional)
var smTitle = 'Realtime Buzz';
// items per page
var smItemsPerPage = 7;
// show or hide user profile images
var smShowUserImages = true;
// widget font size in pixels
var smFontSize = 11;
// height of the widget
var smWidgetHeight = 800;
// sources (optional, comment out for "all")
//var smSources = ['twitter', 'facebook', 'googleblog', 'identica'];
</script>
<script type="text/javascript" language="javascript" src="http://socialmention.s3.amazonaws.com/buzz_widget/buzz.js"></script>
I think your form is submitting back to the backend, you need to stop the form from doing that by returning false from onsubmit or canceling the event.
So this should work:
<form onsubmit="return smSearch();">
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button>Submit</button>
<input type="reset">
</form>
And return false in your JavaScript:
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
return false;
}
Personally I'd use preventDefault() on the event argument (not shown here), but that only works across all browsers when you also include a JavaScript library like jQuery as some versions of IE use a bubble property on the event or something.

Create URL upon JavaScript submit form

I currently have a form with some JavaScript functions and localstorage.
I'm trying to get that when a user types a value into a textbox, the search bar changes the URL from "mysite.com" to "mysite.com/%userinput%". Then that user can send that link to someone else and that person will then see what the original user saw.
This will change the URL after input.
As I understand from your question and comments, you don't want to load the URL, just change it, so try this fiddle: http://jsfiddle.net/GrP6U/2/show/
The code behind is:
JavaScript
var theForm = document.getElementById('theForm');
var theInput = document.getElementById('subj');
theForm.onsubmit = function(e) {
var myurl = "http://jsfiddle.net/GrP6U/2/show/?input=" + encodeURIComponent(theInput.value);
window.history.pushState('', "Title", myurl);
return false;
}
HTML
<form id="theForm">
<input id='subj'/>
<input type='submit'/>
</form>

display * instead of password value in the display table in list page?

i have a table with the fields username , password , email and phone . but the display page should show the value off the password as * . only when editing it should show the value !
Eg: take my password as pass1234
it should be displayed in list page as ***
but wen editing it it should show as pass1234 . how can i do that ?
This requires some Javascript onfocus handler:
field = document.getElementById('pass');
field.onfocus(function() { this.setAttribute('type','text'); });
field.onblur(function() { this.setAttribute('type', 'password'); });
You should only show the password in plaintext when the user asks for it, e.g. by clicking a button. What do you think the asterisks are good for?
However, you can't just set the type of the input, because IE does not allow that. So you will need to completely replace the element. For
<input name="pw" id="pw" type="password"></input>
<label><input id="plain" type="checkbox"></input>Show plaintext</label>
the JS would look like this (using jQuery for event attaching and co, you should be able to adapt this if you need):
$("#plain").change(function() {
var pw = $("#pw"),
type = this.checked ? "text" : "password";
if (type == pw.prop("type")) return;
$("<input>", {name: "pw", id:"pw", type:type}) // could be done programatically
.val(pw.val())
.replaceAll(pw);
});

Categories

Resources