Javascript prompt() alternative - Waiting for user response - javascript

I would like to ask series of questions to users in one function.
If I use prompt(), it is possible to ask all the questions in one function.
function question(){
var name = prompt("Enter your name");
var age = prompt("Enter your age");
}
But if I try to use input tag, this is impossible.
function question(){
document.write("Enter your name");
// you can't wait until the user responds. It will simply execute all the lines at once.
name = document.getElementById("input").value;
document.write("Enter your age");
age = document.getElementById("input").value;
}
If I do this, I can't use input tag to ask questions to users in one function. How can I wait until the user responds?

To chain prompts you can do something like:
const name = prompt("Enter your name");
if (!!name) {
const age = prompt("Enter your age");
if(!!age){
...
}
}
Or if you can use rxjs 5.5+ in your project you can use an observable to wait for the first prompt.
For example:
of(prompt("Enter your name"))
.pipe(first(), filter((name) => !!name))
.subscribe((name) => {
var age = prompt("Enter your age")
if(age) {
...
}
});

You can keep all your input boxes disabled except the first one. The second one can be enabled upon the user response to the first one. The line of inputs will go on like this.
Here is a little demonstration. Please note this is only a sample code which shows you the design pattern.
<input id="name"></input> <button onClick="getInput()">Ok</button>
<input id="address"></input> <button onClick="getInput()" disabled>Ok</button>
and in JS
var name, address;
functon getInput() {
name = document.getelementById("name").value;
address = document.getElementById("address").value;
if (address !== "")
document.getElementById("address").removeAttribute("disabled");
}
There are many advance methods than this is available in JS. But probably you should study this pattern first.

You cant take 2 different values from the same input in a function. You should create another input or some button to differentiate variables. For example:`
Enter your name
Enter your age
Save
var bSave = window.document.getElementById('bSave');
bSave.addEventListener("click", question);
var newName = window.document.getElementById('iName');
var newAge = window.document.getElementById('iAge');
function question() {
name=newName.value;
age=newAge.value;
}
</script>
`

document.write() is to writes HTML not for asking user input like prompt(). what you need is input validation before user submit the form like
function checkQuestion(){
if(document.getElementById("name").value == "")
alert('name empty');
if(document.getElementById("age").value == "");
alert('age empty');
}

Related

Trying to generate username Javascript

Before I start I should mention i'm a complete novice and I apologise if this code is horrific.
I'm trying to create a username using first initial and surname to be ouputted with a welcome message of "hello Username, welcome to myfunction!".
I'm suppose to use a string to attach the initial and surname together then concatenate the first character of string 1 with string 2 and store the username.
any help would be appreciated as this is for school.
here's what I have so far...
<!DOCTYPE html>
<script type = "text/javascript">
// GenerateUsername Function
function GenerateUsername ()
{
var x;
var firstInitial = prompt("Please enter your initial of your first name");
var surName = prompt("please enter your surname");
var user = new Array();
firstInitial [0] = "user";
surName [1] ="user";
document.write(firstInitial + surName);
}
if (user == 0)
{
alert("welcome, " + user);
}
</script>
I think this might can help you. return value from function call and then bind in alert
function GenerateUsername ()
{
var x;
var firstInitial = prompt("Please enter your initial of your first name");
var surName = prompt("please enter your surname");
var user = new Array();
firstInitial [0] = "user";
surName [1] ="user";
return firstInitial[0] + ' ' + surName[1];
}
if (user == 0)
{
alert("welcome, " + GenerateUserName());
}
if you want to call your function when your page is loaded you have to add the attribute onload="GenerateUsername()" on a html tag.
Also you should place your javascript in a different file and comment your code (it is easy to understand it but if you're a total beginner in javascript you will probably not remember what's the difference between prompt and alert in some days for example).

How can I get my span id’s to display the appropriate messages when user doesn’t follow rules?

I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code
$('#button2').on('click', function () {
var NewUsernameError = document.getElementById("New_Username_error");
var NewPasswordError = document.getElementById("New_Password_error");
var NewEmailAddressError = document.getElementById("New_Email_error");
// var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error");
// How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
if($(".newUsername").val().length < 6)
{
NewUsernameError.innerHTML= "The username must be at least 6 characters";
// NewUsernameError.innerHTML= "There is an already existing account with username";
}else
{
NewUsernameError2.innerHTML = '';
}
if($(".newPassword").val().length < 6) {
{
NewPasswordError.innerHTML= "The password must be at least 6 characters";
}else{
NewPasswordError.innerHTML = '';
}
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
{
NewEmailAddressError.innerHTML= "The email must not be left empty.";
NewEmailAddressError.innerHTML= "The email must contain # symbol in it.";
}else{
NewEmailAddressError.innerHTML= '';
}
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
}else{
NewRepeatEmailAddressError.innerHTML= '';
}
.
Lots of problems here.
if($(".newEmail")== "" && $(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
That tries to compare the <input> element instead of its contents.
if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){
That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)
Instead, you want .val():
if($(".newEmail").val() == "" && $(".newEmail").val() != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){
A secondary problem is where you try to assign two error messages simultaneously:
NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered.";
NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank.";
In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.
Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:
$(".newEmail") != /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z])
Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an # symbol:
/#/.test($('.newEmail').val())
Putting it all together
Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:
var validate=function() {
// clear out the error display ahead of time:
var newUsernameError = $("#New_Username_error").html('');
var newPasswordError = $("#New_Password_error").html('');
var newEmailAddressError = $("#New_Email_error").html('');
var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');
// just to make the later conditions easier to read, let's grab all the values into vars:
var newUsername = $('.newUsername').val();
var newPassword = $('.newPassword').val();
var newEmail = $('.newEmail').val();
var repeatEmail = $('.repeatEmail').val();
// presumably you'll want to prevent form submit if there are errors, so let's track that:
var errorsFound = false;
if (newUsername === "") {
errorsFound = true;
newUsernameError.html("The username must not be empty.");
} else if (newUsername.length < 6) {
errorsFound = true;
newUsernameError.html("The username must be at least 6 characters.");
}
if (newPassword.length < 6) {
errorsFound = true;
newPasswordError.html("The password must be at least 6 characters.");
}
if (newEmail === "") {
errorsFound = true;
newEmailAddressError.html("The email must not be left empty.");
} else if (!/#/.test(newEmail)) {
errorsFound = true;
newEmailAddressError.html("The email must contain an # symbol.");
}
if (repeatEmail !== newEmail) {
errorsFound = true;
newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
}
// No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.
// OK, all conditions checked, now:
if (errorsFound) {
// prevent form submit. (If this is called in an onsubmit handler, just return false.)
} else {
// allow form submit.
}
console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's
$('#button2').on('click', function () {
// VALIDATE USERNAME
var newUserErrStr = '';
var newUsernameVal = $(".newUsername").val();
if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
document.getElementById("New_Username_error").innerHTML = newUserErrStr;
// VALIDATE PASSWORD
var newPasswordErrStr = '';
var newPasswordVal = $(".newPassword").val();
if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;
// VALIDATE EMAIL
var newEmailErrStr = '';
var newEmailVal = $(".newEmail").val();
if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
if (newEmailVal !== /^[a-zA-Z0-9]#[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain # symbol in it.";
document.getElementById("New_Email_error").innerHTML = newEmailErrStr;
});

How do I get my function to add the userName to the h2 tag

I am new to javascript and I am having trouble getting the function below to work correctly. The function is supposed to add the userName plus what is already in the h2 header to the website after the user enters their name. It needs to show up as soon as the user enters their name.
/*
* this function will promtpt the user for their name;
* store name in a variable called userName.
* Use variable called phrase, which will hold h2 content
* Lastly write the "new" h2.
*/
function logIn() {
var userName = prompt("Please enter name");
pharse = document.getElementsByTagName('h2').innerHTML;
}
Alright, I'll take a crack at this
// This solution depends on you having an id on your 'h2' element
var userName = prompt('Please enter name');
var headerElem = document.getElementById('yourIdHere');
var pharse = headerElem.innerHTML;
headerElem.innerHTML = pharse + ' ' + userName;
Let me know if this is what you're looking for/if you want an explanation of why I did things the way I did!
Here's a working code pen you can play around with! http://codepen.io/csavage1994/pen/evvXoG
Here is an example of how to accomplish this:
https://jsfiddle.net/mcwc66op/
HTML
<h2>
H2 Text
</h2>
Javascript
var h = document.querySelector('h2');
var userName = prompt("Please enter name");
h.innerHTML = h.innerHTML + ' / ' + userName
document.getElementById("name").innerHTML += prompt("What is your name?");

How to put function using string control

On this first Image I would like to declare a variable that is string that would be used for making a condition if the username that is input if the string has 5 numbers it would be tag as EmployeeID if string has 10 numbers it would be tag as studentID.
So that before I create another app for User Interface for Employee and Student it would then evaluate.
I am not able deduce the code language, but I will write down a function considering that it's a jQuery.
var Id = "" , type = "";
if($("#Userid").val().length = 5)
{
Id = $("#Userid").val();
type = "employee";
}
elseif($("#Userid").val().length = 10)
{
Id = $("#Userid").val();
type = "student";
}
else
{
alert("Invalid ID");
}
Hope that's help! Now you can check type variable to decide the type of current logged in user.

How to validate window.prompt in javascript?

Is there a way to validate the text of the input textBox of the prompt box displayed by calling window.prompt() in javascript?
I mean something like to not to close the prompt box when clicking its OK button if the string written in its input textBox contains numbers or other illegal chars defined by me, etc.
No, there is not.
.prompt is native functionality that can't be modified.
If you want input validation, you're going to need to use a custom prompt. It might be worth looking into UI libraries like jQueryUI, for example.
var obj = {};
function validate( str ){
return !! str; //or your own validation
}
function setName ( error_message ) {
var name = prompt( (error_message || '') + "Enter a name: ");
if ( ! validate( name ) ) {
setName( 'Invalid name entered\n' );
} else {
obj.name = name;
}
}
If you really want to use only prompt then this is the solution. But, I'd suggest you to use a modal dialog or create your own component.
You can't validate the input of a prompt before closing it. You could simulate this by creating your own type of prompt, or using jQueryUI.
I came across this exact problem today while writing a bookmarklet which requests user input.
It struck me that it's possible to validate window.prompt simply by using a while loop:
let promptedAnswer = null;
while (promptedAnswer !== 'spoon') {
promptedAnswer = prompt('Complete this phrase: "There is no [ ]."');
}
Working Example:
let chosenNumber = 0;
while ((chosenNumber < 1) || (chosenNumber > 10)) {
chosenNumber = prompt('Choose a number between 1 and 10:');
}
console.log('Your chosen number is ' + chosenNumber);

Categories

Resources