Else is not executing ever - javascript

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.

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

if contact number is both empty and does not have 11 digits

id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link

Checking if integer JavaScript forms

I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}

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) {

Javascript and HTML form validation checks

i am trying to learn html and javascript. I have created an html form and am using javascript to validate the fields. I have a isNaN check for the age field, a regex check for emial and a presence check for all fields. I am currently outputting the form to the address bar but this does not work as i am getting errors.
<title> </title>
<script type="text/javascript">
function validate()
{
var errors = 0;
if (isNumeric(document.getElementById("age").value) == false)
{
errors++;
}
if (emailCheck(document.getElementById("email").value) == false)
{
errors++;
}
var inputBoxes = document.getElementsByTagName('input');
for(var i= 0; i < inputBoxes.length; i++)
{
if(inputBoxes[i].type != 'text') continue;
if(presenceCheck(inputBoxes[i].value) == false)
{
errors++;
}
}
console.log(errors);
if(errors == 0)
{
window.location.assign("output.html#" + "%%" + "name" + "%%" +
document.getElementById("name").value + "%%" + "email" + "%%" +
document.getElementById("email").value + "%%" + "age" + "%%" +
document.getElementById("age").value + "%%" + "comments" + "%%" +
document.getElementById("comments").value);
}
}
function isNumeric(number)
{
return !isNaN(number) && number != null && number != "";
}
function emailCheck(email)
{
var emailRegex = /\s+#\s+.\s+/;
return emailRegex.test(email);
}
function presenceCheck(data)
{
var regex = /\s+/;
return regex.test(data);
}
</script>
Below is the form which is just incased in body tags at the moment
<form id="frmA" name="frmA">
<label name="frmName">Name:</label><br />
<input form="frmA" type="text" name="frmName" id="name"/><br />
<label name="frmEmail">E-Mail:</label><br />
<input form="frmA" type="text" name="frmEmail" id="email"/><br />
<label name="age">Age:</label><br />
<input form="frmA" name="frmAge" id="age"/><br />
<label name="frmComments">Comments:</label><br />
<textarea form="frmA" cols="50" rows="10" id="comments"></textarea><br />
</form>
<button onClick="validate();">Submit</button>
i know that the checks work when no data is present however when i input data in the form and hit submit i am still faced with 4 errors. (there are 5 errors with no data: 3x presence checks, 1 for the regex and one for the isNaN)
My question therefore is why am i still getting errors and why do i get no output.
Any help would be greatly appreciated.
Extra: i would also like the input fields to change colour when there is an error.
Your regexes are wrong. You have /\s+#\s+.\s+/ and it should be /\w+#\w+\.\w+/. You didn't escape the dot and \s matches whitespace, not strings. \w matches word. For a proper email regex you would need much more than that but for your simple case to work this will suffice. The second regex should be /\w+/.

Categories