Use user info without prompt or confirm? - javascript

All I want to do is be able to do is have users submit info and be able to use it - without using prompt.
I would like to have them be able to input and have a different box to be able to give them info based on there info. I.E. 81 is a great number.
var c = prompt("pick a number")
if(c>100){
console.log("110 is to high of a number")
}
This is what I have. I'm used to JavaScript editors and using console.log. I'm looking for a way to do that based on info I receive and be able to give feed back in a different <div> or whatever. Can anyone help?
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="submit" value="submit" />
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert(textbox.value + '\n' + location.value);
}
<input type="button" value="submit" onclick="showConfirmationDialog();" />

If you're using jQuery, you can use a click handler that looks like this:
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Here's a fiddle that shows the above code in action.

Related

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"/>

Converting HTML form input into Javascript variables and comparing values

I am trying to compare the birth dates of two people. Person 1 and Person 2 input their names and dates of birth in an HTML form, and I want to use Javascript to compare the two dates and print out which person is older on the HTML page. However, I'm not sure how to submit the form and compare the dates. Here is what I have so far for the HTML:
<form id="form1">
Full name of first person: <input type="text" name="name1"><br>
Birthday: <input type="date" date="date1"><br>
<br>
Full name of second person: <input type="text" name="name2"><br>
Birthday: <input type="date" date="date2"><br>
</form>
And the Javascript:
var name1 = document.getElementsByName("name1");
var name2 = document.getElementsByName("name2");
var date1 = document.getElementsByName("date1");
var date2 = document.getElementsByName("date2");
How do I submit the variables in HTML and then have Javascript compare the two dates?
You forgot two things:
A submit button.
A submit handler.
I guess this solves your question.
window.onload = function () {
document.getElementById("form1").onsubmit = function () {
var name1 = document.getElementById("name1");
var name2 = document.getElementById("name2");
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
if ((new Date(date1.value)).getTime() < (new Date(date2.value)).getTime()){
console.log(name1.value + " is greater than " + name2.value)}
else if ((new Date(date1.value)).getTime() > (new Date(date2.value)).getTime()){
console.log(name2.value + " is greater than " + name1.value)}
else{
console.log(name2.value + " and " + name1.value + " are of same age.")};
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
<input type="submit" value="Check" />
</form>
You need to add an action to the form and a submit button. Then you can add an onsubmit call from your button to invoke a simple string comparison function to see which number is greater
Basic form data access demo
var compare = function () {
var form = document.getElementById("form1");
var output = document.getElementById("demo");
output.innerHTML = "";
for(var i = 0; i< form.length; i++){
output.innerHTML = output.innerHTML +" "+ form.elements[i].value;
};
};
<form id="form1">
Full name of first person: <input type="text" id="name1"><br>
Birthday: <input type="date" id="date1"><br>
<br>
Full name of second person: <input type="text" id="name2"><br>
Birthday: <input type="date" id="date2"><br>
</form>
<input type="button" name="submit" value="Compare " onclick="compare()" />
<p id="demo"></p>
Well, let's go step by step on this
1. How to submit a form
In HTML you have 2 ways of submitting a form:
Through an <input> tag with the type="submit" attribute (resulting in <input type="submit" />
Trough a <button> tag with the type="submit" attribute (resulting in <button type="submit">...content...</button>
Now when these buttons get clicked, they will trigger the <form>'s submit event.
2. How to subscribe to a form's submit event
As when submitting a form, there're (without any external libraries) 2 ways of subscribing to a form's submit event:
Directly setting a property on the form: formvar.onsubmit = function() { /* ... do stuff ... */ } (not really recommended as other plugins/scripts might overwrite this)
Adding an event listener: formvar.addEventListener("submit", function() { /* ... do stuff ... */ } (better than directly setting a property as this won't be removed when another script subscribes to the same event)
3. Comparing dates
Well, first you'd have to transform the dates from the string value you got from the textbox to a proper Date type:
date1 = Date.parse(date1.value);
date2 = Date.parse(date2.value);
And then with a simple arithmetic operator you can find out which one of them is the oldest:
var difference = date2 - date1;
if(difference > 0)
{
// Second person is the oldest
}
else if (difference < 0)
{
// First person is the oldest
}
else
{
// They are the same age
}
You don't need to submit the form to check the difference. A simple onclick function or click event listener will do.
You need to check if they are older, younger, or the same age. Try it below. You code wasn't working because you didn't have a name property for your dates. I switched them to use ids.
document.getElementById("theButton").addEventListener('click', checkOldest);
function checkOldest() {
var name1Value = document.getElementById("name1").value,
name2Value = document.getElementById("name2").value,
date1Value = document.getElementById("date1").value,
date2Value = document.getElementById("date2").value,
result = document.getElementById("result");
// make sure you have input for both birthdates and names
if (name1Value && name2Value && date1Value && date2Value) {
var dateOneComparedToTwo = new Date(date1Value) - new Date(date2Value);
if (dateOneComparedToTwo < 0) {
result.innerText = name1Value + ' is older than ' + name2Value + '!';
} else if (dateOneComparedToTwo > 0) {
result.innerText = name1Value + ' is younger than ' + name2Value + '!';
} else {
result.innerText = name1Value + ' and ' + name2Value + ' are the same age!';
}
} else {
result.innerText = "You need to fill out the form completely!";
}
}
<form id="form1">
Full name of first person: <input type="text" id="name1" name="name1"><br>
Birthday: <input type="date" id="date1" name="date1"><br>
<br>
Full name of second person: <input type="text" id="name2" name="name2"><br>
Birthday: <input type="date" id="date2" name="date2"><br>
<button id="theButton">Who's oldest?</button>
</form>
<p id="result">
Fill out the form please!
</p>

Form validation woes

New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.

Simple Age Verification in javascript

I'm a total Js noob and i'm trying to make a simple script to take values from two input tags and based on their value change a p tag. I'm probably just not using proper syntax but I can't find an answer online to how to do this.
The script is supposed to be like age verification for an r-rated movie. The first input is age and the second is whether or not the customer has an adult with them for if they are underage.
<pre>
<!DOCTYPE html>
<html>
<input type="text" id="age" value="your age">
<input type="text" id="adult" value="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
<script>
var age = document.getElementById("age").innerHTML;
var adult = document.getElementById("adult").innerHTML;
var result = document.getElementById("answer").innerHTML;
var oldEnough = false;
function checkAge(){
if(age.value >= 18){
oldEnough = true;
}
else{
oldEnough = false;
}
if(oldEnough == false){
if(adult.value == "y"){
result = "You are not old enough, but have an adult with you.";
}
else{
result = "You are not old enough and are unaccompanied."
}
}
else{
result = "You are old enough."
}
}
</script>
</html>
</pre>
Don't call .innerHTML on the input elements. Just set the variables to point to the elements.
When assigning the result, you need to use result.innerHTML at the time of the assignment. Assigning .innerHTML to the variable just copies the current contents of the element as a string, it doesn't make result a reference to the innerHTML property.
You should call parseInt on age, because .value is a string.
function checkAge() {
var age = document.getElementById("age");
var adult = document.getElementById("adult");
var oldEnough = false;
var result = document.getElementById("answer")
if (parseInt(age.value, 10) >= 18) {
oldEnough = true;
} else {
oldEnough = false;
}
if (oldEnough == false) {
if (adult.value == "y") {
result.innerHTML = "You are not old enough, but have an adult with you.";
} else {
result.innerHTML = "You are not old enough and are unaccompanied."
}
} else {
result.innerHTML = "You are old enough."
}
}
<input type="text" id="age" placeholder="your age">
<input type="text" id="adult" placeholder="(y or n)">
<input type="button" onclick="checkAge()" value="submit">
<p id="answer"></p>
The input elements can be more easily accessed if they are put in a form, and the logic can be simpler. Also, make sure you use appropriate elements and attributes, e.g. don't use value as a kind of placeholder, it should be a suitable default value (if there is one).
And don't use placeholders instead of labels, they should only be used as a hint for the kind of content required, they don't replace labels.
function checkAge(button) {
var form = button.form;
var result = document.getElementById("answer");
result.innerHTML = form.age.value >= 18? 'You are old enough.' :
form.adult.checked? 'You are not old enough, but have an adult with you.' :
'You are not old enough and are unaccompanied.';
}
<form>
<label>Age: <input type="text" name="age"></label>
<label>Adult: <input type="checkbox" name="adult"></label>
<input type="button" onclick="checkAge(this)" value="Check age">
<p id="answer"></p>
</form>

To validate and connvert entered phone number in a form

I am working on an HTML form which has 4 fields as below
Name
Email
Phone Number
Message
The field for phone number should accept 10 digits. It change/accept of the format (xxx) xxx-xxxx when i click on the Message field.
I have written the function for javascript to do so but the number is not getting changed when i click on the message field. The code is below
It would be a great help if someone could help me out with this. Thanks in advance!
function PhoneValidation(phone) {
if (!(this.isNull)) {
var str = this.rawValue;
var regExp = /^\d{10}$/;
if (regExp.test(str)) {
this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(3, 3) + "-" + str.substr(6, 4);
} else {
regExp = /^[1-9]\d{2}\s\d{3}\s\d{4}$/;
if (regExp.test(str)) {
this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(4, 3) + "-" + str.substr(8, 4);
} else {
regExp = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
if (!(regExp.test(str))) {
xfa.host.messageBox("Please enter the telephone number in the format '(999) 999-9999'.");
this.rawValue = null;
xfa.host.setFocus(this);
}
}
}
}
}
And HTML below:
<form id="contact-form" class="contact-form" method="post" action="">
<div class="result"></div>
<input type="text" name="contact[name]" id="name" placeholder="Name *">
<input type="text" name="contact[email]" id="email" placeholder="E-mail *">
<input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)" ;>
<textarea cols="5" rows="5" name="contact[message]" id="message" placeholder="Message *"></textarea>
<input type="submit" class="btn-dark" value="SEND">
</form>
in your validate function this = window, or something else so I have no idea what will !this.isNull actually do.
You may change it to something like
function PhoneValidation(phone) {
if(phone.value) {
// set up the phone.value here
}
}
// bind the change event as you did.
<input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)";>
EDIT The code above is just the idea, please note that inside PhoneValidation in your case this = window. You have passed phone so try to use it, you can take the demo here http://jsfiddle.net/7qjz2/. As a summary
window.PhoneValidation = function(phone)
// cause I don't know where you put this js, so let bind it to window.
Next in side function, rawValue is undefined so use phone.value instead
If you can't pass the condition, set the html for your message div. by
document.getElementById("result").innerHTML = "Whatever you want"
That's all. Hope this help!
if (!(this.isNull)) {
Apparently, keep it short and simple like:
if (this) {

Categories