I want to print out a series of error messages on my html page based on what the user enters such as password, user name, address etc., which the information failed to validate.
My code looks like this:
function validate(){
var x,y,z;
x = document.getElementById("name").value;
if (x.length<6){
text="user name too short";
} else {
text="validated";
}
document.getElementById("aka").innerHTML = text;
}
Now I can only validate one input. In this case the input with id "name".
I want to validate all the inputs like password also in this function.
How could I implement that in the function?
I tried adding more if statement followed by another document.getElementById("aka").innerHTML = text, but didnt work and the first didn't print out.
Create a variable and put all the error messages there. Once you have finished, put the value of that variable in the innerHTML of the element you want.
function validate(){
var x, errors = "";
x = document.getElementById("name").value;
if (x.length<6){
errors += "user name too short<br />";
}
x = document.getElementById("password").value;
if (x.length<6){
errors += "password too short<br />";
}
document.getElementById("aka").innerHTML = errors;
}
You can either store all messages inside text variable
var text = "";
if (x.length<6){
text+="user name too short";
}
if(y.lenght<6) {
text+= 'pwd too short';
}
document.getElementById("aka").innerHTML = text;
Other option would be using DOM functions as follows:
document.appendChild(document.createTextNode(text));
var text ="";
text += "user name too short";
text += "<br/>pwd too short";
document.getElementById('out1').innerHTML=text;
document.getElementById('out2').appendChild(document.createTextNode('user name too short'));
document.getElementById('out2').appendChild(document.createTextNode('pwd too short'));
<div id="out1"></div>
<div id="out2"></div>
Related
I'm trying to use this to create a message that states "Please enter a number" when you hit submit on a form and there's no number in the input for "If you would like to state a specific amount type it in the box below". It's doing absolutely nothing, so I don't know what's going on. I'm still in school and this is my first class with JavaScript so I would appreciate any help you can give.
Here is the JavaScript portion:
```
// test page form exception code - Chapter 4
function verifyFormCompleteness() {
var specificAmountBox = document.getElementById("specificamount");
var completeEntry = true;
var messageElement = document.getElementById("message");
var messageHeadElement = document.getElementById("messageHead");
var validity = true;
var messageText = "";
try {
if (specificAmountBox.value == "" || specificAmountBox.value == null){
window.alert = "Please enter a number in the specific amount box";
}
}
catch(message) {
validity = false;
messageText = message;
specificAmountBox.value = ""; // removes bad entry from input box
}
finally {
completeEntry
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = "";
alert("This is happening in the finally block");
}
if (validity = true) {
return submit;
}
}
```
Here is the HTML portion:
```If you would like to state a specific amount type it in the box below:<br>
<input type="number" id="specificamount" name="specificamount">
<h1 id="messageHead"></h1>
<p id="message"></p>
<br>
<br>
```
Im trying to make an option, for the user to create a list of owned records. However i ran into the following problem:
When the user tries to create a list with no name, an empty/invisible element is added to the list. I want the code, to ask the user to enter a name if he leaves the prompt blank.
When elements are added, i want them to be separate and different elements. Now they are shown and displayed as one.
I hope some of you guys can help me overcome this problem. Please ask if anything seems unclear.
My present code is presented below:
function myFunction1() {
var txt;
var person = prompt("Please enter the name of your record list:");
if (person == null || person == "") {
txt = "";
} else {
txt = person + "<br>";
}
document.getElementById("myRecords").innerHTML += txt;
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
When using prompt, it's best to use a while loop to make sure that input is entered. This will continue cycling the message until the user enters sufficient information. When a user hits cancel a null value is returned. Within the while loop we check if person is null, and if that is the case we immediately return.
To add separate elements you can use document.createElement and then append that element to your selected parent through the use of the appendChild method.
In the below code I took the liberty of converting your myRecords div into a ul or unordered list tag. When names are entered they are added as li ( list item ) children to this tag.
function myFunction1() {
var person, ul = document.getElementById("myRecords"), li = document.createElement("li");
while (!person) {
person = prompt("Please enter the name of your record list:");
if (person == null) return;
}
li.textContent = person;
ul.appendChild(li);
}
myFunction1();
myFunction1();
<ul id="myRecords"></ul>
If you don't want to use a list, you can simply update the markup and change what you are appending. In the below myRecords is an a tag. We append a div with the appropriate text to this anchor tag as we did in the above.
function myFunction1() {
var person, a = document.getElementById("myRecords"), div = document.createElement("div");
while (!person) {
person = prompt("Please enter the name of your record list:");
if (person == null) return;
}
div.textContent = person;
a.appendChild(div);
}
myFunction1();
<a id="myRecords" href="#"></a>
You should use something like an (un)ordered list (<ol>, <ul>) and then append list item (<li>) containing the name in an <a> tag if need be. If you want to append an empty item when a name isn't entered, you don't have to use an if statement.
const getRecordList = () => document.getElementById('recordList');
const getCreateButton = () => document.getElementById('create');
function promptInput(value = '') {
const message = 'Please enter the name of your record list:';
let name = '';
while (name === '') {
name = prompt(message, value);
}
return name;
}
function createListItem(name) {
const listItem = document.createElement('li');
listItem.innerHTML = `<a onclick="updateRecord(this)">${name}</a>`;
return listItem;
}
function createRecord() {
const name = promptInput();
if (!name) return;
getRecordList().appendChild(createListItem(name || ''));
}
function updateRecord(li) {
li.innerHTML = promptInput(li.innerHTML);
}
<h2>Record List</h2>
<ol id="recordList"></ol><hr>
<button id="create" onclick="createRecord()">Create</button>
you need to change your JS to the following:
function myFunction1() {
var txt;
var person = prompt("Please enter the name of your record list:");
if (person == "") {
alert('Please enter a name');
return;
} else if(person == null){
return;
} else {
txt = person;
}
var span = document.createElement('span');
span.setAttribute('class', 'myElement');
span.innerHTML = txt;
document.getElementById("myRecords").appendChild(span);
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
With createElement a new element is created, to add a class you can use setAttribute and then you append it as a child to your myRecords element via appendChild.
function myFunction1() {
let person = prompt("Please enter the name of your record list:");
if (person) {
let div = document.createElement('div');
div.innerText=person;
document.getElementById("myRecords").appendChild(div);
}else{
alert('Please enter a name');
}
}
<a id="myRecords"></a>
<a id="create" onclick="myFunction1()">Create RecordList</a>
You can createElement and appendChild to add desired elements.
Without knowing exactly what you're trying to accomplish, this is the solution I came up with for you:
function myFunction(prompt_text) {
var txt;
var list;
var person;
if (prompt_text != '' && prompt_text != undefined) {
person = prompt(prompt_text);
} else {
person = prompt("Please enter the name of your record list:");
}
if (person == null || person == "") {
txt = "";
} else {
txt = '<li>' + person + "</li>";
}
if (txt != '') {
document.getElementById("myRecords").innerHTML += txt;
} else if(person != null){
myFunction("Names cannot be blank, please enter the name of your record list:");
} else {
return;
}
}
<ul id="myRecords"></ul>
<a id="create" onclick="myFunction()">Create RecordList</a>
I've modified the container that you're putting the data into to be an unordered list <ul></ul> to better facilitate having multiple entries in it, and auto-appended the <li></li> DOM so that the list does all of the work for you.
I've also changed the function to accept prompt_text as a parameter, so you can recursively call the function if they don't enter text.
EDIT: updated the code to understand the null returned when a user clicks the cancel button, which removes the error that was created by the code I originally posted.
The final change is the recursive function call I mentioned above. If the txt variable is empty, the function calls itself with new prompt_text allowing you to let the user know WHY they didn't do it right, as well as giving them another opportunity to correct that.
I am trying to check an HTML input form to see if it contains an # symbol.
HTML:
<input id="emailCheck" type="text" name="uid" />
<input type="button" value="Continue" onClick="continuePlease()" />
<br>
<p id="invalidEmail"></p>
Javascript:
var at = document.getElementById("emailCheck").value.indexOf("#");
function continuePlease() {
if (at == -1) {
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
} else {
changeData();
}
}
function changeData() {
document.getElementById("title").innerHTML = "<font color=#33FF00> Information Confirmed </font>";
document.getElementById("lock").innerHTML = "<font color=red>This Account is now locked.</font>";
document.getElementById("time").innerHTML = "<font color=white> You will have 30 minutes to send the provided wallet address the correct amount of Bitcoin or the account will unlock again. </font>";
document.getElementById("daemon").innerHTML = "<font color=white> Our Bit-Daemon is watching the address 24/7, once a payment is made, the contents of the account will be sent to your Email. Thanks, Paypal Trader.</font>";
document.getElementById("pig").innerHTML = "";
document.getElementById("cow").innerHTML = "";
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
}
What's happening is that when it performs the function continuePlease() it does both the code in the IF and in the ELSE.
It should do one or the other, not both.
I think I need a better way to check for the # symbol.
move at assignment as the first line of the continuePlease. I don t think it is doing both it is always doing the else block and check the last line of the else block it is same with if block.
You can use this handy function to test that:
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
You can pass in the email using this:
var email = document.getElementById("email").value;
This function will return either true or false depending on the email string you'll provide.
Do it this way. It should work.
function continuePlease() {
var at = document.getElementById("emailCheck").value.indexOf("#");
if (at == -1) {
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
} else {
changeData();
}
}
Is it possible to check the form field values dynamically with javascript only.
For example if I have form field for username and when the user enters their chosen username it checks whether this username is available and pops up an alert box or shows a message on the screen based on the result.
all of this is done without clicking any button. and the data is stored in an array.
Thanks in advance. Im trying to achieve this only by using javascript.
var username = document.getElementById('username');
var goBtn = document.getElementById('check');
var output = document.getElementById('output');
var usernames = ['bob', 'sally', 'alice', 'roy', 'kate', 'phil'];
function showResult() {
output.innerHTML = usernames.join(', ');
}
function checkUsername() {
if (usernames.indexOf(username.value) < 0) {
usernames.push(username.value);
username.value = '';
} else {
alert('That username is already taken. Try again.');
}
showResult();
}
goBtn.onclick = checkUsername;
showResult();
<label for="username">Name:</label>
<input id="username" name="username" placeholder="username">
<button id="check">Go</button>
<div id="output"></div>
may be this is what you want
// usernameArray contains all the usernames that can't be used
var usernameArray = ['username1','username2','username3'];
// i'm using .kyup() method to get a dynamic result so whenever the user type a letter or
// something else (just one caracter) we check that value against our usernameArray list
$('#username').keyup(function(){
var value = $(this).val();
if(usernameArray.indexOf(value) >= 0){
alert('sorry, try another username ');
}else{
alert('good, you can use this username it is available');
}
});
I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}