Javascript Concatenate FirstName, LastName and Code - javascript

I am trying to concatenate the first letter of both names onto the randomly generated code.
var firstname = prompt("Please enter your first name.");
var lastname = prompt ("Please enter your last name.");
if (amountCorrect >= 4){
alert("Your login Code for the store is: " + str(firstname,1,1) + str(lastname,1,1) + (generateCode())); // Do the generateCode function
}
else{
alert("You have not passed on this occasion. You will now be taken back to the homepage.");
window.history.go(-1); // Go back a step
}
}
function generateCode(){
var text = "";
var possible = "0123456789";
for( var i=0; i < 4; i++ ){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}

There is no definition for 'str' used within your alert line..
alert("Your login Code for the store is: " + firstname[0] + lastname[0] + (generateCode()));
The above should work. It also looks like you have a stray } after the if block. You should probably also be doing more error checking for the user input, if the user doesn't enter a value at the prompt for example, you will get undefinedundefined#### where #### is the generated code.

You can use substring to extract the first character:
alert("Your login Code for the store is: " + firstname.substring(0,1) + lastname.substring(0,1) + (generateCode()));
Here is the documentation for String.prototype.substring.

Replace the line
alert("Your login Code for the store is: " + str(firstname,1,1) + str(lastname,1,1) + (generateCode())); // Do the generateCode function
with
alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function

Related

Copy command in html for chrome to copy multiple text boxes

I am creating a note pad that is to help keep notes consistent between users. I am unable to copy the multiple text boxes to a string. I have attached all of my Java Script.
The copy button that I would like to use to link the multiple text boxes into one string of text. the reset button works at clearing the page and the copy button follows the not empty text box checks. Please help with my copy string to the clipboard.
I have tried a bunch of different sites on the java script with no success. I have also reviewed Stack Overflow to see if I could find a close project.
input type="button" id="BtnSupSubmit" value="Copy" onclick="notEmptySup()" style="width: 87px"
function settime() {
var curtime = new Date();
var curhour = curtime.getHours();
var curmin = curtime.getMinutes();
var time = "";
if (curhour == 0) curhour = 12;
time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
(curmin < 10 ? "0" : "") + curmin + ":" +
(curhour > 12 ? "PM" : "AM");
document.date.clock.value = time;
clock = time
window.status = time
}
function notEmptySup() {
var myTextField = document.getElementById('TxtBoxCallersName');
if (myTextField.value != "") notEmptySup2()
else
alert("Please enter callers name.")
}
function notEmptySup2() {
var myTextField = document.getElementById('TxtBoxSupIssue');
if (myTextField.value != "") notEmptySup3()
else
alert("Please enter the reason for the escalation.")
}
function notEmptySup3() {
var myTextField = document.getElementById('TxtBoxSupAction');
if (myTextField.value != "") notEmptySup4()
else
alert("Please enter the action you took to help the customer.")
}
function notEmptySup4() {
var myTextField = document.getElementById('TxtBoxSupResolution');
if (myTextField.value != "") CreateMessage()
else
alert("Please enter the resolution of the call.")
}
function CreateMessage() {
strMessage =
"Time: " + clock + "\|" +
"***Supervisor Escalation" + "\***|" +
"Caller: " + document.getElementById("TxtBoxCallersName").value + " \| " +
"Reason: " + document.getElementById("TxtBoxSupIssue").value + " \| " +
"Action: " + document.getElementById("TxtBoxSupAction").value + " \| " +
"Resolution: " + document.getElementById("TxtBoxSupResolution").value + " \| " +
"Ticket Number: " + document.getElementById("TxtBoxSupTicketNumber").value + " \| " +
"Addl Notes: " + document.getElementById("TxtBoxSupNotes").value;
document.getElementById("hdnBuffer").value = strMessage;
var buffer = document.getElementById("hdnBuffer").createTextRange();
buffer.execCommand("Copy");
}
Most of what you have is redundant. See comments inline below:
// Get a reference to the form
let frm = document.querySelector("form")
// Set up a sumbit event handler for the form
frm.addEventListener("submit", function(evt){
// Just get the locally formatted time
var message = "Time: " + new Date().toLocaleTimeString() +
"\n***Supervisor Escalation***\n\n";
// Get all the input elements
let inputs = document.querySelectorAll("input");
// Loop over them
for(let i = 0; i < inputs.length; i++){
if(inputs[i].value === ""){
alert("Please enter the " + inputs[i].dataset.message);
inputs[i].focus(); // Put focus on bad element
evt.preventDefault(); // Cancel the form submit
break; // Exit the loop
} else {
// Update the message
message += inputs[i].dataset.message + ": " +
inputs[i].value + " \n";
}
}
alert(message); // Do whatever you want with the message
});
<form action="https://example.com" method="post">
<div><label>Name:<input data-message="callers name"></label></div>
<div><label>Issue: <input data-message="reason for the escalation"></label></div>
<div><label>Action: <input data-message="action you took to help the customer"></label></div>
<div><label>Resolution: <input data-message="resolution of the call"></label></div>
<button type="submit">Submit Ticket</button>
</form>

Filter out invalid emails to NOT show up from alert prompts onto document

The behavior I want to get is when the user inputs anything invalid(data), to not show up onto the document write as the domain and username since we are using a slice and uppercase in order to manipulate the username only and show the domain.
It works fine when a valid email in entered, but not when erroneous data is entered it still writes it to document.
function emailValid(email) {
var emailRegex = /^[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/;
var valid = email.match(emailRegex);
return valid;
}
var email = prompt("Please enter your email address");
if (emailValid(email)) {
document.write("<p>Thank you for registering with us!</p>");
} else {
document.write("<p> Error: Please enter a valid email address </p>");
}
var atIndex = email.indexOf('#');
var getString = email.slice(atIndex + 1);
var getUsername = email.slice(0, atIndex);
var valid = getUsername.toUpperCase();
document.write("<p>The domain for this email is " + getString + "</p>");
document.write("<p>The username for this email is " + valid + "</p>");
I took Jetos recommendation and did this:
var email = prompt("Please enter your email address");
if (emailValid(email)) {
var atIndex = email.indexOf('#');
var getString = email.slice(atIndex + 1);
var getUsername = email.slice(0, atIndex);
var valid = getUsername.toUpperCase();
document.write("<p>Thank you for registering with us!</p>");
document.write("<p>The domain for this email is " + getString + "</p>");
document.write("<p>The username for this email is " + valid + "</p>");
} else {
document.write("<p> Error: Please enter a valid email address </p>");
}

I'm trying to clear the input field after the button is clicked

I need the input field to clear after the user clicks the button to convert the number they've entered. I'm having a difficult time figuring this out, if anyone can help i feel like it's a very simple solution but, I can't seem to wrap my head around it.
(function () {
//Constants
const KM_TO_MILES = 0.625;
const MILES_TO_KM = 1.6;
var user = prompt("So..What's your name beautiful?");
if (user === null) {
alert("NOOOOO, you cancel me? meanie.")
remove();
}
//on load function
window.onload = function () {
var result = document.getElementById("result");
//display the user's name with a message prompt to continue to enter a distance
result.innerHTML = "Okay, " + user + ", enter your distance and I will calculate for you, don't worry.";
document.getElementById("convertBtn").onclick = startConvert;
};
//on load function done
//conversion function
function startConvert() {
var placeholder = document.getElementById("distance").value;
var distanceInput = document.getElementById("distance").value;
var conversion = document.getElementById('List').value;
document.getElementById("List").value;
// If the user doesn't input a number run the alert
if ((placeholder === "") || (conversion == "Select Types")) {
alert("You didn't enter anything mate");
// If the user inputs a number and clicks KM to M then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Kilometers to Miles") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * KM_TO_MILES + " miles.");
// If the user inputs a number and clicks M to KM then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Miles to Kilometeres") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * MILES_TO_KM + " kilometers.");
}
}
//conversion function done
}());
document.getElementById('yourid').value = '';
you call this event on your button click surely it'll be works

Jquery to capture and output information from html form

I'm having problems with this bit of code. For some reason it won't capture the radSize, and it's giving me problems. Any ideas?
The page is supposed to capture the values, then add the base and size together to output total.
$(function() {
$("#btnMessage").click(function() {
var name = $("input[name=txtName]").val();
var phone = $("input[name=txtPhone]").val();
var basePizza = $("#cboBase").val();
var size = $("input[name=radSize]").is(":checked").val;
// alert(name +" "+ phone +" "+ basePizza +" "+ size);
var message = "";
var calculation = parseInt(basePizza) + parseInt(size);
//test each value
if (name == "")
message += "--Enter a first name";
if (phone == "")
message += "\n--Provide a number";
if (basePizza == "0")
message += "\n--Pick Base Pizza";
if (size == "")
message += "\n--Pick a Size";
else
message += name + "," + " " + "Your total for the pizza will be " + "$" + calculation;
alert(message);
// $('#output').html(message);
});
});
This line isn't really valid:
var size = $("input[name=radSize]").is(":checked").val;
The .is(":checked") part is a jQuery filtering utility that will return true or false.
Instead, you want to do something like this:
var size = $("input[name='radName']:checked").val();
Assuming only one of the "radSize" checkboxes can be checked, $("input[name='radName']:checked") will return the checked checkbox and val() will return its value.

Why doesn't this function give window.alert when user enters spaces or too many/not enough characthers?

Seemed like an easy problem to solve. Cannot figure out why the code will return the secret word despite entering spaces or too many/too few characters. Need a little help. Thanx!
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
<!--variable to hold secret word-->
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
do {
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length < 6) {
window.alert("secret word is too short");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length > 6) {
window.alert("secret word is too long")
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user_prompt.indexOf('') >= 0) {
window.alert("secret word cannot contain spaces");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
}
while(user_prompt != -999);
}
Apart from the typos you have (user_prompt != user.prompt), you're looking for a 7-character string with no spaces.
What this condition checks:
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
is a 6-character string with ANY character present.
What you need instead is:
if(user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
This will be true if the string length is 7 and there are no spaces.
Here's a working example, I've simplified it a bit so it's easier to work with in a snippet here, but you can see and reuse the conditions:
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
document.getElementById("guess").innerHTML = '';
if (user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
document.getElementById("guess").innerHTML = text + "<br>" + user_prompt + "<br>" + output;
} else if (user_prompt.length < 7) {
document.getElementById("guess").innerHTML = "secret word is too short";
} else if (user_prompt.length > 7) {
document.getElementById("guess").innerHTML = "secret word is too long";
} else if (user_prompt.indexOf(' ') >= 0) {
document.getElementById("guess").innerHTML = "secret word cannot contain spaces";
}
}
<div id="guess"></div>
<button onclick="secretWord()">Run</button>
else if(user.prompt.length < 6) {
// ...
else if(user.prompt.length > 6) {
In both cases, user.prompt.length should be user_prompt.length
your problem is in else if statement
it should be user_prompt and not user.prompt
besides, even if you enter space yet exactly right amount of characters say 6 or so, it will pass the first if test.
you are not checking for space i.e. ' ' but ''. see to it you check for spaces properly.

Categories

Resources