PHP, HTML and Jquery: Dynamic User Info - javascript

I'm working on a PHP form for inputting user information. I have these 3 important fields: First Name, Last Name, and E-mail. What I need to do is to set the E-mail automatically when the user enters the first two fields and before saving. For example when the user types 'First' in the First Name and 'Last' in the Last Name fields, the E-mail field should automatically show First.Last#example.com.
The code is already written and this is the part I'm working on:
echo '<TABLE ><TR><TD >'.TextInput($student['FIRST_NAME'],'students[FIRST_NAME]','<FONT color=red>'._('First').'</FONT>','size=12 class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.TextInput($student['MIDDLE_NAME'],'students[MIDDLE_NAME]',''._('Middle').'','class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.TextInput($student['LAST_NAME'],'students[LAST_NAME]','<FONT color=red>'._('Last').'</FONT>','size=12 class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.SelectInput($student['NAME_SUFFIX'],'students[NAME_SUFFIX]',''._('Suffix').'',array('Jr.'=>'Jr.','Sr.'=>'Sr.','II'=>'II','III'=>'III','IV'=>'IV','V'=>'V'),'','style="font-size:14px; font-weight:bold;"').'</TD></TR></TABLE>';
else
echo '<DIV id=student_name><div style="font-size:14px; font-weight:bold;" onclick=\'addHTML("<TABLE><TR><TD>'.str_replace('"','\"',TextInput($student['FIRST_NAME'],'students[FIRST_NAME]','','maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',TextInput($student['MIDDLE_NAME'],'students[MIDDLE_NAME]','','size=3 maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',TextInput($student['LAST_NAME'],'students[LAST_NAME]','','maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',SelectInput($student['NAME_SUFFIX'],'students[NAME_SUFFIX]','',array('Jr.'=>'Jr.','Sr.'=>'Sr.','II'=>'II','III'=>'III','IV'=>'IV','V'=>'V'),'','style="font-size:14px; font-weight:bold;"',false)).'</TD></TR></TABLE>","student_name",true);\'>'.$student['FIRST_NAME'].' '.$student['MIDDLE_NAME'].' '.$student['LAST_NAME'].' '.$student['NAME_SUFFIX'].'</div></DIV>';
echo'</td></tr>';
echo '<tr><td>'._('Email').'</td><td>:</td><td>'.TextInput($student['EMAIL'],'students[EMAIL]','','size=100 class=cell_medium maxlength=100').'</td></tr>';
I don't know how I'm supposed to edit it or where to add the jquery code.
Note: I already have the following options as I've asked this question before:
Option1 :
$('body').on('blur', '.firstname, .lastname', function(){
var fname = $.trim($('.firstname').val()),
lname = $.trim($('.lastname').val()),
email = $('#email'),
// Set your domain name here
prefix = '#example.com';
if( fname != "" && lname != "" )
email.val( fname + '.' + lname + prefix );
else if( fname == "" && lname == "" )
email.val("");
else
email.val( (fname != "" ? fname : lname) + prefix );
});
Option2:
$('#firstName', '#lastName').keyup(function() {
var domain = 'example.com';
var email = $('#firtName').val() + '.' + $('#lastName').val() + '#' + domain;
$('#email').val(email);
});
My Problem is that I don't know how to apply any of this in my code.

Yes you can do this
if you have fields like this
<input type="text" name="fn" value="" id="firstname" maxlength="30" />
<input type="text" name="ln" value="" id="lastname" maxlength="30" />
<input type="text" name="em" value="" id="email" maxlength="30" />
put the following script at the bottom of your html content
dont forget to add the jquery library
<script type="text/javascript">
$("#lastname").blur(function() { //blur event is called when the textbox lost focus
var vall = $("#firstname").val()+$("#lastname").val()+"#example.com";
$("#email").val(vall);
}) ;
</script>
comment for further changes...

var namehandler = function(){
var firstname = $('[name="students[FIRST_NAME]"]');
var lastname = $('[name="students[LAST_NAME]"]');
var email = $('[name="students[EMAIL]"]');
if (firstname.val() == '' || lastname.val() == ''){
email.val('');
return;
}
email.val(firstname.val() + '.' + lastname.val() + '#email.com');
};
$(document).ready(function(){
$('[name="students[LAST_NAME]"]').keyup(namehandler);
$('[name="students[FIRST_NAME]"]').keyup(namehandler);
});
Here's a link to the JSFiddle: http://jsfiddle.net/xw44gwvt/1/
This makes the email change instantly when the first or last name changes using the keyup event.
EDIT:
I changed the selector to get element by name. Maybe this will help, let me know if it works. If not, I'll see what i can do otherwise.

Related

How can I check if a variable is a specific type using javascript?

I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)

Else is not executing ever

Im trying to do a form, in which you put your first name, surname and city, if inputs are empty or have number in them it should say Please fill out all of available boxes and make sure there are no numbers. Else it should say quote using all of input informations. But the else is not working.
I tried cahnging the code and swapping some variables.
function FillInfo()
{
/* proměnné */
var jmeno = document.forms ["SignUpForm"] ["jmeno"].value;
var prijmeni = document.forms ["SignUpForm"] ["prijmeni"].value;
var rok = document.forms ["SignUpForm"] ["mesto"].value;
/*Kontrola zdali input políčka jsou prázdná či pokud bylo zadáno číslo */
if(jmeno=="" || jmeno!=NaN || prijmeni=="" || prijmeni!= NaN || mesto=="" || mesto!=NaN){
document.getElementById("info").innerHTML = "Please fill out all of available boxes and make sure there are no numbers";
}
else{
document.getElementById("info").innerHTML = "Thank you" + " " + jmeno + " " + prijmeni + " from" + " " + mesto + "." + " " + "You are now being considered as our next adventurer. Good luck!";
}
}
<div class="heading2">
<div class="container2">
<p>Do you want to travel troughout space? Then fill out our form!</p><br>
<form name="SignUpForm">
<input type="text" name="jmeno" placeholder="First name" required><br>
<input type="text" name="prijmeni" placeholder="Last name" required><br>
<input type="text" name="mesto" placeholder="City" required><br><br>
<div id="info" class="well"></div>
<input type="button" class="otherpage" onclick="FillInfo();" value="Submit" /><br><br>
Return
</form>
</div>
</div>
Your if condition has to change, it always evaluates to true.
Instead of:
if (jmeno=="" || jmeno!=NaN || prijmeni=="" || prijmeni!= NaN || mesto=="" || mesto!=NaN) {
You should try:
if (jmeno==="" || isNaN(jmeno) || prijmeni==="" || isNaN(prijmeni) || mesto==="" || isNaN(mesto)) {
By the way, NaN is never equal to NaN, you have to use isNaN to know if it's a NaN.
However, this code is not what actually want. You want to check that there are no numbers, right? Depending on if you want no digits at all or no number-only values, you have to adapt your code. For example: !isNaN(Number(jmeno)) to check if the value is a number-only value. The values you get from the text inputs are always strings so the conversion is needed.
Your logic is wrong
jmeno=="" || jmeno!=NaN
Will always evaluate to true, I think you mean
jmeno=="" || isNaN(jmeno)
Obviously the rest of the statement needs editing too.

How to split string of input tag HTML?

When a user enters the below link in an input tag, I just want the last part of the string, in order to minimize input mistakes - the two input fields generate a new link that the user can copy and use.
name:id:5icOoE6VgqFKohjWWNp0Ac (I just want the last '5icOoE6VgqFKohjWWNp0Ac' part)
Can anyone help me with amending the below to achieve this?
function generateFullName() {
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + document.getElementById('fName').value + ('?context=') + document.getElementById('lName').value;
}
Enter a product ID:
<input type="text" id="fName" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' />
Enter a user ID:
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M'/><br/></p>
Tada! This would be the link for your campaign:
<input type="text" id="txtFullName" name="txtFullName" />
Here's a JavaScript function that takes a string as input, and formats it to only keep the last part after the last colon (if it contains a colon):
function parseColon(txt) {
return txt.split(":").slice(-1).pop();
}
Eg. parseColon("a:b:c") would return "c"
You can validate your inputs with:
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 32 && numberOfColons == 2)
return true
return false
}
In your code you can use these two functions to check & parse lName and fName like this:
function generateFullName() {
var lName_val = document.getElementById('lName').value;
var fName_val = document.getElementById('fName').value;
//fill in link in the output if fName and lName are valid inputs
if(isValidInput(fName_val) && isValidInput(lName_val))
document.getElementById('txtFullName').value = ('https://nlproducts.nl/item/') + parseColon(fName_val) + ('?context=') + parseColon(lName_val);
// otherwise, clear the output field
else
document.getElementById('txtFullName').value = "";
}
function parseColon(txt) {
// return the part after the last colon
return txt.split(":").slice(-1).pop();
}
function isValidInput(txt) {
numberOfColons = txt.split(":").length - 1;
if (txt.length == 38 && numberOfColons == 2)
return true
return false
}
Enter a product ID:<br>
<input type="text" id="fName" oninput="generateFullName()" placeholder='0A5gdlrpAuQqZ2iFgnqBFW' size="50"/><br/>
Enter a user ID:<br>
<input type="text" id="lName" oninput="generateFullName()" placeholder='37i9dQZF1DXcBWIGoYBM5M' size="50"/><br/><br/>
Tada! This would be the link for your campaign:<br>
<input type="text" id="txtFullName" name="txtFullName" size="50"/>

How do I change the value of an input text field based on if a checkbox is checked or not?

Basically I have an email field, then a checkbox under it. If it's checked i want it to change the value of the email address field to something like originalemailATgmail.com#mydomain.com then if it's unchecked I want it to display "originalemail#gmail.com" that it started with. I'm having a problem switching back to the original email value after changing it to "derrrr"
[html]
<input type="email" name="email_address" value="originalemail#gmail.com" id="email_addressez">
<input type="checkbox" name="post_date_email" value="post_date_email" id="post_date_email" onclick="postDateEmail(document.getElementById("email_addressez").value)">
function postDateEmail(email){
var emailchecked=document.getElementById("post_date_email").checked;
var emailsub = "derrrrrr";
var originalemail = email;
alert("email is "+email+" checked is "+emailchecked);
if(emailchecked=true){
//var email=document.getElementById("email_addressez").value;
alert("in if, email is " + email + " checked is "+emailchecked);
document.getElementById("email_addressez").value = emailsub;
}else{
alert("else" + email + " checked is "+emailchecked);
document.getElementById("email_addressez").value = email;
}
}
[/html]
This is a working sample of what you are trying to do.
And notably, when writing conditional operation like if else statements.
You use == or === depending on what you want.
In your case, using = is an assignment operator so your if statement will not work at all.
Below is a simplified version using ternary operators ? and :
function postDateEmail() {
var checked = document.getElementById('post_date_email').checked;
document.getElementById('email_addressez').value = 'originalemail' + (checked ? 'AT' : '') + '#gmail.com';
}
<input type="email" name="email_address" value="originalemail#gmail.com" id="email_addressez">
<input type="checkbox" name="post_date_email" value="post_date_email" id="post_date_email" onclick="postDateEmail()">
ended up modifying your code to this:
var checked = document.getElementById('post_date_email').checked;
var originalemail = <?php echo(json_encode($email)); ?>;
var postDateEmailAddy = originalemail.replace("#", "AT");
var postDateEmailAddy = postDateEmailAddy.replace(".com", ".com#mydomain.com");
//alert(postDateEmailAddy);
document.getElementById('email_addressez').value = (checked ? postDateEmailAddy : originalemail);
where $email is defined elsewhere in the php.

How to validate empty value using javascript?

Here is html code for text field what to check for empty/null values
function myFormValidation() {
alert("HI");
var name = document.getElementById("name").value;
alert(name);
if (name == null || name == " ") {
document.getElementById("inp1").innerHTML = "Enter your name please";
} else {
document.myForm.submit();
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" name="inp1" />
<input type="button" value="Register" onclick=" myFormValidation()" />
I want to validate using innerHtml, but my js is not getting called.
I guess removing the space between " " may work
your code
if(name==null || name ==" " ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
change to
if(name==null || name =="" ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
You might like to validate the input edit through the help of regular expressions
if ( name == null || /\s*/g.test(name) )
{
document.getElementById("inp1").innerHTML = "Enter your name please";
}
The expression \s* covers both the empty string as well as the input consists of multiple blank spaces, such as " " for example
I'm not really familiar with JavaScript/jQuery but I think this is what you're looking for. I've changed your input for the message to label because your type is hidden which also means that users will not be able to see the message at all.
Also, you didn't include the id attribute for your inp1 so it's impossible to use getElementbyId().
function myFormValidation() {
if (document.getElementById("name").value == "") {
document.getElementById("inp1").innerHTML = "Enter your name please";
}
else {
var name = document.getElementById("name").value;
alert("HI");
alert(name);
document.myForm.submit();
}
}
Name:
<input type="text" name="name" id="name" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<label id="inp1"></label>
Here is example:
function myFormValidation() {
var user = document.getElementById("name").value;
if (user === "") {
document.getElementById("body").innerHTML = "Enter your name please";
} else {
document.getElementById("body").innerHTML = user + " " + "How are you..!";
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<div id="body"></div>

Categories