I am inputting age in a form in HTML which has a age field. I want to take input in age as a number only so I have defined age field as number type. I am putting a check in the javascript code if(typeof name === "string" && isNaN("age") ==="false").I observed during debugging that typeof age is string.I don't know how is it getting converted to string type automatically.
I have attached my HTML and javascript codes.Plz help...
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.11.3.min.js"></script>
</head>
<script src="form_js.js"></script>
<body>
<form id="myForm">
First Name:
<input type="text" id="field1">
<br> Last Name:
<input type="text" id="field2">
<br> Age:
<input type="number" id="field3">
<br>
<br> Gender:
<select id="field5">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
<p>
<input type="button" onclick="insRow('Table1')" value="Insert">
</p>
<table id="Table1" style="width:100%">
<tr>
<td>Name</td>
<td>Age</td>
<td>Gender</td>
</tr>
</table>
</body>
</html>
Javascript:
var count = 0;
function insRow() {
count += 1;
var x, y, z, a, w;
var w = document.getElementById('Table1').insertRow(count);
var name = $("#field1").val() + " " + $("#field2").val();
//var age = $('#field3').val();
//var age = $('#myForm :field3');
//var Email = $("#field4").val();
var gender = $("#field5").val();
//w = document.getElementById('Table1').insertRow(count);
//var first_name = document.getElementById("field1").value;
//var last_name = document.getElementById("field2").value;
var age = document.getElementById("field3").value;
//var gender = document.getElementById("field5").value;
if (typeof name === "string") //&& isNaN("age") ==="false")
{
x = w.insertCell(0);
y = w.insertCell(1);
a = w.insertCell(2);
x.innerHTML = name //" " + last_name;
y.innerHTML = age;
a.innerHTML = gender;
document.getElementById("myForm").reset();
} else alert("Invalid Data");
//var rows += "<tr><td>" + name + "</td><td>" + age + "</td><td>" + Email + "</td><td>" + Gender +"</td></tr>";
//$("#Table1 tbody").append(rows);
}
When you get any value from HTML it is by default string. To convert it to Number use parseInt or parseFloat according to your requirement.
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
var age = parseInt(document.getElementById("field3").value, 10);
OR
The parseFloat() function parses a string argument and returns a floating point number.
var age = parseFloat(document.getElementById("field3").value);
When you are checking for NaN, use variable age without quotes. And for strict comparison false should be without quotes.
isNaN("age") ==="false")
Should be
isNaN(age) === false) // Without quotes for age and false
Note that document.getElementById(someId).value will always return you string type, if any. There are several methods to parse like parseInt(), parseFloat() and also +()
var str = document.getElementById('num').value;
var num = +(str);
alert("Type of " + num + " is " + (typeof num));
var price = +(document.getElementById('price').value);
alert("Type of " + price + " is " + (typeof price));
<input type="text" id="num" value="56" />
<input type="text" id="price" value="9.13" />
Related
I'm working on a tool for my job to auto generate task comments to streamline agent workflow. I'm trying to use a selector to differentiate between ticket types and generate a comment string accordingly.
The problem I'm running into is I can't seem to get the page to tell the the selector has changed, and it will only give the if condition and ignore the else.
I'm certain I'm missing something simple but can't seem to figure it out.
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth() + 1) + '-' + today.getDate() + '-' + today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date + ' ' + time;
setInterval(1000);
if (tick = 1) {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:" + ' ' + dateTime + ' ' + txt1.value + ' ' + "# attempt, contacted CX #";
}
}
btn1.addEventListener('click', fun1);
</script>
</html>
A few issues to address:
your comparison needs a double equal - ==
tick itself is just an html element, you can't compare it to a number, you need to get the currently selected index
you use id=ticket twice, so when you get the html element by that ID, it grabs the first one, which is a label.
I believe this code should fix your issues
<!DOCTYPE html>
<html>
<body>
Select Ticket Type:
<label name="ticket" id="ticket-label"></label>
<select name="ticket" id="ticket">
<option value="1">SMB</option>
<option value="2">Complete</option>
</select>
<input type="text" id="ticketgen" placeholder="EnterTicket number" maxlength="8">
<input type="button" id="tickgen" value="Generate">
<p id="output"></p>
</body>
<script>
const txt1 = document.getElementById('ticketgen');
const btn1 = document.getElementById('tickgen');
const out1 = document.getElementById('output');
function fun1() {
var tick = document.getElementById('ticket');
var today = new Date();
var date = (today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
var time = today.getHours() + ':' + today.getMinutes();
var dateTime = date+' '+time;
setInterval(1000);
if (tick.selectedIndex == 0){
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"SMB Correspondence";
} else {
out1.innerHTML = "Correspondence:"+' '+dateTime+' '+txt1.value+' '+"# attempt, contacted CX #";
}
}
btn1.addEventListener('click',fun1);
</script>
</html>
Your value for tick would be a string and you are checking it as integer. Try by changing it to, if (tick == "1").
Label attribute id is same as of select attribute. Try by changing the label id. All HTML attributes must have unique id / name.
In Plain JavaScript, you get the selected option value as follow
var e = document.getElementById("tick");
var value = e.options[e.selectedIndex].value;
Hope this helps! :)
I'm stuck on trying to get the email outputted instead of numbers related to the amount of words inputed
var output2 = "Email: " + at; is counting the amount of letters that was inputed.
I'm trying to figure out how its counting the amount of letters and why is it not outputting the email instead
Demo in Stack Snippets
function myFunction() {
var uname = document.getElementById("uname").value;
var age = document.getElementById("age").value;
var at = document.getElementById("email").value.indexOf("#");
submitOk = "true";
if (uname.length > 16) {
alert("Characters have exceeded specified amount");
submitOk = "false";
}
if (age < 13 || age > 19) {
alert("Numbers must be between 13 and 19");
submitOk = "false";
}
if (at == -1) {
alert("not a valid E-mail");
}
if (submitOk == "false") {}
if (submitOk == "true") {}
var output = "Name: " + uname;
var output1 = "Age: " + age;
var output2 = "Email: " + at;
document.getElementById("output").innerHTML = output;
document.getElementById("output1").innerHTML = output1;
document.getElementById("output2").innerHTML = output2;
}
<form onsubmit="return myFunction()">
Name : <br><input type="text" id="uname" size="30" placeholder="Maximum of 16 Characters"><br> Age : <br><input type="number" id="age" size="30" placeholder="From 13 to 19 only"><br> E-mail : <br><input type="text" id="email" size="30" placeholder="Examplename#mail.com"><br>
<br>
<input type="submit" onclick="myFunction();return false" value="Submit">
</form>
<table class="center">
<tr>
<td>
<div id="output"></div>
</td>
</tr>
<tr>
<td>
<div id="output1"></div>
</td>
</tr>
<tr>
<td>
<div id="output2"></div>
</td>
</tr>
</table>
It looks like at is being used to verify that the email has an # symbol, not neccessarily return the pure value as seen here where it's calculated:
var at = document.getElementById("email").value.indexOf("#");
indexOf("#") will return the position of the first at symbol if found, or -1 if not found.
If you just want the email address, you can break into two statements:
var email = document.getElementById("email").value;
var at = email.indexOf("#");
I want to implement a simple measurement convergence program but the convert button doesn't really work and it's not even changing the value of the answer box. What should I do now?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Measurement Conversion</title>
</head>
<body>
<h1 align="center">
Measurement Conversion
</h1>
<div align="center"><center><table border="0">
<tr>
<input type="text" name="what" size="15">
</tr>
<tr>
<td align="center">From:<br>
<select name="unit" size="9" onChange="convert()">
<option name="meter">meter</option>
<option name="mile">mile</option>
<option name="yard">yard</option>
</select></td>
</tr>
<tr>
<input type="button" onclick="convert()">Convert it now!</button></td>
</tr>
<tr>
<input type="text" name="answer" title="answer" size="70" value="None"></td>
</tr>
</table>
</center></div>
<script>
function convert() {
// var FromVal, ToVal, FromName, ToName, v1;
v1 = document.getElementByName("what").value;
document.getElementByName("answer").value = v1;
var unit = document.getElementByName("unit").name;
if (unit == "yard") {
var meter = "meter= " + 0.9144*document.getElementByName("what").value;
var mile = "mile = " + 0.000568181818*document.getElementByName("what").value;
document.getElementById("answer").value = meter + mile;
}
if (unit == "meter") {
var yard = "yard = " + 1.0936133*document.getElementByName("what").value;
var mile = "mile = " + 0.000621371192*document.getElementByName("what").value;
// var meter = "m = " + 0.9144*document.getElementByName("what").value
document.getElementById("answer").value = yard + mile;
}
if (unit == "mile") {
var meter = "meter = " + 1609.344*document.getElementByName("what").value
var yard = "yard = " + 1760*document.getElementByName("what").value
document.getElementById("answer").value = meter + yard;
}
}
</script>
</body>
</html>
It seems there is something wrong with my convert() function.
How about using the most basic troubleshooting methods first and then coming here and asking specific questions to help get you through the problem.
Add an alert("button Clicked");
to the first line of your function and see if you get the alert. If you do, move the alert to after your variable statements and change it to
alert("what = " + what + ", "answer = " + answer + ", unit = " + unit);
and make sure you are getting what you expect for your variable assignments. Continue like this and when you get to a specific problem that your can't seem to remedy yourself, come back.
there's no getElementByName.
add attribute id on your input then use getElementById instead.
I am making a contact list in which I will be saving the contacts, but when I save one or more contact and refresh the page it doesn't save. I tried to put it in the local storage but it doesn't work. Can anyone help me with this?
HTML:
<br><br>
Name: <input id = "name" name = "name" type = "text">
<br><br>
Gender: <input name = "gender" type = "radio" value = "Male"> Male
<input name = "gender" type = "radio" value = "Female"> Female
<br><br>
Age: <input id = "age" name = "age" type = "text">
<br><br>
Number: <input id = "number" name = "number" type = "text">
<br><br>
Contact Type: <select id = "Contact_Type" name = "Contact_Type">
<option>none</option>
<option>Friend</option>
<option>Business</option>
<option>Educational</option>
</select>
<br><br>
Address: <input id = "Address" name = "Address" type = "text">
<br><br>
Post Code: <input id = "Post_Code" name = "Post_Code" type = "text">
<br><br>
Marital Status: <select id = "Marital_Status" name = "Marital_Status">
<option>none</option>
<option>Single</option>
<option>in relationship</option>
<option>Engaged</option>
<option>Married</option>
</select>
<br><br>
<input type = "button" value = " Reset " onclick = "ResetForm()">
<input type = "button" value = " Add " onclick = "AddData(), saveList()">
<input type = "button" value = "Remove contact" onclick = "Remove()">
</form>
JS:
function AddData() {
var x = document.getElementById("age").value;
var y = document.getElementById("name").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = document.getElementById("name").value;
var gender = document.querySelector('input[name="gender"]:checked');
gender = gender ? gender.value : '';
var age = document.getElementById("age").value;
var number = document.getElementById("number").value;
var Contact_Type = document.getElementById("Contact_Type").value;
var Address = document.getElementById("Address").value;
var Post_Code = document.getElementById("Post_Code").value;
var Marital_Status = document.getElementById("Marital_Status").value;
rows += "<td>" + name + "</td><td>" + gender + "</td><td>" + age + "</td><td>" + number +"</td><td>" + Contact_Type + "</td><td>"+ Address + "</td><td>" + Post_Code+ "</td><td>" + Marital_Status +" </td>";
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
saveList();
}
}
var saveList = function () {
"use strict";
var appts = JSON.stringify(contact);
if (appts !== "") {
localStorage.contact = appts;
} else {
window.alert("Could not save appointments at this time");
}
};
function ResetForm() {
document.getElementById("contact").reset();
}
Your code has several errors.
HTML table is not found.
You're invoking saveList function two times (in button event and at the end of AddData function).
You aren't passing the contact parameter to the saveList function.
You should read Clean Code Book for improve your coding =).
The code should be the next (you could check the key "contact" in your browser).
HTML:
<br>
<br> Name:
<input id="name" name="name" type="text">
<br>
<br> Gender:
<input name="gender" type="radio" value="Male"> Male
<input name="gender" type="radio" value="Female"> Female
<br>
<br> Age:
<input id="age" name="age" type="text">
<br>
<br> Number:
<input id="number" name="number" type="text">
<br>
<br> Contact Type:
<select id="Contact_Type" name="Contact_Type">
<option>none</option>
<option>Friend</option>
<option>Business</option>
<option>Educational</option>
</select>
<br>
<br> Address:
<input id="Address" name="Address" type="text">
<br>
<br> Post Code:
<input id="Post_Code" name="Post_Code" type="text">
<br>
<br> Marital Status:
<select id="Marital_Status" name="Marital_Status">
<option>none</option>
<option>Single</option>
<option>in relationship</option>
<option>Engaged</option>
<option>Married</option>
</select>
<br>
<br>
<table id="list">
<tbody>
</tbody>
</table>
<input type="button" value=" Reset " onclick="ResetForm()">
<input type="button" value=" Add " onclick="AddData()">
<input type="button" value="Remove contact" onclick="Remove()">
JS:
<script>
function AddData() {
var x = document.getElementById("age").value;
var y = document.getElementById("name").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = document.getElementById("name").value;
var gender = document.querySelector('input[name="gender"]:checked');
gender = gender ? gender.value : '';
var age = document.getElementById("age").value;
var number = document.getElementById("number").value;
var Contact_Type = document.getElementById("Contact_Type").value;
var Address = document.getElementById("Address").value;
var Post_Code = document.getElementById("Post_Code").value;
var Marital_Status = document.getElementById("Marital_Status").value;
rows += "<td>" + name + "</td><td>" + gender + "</td><td>" + age + "</td><td>" + number + "</td><td>" + Contact_Type + "</td><td>" + Address + "</td><td>" + Post_Code + "</td><td>" + Marital_Status + " </td>";
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
contact = {name:name, gender:gender, age:age, number:number, type:Contact_Type, address: Address, zip: Post_Code, marital: Marital_Status};
saveList(contact);
}
}
var saveList = function(contact) {
"use strict";
var appts = JSON.stringify(contact);
if (appts !== "") {
localStorage.contact = appts;
} else {
window.alert("Could not save appointments at this time");
}
};
function ResetForm() {
document.getElementById("contact").reset();
}
</script>
Now you should program the function to read the localStorage.
I'm trying to learn Javascript and I feel like I have a decent grasp on the fundamentals but I am having problems making it do things that i want .. for example.. I am trying to create a simple form in html that calculates the sum of 2 numbers.. here is my html and javascript:
<head>
<script type="text/javascript">
function adder(a,b) {
var a = document.getElementById('firstNum').value;
var b = document.getElementById('secondNum').value;
var numbers = new Array(a,b);
var sum = 0;
for (i=0; i < numbers.length; i++) {
sum += parseInt(numbers[i]);
}
//this part i need help with
document.getElementById('answer').write("First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
</script>
</head>
<body>
<form id="additionForm">
A + B = C : <input type="text" id="firstNum" placeholder="A">
+ <input type="text" id="secondNum" placeholder="B">
<input type="button" id="addBtn" value="Add" onClick="adder();">
= <input type="text" id="answer" placeholder="C">
</form>
</body>
My problem is that i don't know how to get the javascript to overwrite the value attribute for my form input id=answer .. or if i'm supposed to be using Jquery instead .. thanks in advance.
function adder() {
var a = parseInt( document.getElementById('firstNum').value, 10);
var b = parseInt( document.getElementById('secondNum').value, 10);
var sum = a + b;
//this part i need help with
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum).value; //this part i need help with
}
If you want to modify an input field in javascript, you can simply set the value attribute:
document.getElementById('answer').value = "First Number: " + a + " plus Second Number: " + b + " is " + sum;