i wrote a program which converts lbs to kg, it works fine. how would i ask the user to enter the conversion. for example, i have the weight set at 0.4536, but if i wanted it to be whatever the user wants how do i do that? i know in reality it would not change, but i'm thinking about future programs - possibly currency conversions where the rates change and i want the user to enter it easily.
Javascript
function onlyNumber(fld) {
if(fld.value.match(/[^0-9.]/)) {
fld.value=fld.value.replace(/[^0-9.]/g,'');
}
}
function convertUnit(lbs, kilo) {
retValue = 0;
if (isNaN (kilo)) { alert ('Non-numeric value'); return 0; }
kilo = parseFloat (kilo);
var factor = 0.4536;
if (lbs == 'kg2lb') {
retValue = kilo/factor;
}
else if (lbs == 'lb2kg') {
retValue = kilo*factor;
}
return retValue;
}
HTML
<form>
<table>
<tr>
<td>LB<td>
<input type="text" name="lb" id="lb" onblur="this.form.kg.value=convertUnit('lb2kg',this.value);" onkeyup="onlyNumber(this);">
</tr>
<tr>
<td>KG<td>
<input type="text" name="kg" id="kg" onblur="this.form.lb.value=convertUnit('kg2lb',this.value);" onkeyup="onlyNumber(this);">
</tr>
</table>
</form>
Add another input field or prompt the user.
<form>
<table>
<tr>
<td>LB<td>
<input type="text" name="lb" id="lb" onblur="this.form.kg.value=convertUnit('lb2kg',this.value);" onkeyup="onlyNumber(this);">
</tr>
<tr>
<td>KG<td>
<input type="text" name="kg" id="kg" onblur="this.form.lb.value=convertUnit('kg2lb',this.value);" onkeyup="onlyNumber(this);">
</tr>
<tr>
<td>Ratio<td>
<input type="text" name="r" id="r" onkeyup="onlyNumber(this); window.ratio = this.value;">
</tr>
</table>
</form>
window.ratio = undefined;
function convertUnit(lbs, kilo) {
retValue = 0;
if (isNaN (kilo)) { alert ('Non-numeric value'); return 0; }
kilo = parseFloat (kilo);
if (lbs == 'kg2lb') {
retValue = kilo/window.ratio;
}
else if (lbs == 'lb2kg') {
retValue = kilo*window.ratio;
}
return retValue;
}
Or with a prompt
window.ratio = prompt("Which ratio to use ?"); // add validation
Related
I am trying to develop a simple piece of code.. I created a calculator to calculate Celcius/Kelvin/Fahrenheit based on HTML input. The code seems to be working. The correct answers appear but then dissapear in a split second, the browser seems to 'refresh'. Am i missing something?
Html code:
<html>
<body>
<form>
<label for="degrees">Degrees: </label>
<input type="text" name="degrees" id="degrees">
<label for="calc_type">Type: </label>
<select name="calc_type" id="calc_type">
<option value="celcius">Celcius</option>
<option value="kelvin">Kelvin</option>
<option value="fahrenheit">Fahrenheit</option>
</select>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
<table style="width: 100px">
<tr>
<th>Celcius: </th>
<th id="celsius_value">0</th>
<tr></tr>
<th>Fahrenheit: </th>
<th id="fahrenheit_value">0</th>
<tr></tr>
<th>Kelvin: </th>
<th id="kelvin_value">0</th>
</tr>
</table>
</body>
<script src="js/celcius_calulator.js"></script>
</html>
JS code:
function myFunction() {
var degrees = document.getElementById('degrees').value
var calc_type = document.getElementById('calc_type').value
if (calc_type === "celcius") {
cC(degrees);
} elseif (calc_type === "fahrenheit"); {
fC(degrees);
} elseif (calc_type === "kelvin"); {
kC(degrees)
}
}
function cC(degrees) {
celcius_value = degrees;
kelvin_value = degrees * 273.15;
fahrenheit_value = degrees * 1.8 + 32;
document.getElementById('celsius_value').innerHTML = degrees;
document.getElementById('fahrenheit_value').innerHTML = fahrenheit_value;
document.getElementById('kelvin_value').innerHTML = kelvin_value.toFixed(2);
}
function fC(degrees) {
celcius_value = Math.round(degrees - 32) / 18 * 10;
kelvin_value = degrees + 459.67 / 1.8;
fahrenheit_value = degrees;
document.getElementById('celsius_value').innerHTML = degrees;
document.getElementById('fahrenheit_value').innerHTML = fahrenheit_value;
document.getElementById('kelvin_value').innerHTML = kelvin_value.toFixed(2);
}
function kC(degrees) {
celcius_value = degrees - 273.15
fahrenheit_value = degrees * 1.8 - 459.67;
kelvin_value = degrees;
document.getElementById('celsius_value').innerHTML = degrees;
document.getElementById('fahrenheit_value').innerHTML = fahrenheit_value;
document.getElementById('kelvin_value').innerHTML = kelvin_value.toFixed(2);
}
The submit button will post the form-content to whatever you specified as the form's target through <form action="target-url">. As you didn't specify anything, it will simply post the forms content to the current page.
You will have to do something like
document.querySelector('form').addEventListener('submit', e => e.preventDefault())
to prevent the form from being submitted, which will then again prevent the page from reloading.
You can then also do your evaluation logic in the event listener so you don't end up with two event listeners (One for the submit button, one for the form submit event).
The simplest answer would be to pass an event as parameter in myFunction(event) and do event.preventDefault(). Just pass event as param the following ->
<input type="submit" value="Submit" onclick="myFunction(event)">
and in your js file do this ->
function myFunction(event) {
event.preventDefault();
var degrees = document.getElementById('degrees').value
var calc_type = document.getElementById('calc_type').value
if (calc_type === "celcius") {
cC(degrees);
} elseif (calc_type === "fahrenheit"); {
fC(degrees);
} elseif (calc_type === "kelvin"); {
kC(degrees)
}
You can make the below change in your code.
<input type="button" value="Submit" onclick="myFunction()">
Hope this solve your problem.
I created a function that checks if the username already exists in the data list, but alert shows every time even if the username isn't in duplicate data list.
<form onsubmit="return validation()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user"></td>
<datalist id="list">
<option value="Tilen">
<option value="Marko">
<option value="Teja">
<option value="Tisa">
<option value="Rok">
<option value="Luka">
<option value="Mojca">
</datalist>
</tr>
</table>
</form>
<script>
function validation(){
var user = document.getElementById("user");
if(user.value.length <= 20 && user.value.length >= 3){
}
else{
alert("Username has to be between 3-20 characters.")
}
//duplication data list
var user = document.getElementById("user");
if(user.value == list.value){
}
else{
alert("Username already exists.")
}
}
</script>
You can get all the options using querySelector, iterate over them and compare then with user.value. Also you need list="polje_imen" in the input element.
function validacija() {
let user = document.getElementById('user');
let listOptions = document.querySelectorAll("#list option");
if (user.value.length <= 20 && user.value.length >= 3) {} else {
alert("Username has to be between 3-20 characters.")
}
for (let i = 0; i < listOptions.length; i++) {
if (listOptions[i].value === user.value) {
alert('The name already exist')
}
}
return false;
}
<form onsubmit="return validacija()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user" list="list"></td>
<datalist id="list">
<option value="Tilen">
<option value="Marko">
<option value="Teja">
<option value="Tisa">
<option value="Rok">
<option value="Luka">
<option value="Mojca">
</datalist>
</tr>
</table>
</form>
Edit: If you do not want to show the datalist, just use javascript.
function validacija() {
let user = document.getElementById('user');
let listNames = ["Tilen","Marko","Teja","Tisa","Rok","Luka","Mojca"];
if (user.value.length <= 20 && user.value.length >= 3) {} else {
alert("Username has to be between 3-20 characters.")
}
for (let i = 0; i < listNames.length; i++) {
if (listNames[i] === user.value) {
alert('The name already exist')
}
}
return false;
}
<form onsubmit="return validacija()">
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="user" name="user"></td>
</tr>
</table>
</form>
Firstly, I don't think you're binding to the input on the datalist correctly. You can actually use the datalist as an autocomplete for the input if you simply change your input to look like this:
<input type="text" id="upor_ime" name="upor_ime" list="polje_imen">
If you have that in there, it becomes much more obvious if they choose a value that is not in the list or not from a visual perspective. Now when it comes to validating it in javascript, if you still want to take it that far, you're going to have to break out your list of possible names into an array so you can check to see if the string you're entering in the input exists in the array of strings. Because you're trying to compare an array of strings to a string, using the == operator in an if statement will not work. Here's a possible solution:
<form onsubmit="return validacija()">
<table>
<tr>
<td>Uporabniško ime:</td>
<td><input type="text" id="upor_ime" name="upor_ime" list="polje_imen"></td>
<datalist id="polje_imen"></datalist>
</tr>
</table>
</form>
<script>
var names = ["Tilen", "Marko", "Teja", "Tisa", "Rok", "Luka", "Mojca"];
var options = "";
for (let name of names) {
options += "<option value='" + name + "'>";
}
document.getElementById("polje_imen").innerHTML = options;
function validacija(){
var upor_ime = document.getElementById("upor_ime");
if(upor_ime.value.length > 20 || upor_ime.value.length < 3){
alert("Uporabniško ime mora imeti med 3-20 znakov.")
return;
}
//duplication data list
var polje_imen = document.getElementById("polje_imen");
if(names.includes(upor_ime.value)) {
alert("Uporabniško ime že obstaja.");
return;
} else{
// success
}
}
</script>
Here is a JSFiddle: http://jsfiddle.net/4f1hztr2/
Edit: I also changed around some of your if statement logic so that if the length of the item wasn't right it didn't continue executing the rest of the code.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm trying to verify a user's input on a web login form using JavaScript, but something drives me nuts and I don't know whats wrong. Restrictions: Ref. number must be numeric, and postcode can contain only numbers and letters. So I'm checking this and the length of input fields through out a couple of functions. In addition the HTML form and JavaScript file. EDIT: All validation methods falls, even if i dont enter a value into the fields it redirect me to the succesful login page.
<html>
<form method"POST" id="loginform" action="thank-you.html">
<table>
<tr>
<td> Post Code : <input id="postcode" type="text" required="required" /></td>
<td> Ref. Number :<input id="passw" type="password" required="required" /></td>
<td> <input type="submit" class="submit"value="Submit" </td>
</tr>
</table>
</form>
</html
And the javascrit code:
function formValidation() {
document.getElementById("loginform").onsubmit = function () {
var uid = document.loginform.postcode;
var passid = document.loginform.passw;
if (postcode_validation(uid, 5, 7)) {
if (passid_validation(passid, 4, 6)) {
if (alphanumeric(uid)) {
if (allnumeric(passid)) {}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("Postcode should not be empty / length be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function alphanumeric(uid) {
var letters = /^[0-9a-zA-Z]+$/;
if (uid.value.match(letters)) {
return true;
} else {
alert('postcode must have alphanumeric characters only');
uid.focus();
return false;
}
}
function allnumeric(passid) {
var numbers = /^[0-9]+$/;
if (passid.value.match(numbers)) {
return true;
} else {
alert('REf number must have numeric characters only');
passid.focus();
return false;
}
}
window.onload = function () {
formValidation();
}
The submit tag isn't closed. Look at the code highlighting Stackoverflow puts there, it's missing on the submit tag.
<td> <input type="submit" class="submit"value="Submit" </td>
should be:
<td> <input type="submit" class="submit" value="Submit" /></td>
I think you may try to add a final return statement in the innermost if-block.
function formValidation() {
document.getElementById("loginform").onsubmit = function () {
var uid = document.loginform.postcode;
var passid = document.loginform.passw;
if (postcode_validation(uid, 5, 7)) {
if (passid_validation(passid, 4, 6)) {
if (alphanumeric(uid)) {
if (allnumeric(passid)) {
return true;
}
}
}
}
}
return false;
}
I know this seems too simple, but it's obviously missing in your code.
Without the return statement Javascript defaults to undefined, what will prefend your form from submitting.
Change your code to the following:
<html>
<form method"POST" onSubmit="return formValidation(this)" id="loginform" action="thank-you.html">
<table>
<tr>
<td> Post Code : <input name="postcode" id="postcode" type="text" required="required" /></td>
<td> Ref. Number :<input name="passw" id="passw" type="password" required="required" /></td>
<td> <input type="submit" class="submit"value="submit"> </td>
</tr>
</table>
</form>
</html>
And:
function formValidation(theForm) {
if (postcode_validation(theForm.postcode, 5, 7)) {
if (passid_validation(theForm.passwd, 4, 6)) {
if (alphanumeric(this.postcode)) {
if (allnumeric(theForm.passwd)) {
return true;
}
}
}
}
return false;
}
This way you don't have to fetch elements by ID, because you have everything you need inside the added parameter theForm. If you don't use the IDs for layout just remove them entirely.
Hello everyone i am working on a project similar to a shopping cart.I am using the below code to generate textboxes(for selecting the quantity) in my view:
#foreach (var item in Model)
{
<tr>
<td align="left" class="Text_nocolor">
#Html.DisplayFor(modelItem=>item.ProductName)
/td>
<td align="right" class="Text_nocolor" valign="top">
#using (Html.BeginForm("Update", "Cart", new { UserID = Request.QueryString["UserID"] }, FormMethod.Post, new { id = "myForm" }))
{
<input id="Quantity" type="text" class="Text_nocolor" name="Quantity" value="#item.Quantity" #*onblur="return NumberOnlyTextBox(event)"*# onchange="return allownumbers()" maxlength="3"/>
#Html.Hidden("unitrate", item.Rate)
<input type="submit" value="Edit" class="Text_nocolor" onkeypress="return validateNumbersOnly(e);" onclick="return RegainFocus();" />
}
In the above code "id=Quantity" represents the textboxes.
and i have written a javascript for numbers only validation for these textboxes.
These are my javascript functions:
<script type="text/javascript">
function RegainFocus() {
if ((document.getElementById("Quantity").value).length == 0) {
document.getElementById("Quantity").focus();
alert("Quantity cannot be empty");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
else if ((document.getElementById("Quantity").value) > 100) {
alert("There is no enough inventory for this product to fulfill your order");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
}
</script>
<script type="text/javascript">
function allownumbers() {
// var elements = document.getElementsByName('Quantity');
// for()
var val = parseInt(document.getElementsByName("Quantity").item(1).value);
alert(val);
if (!val || val < 1) {
alert('Please enter a valid value');
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
document.getElementById("Quantity").value = val;
return true;
}
</script>
My problem is that the validation works only for the first textbox not the others.
Can anyone pls provide a solution? Thank you
Try it using the following code snippet:
onkeypress="return validateNumbersOnly(this);" onclick="return RegainFocus(this);"
...
function RegainFocus(obj)
{
if ((document.getElementById(obj).value).length == 0) {
..
}
..
Hope it helps.
I have a form with variable length of dynamic field names, for instanced, item{n}, the n could be 1 or 30, and I need to calculate the subtotal of qty{n} * price{n} for each such data row, then finally sum subtotal up.
The form looks like the following:
<form>
<table name="forInstruction">
<tr><td>... </td> <td>...</td> ... more td </tr>
....
</table>
<table name="forUserinput">
<tr>
<td><input type="text" id="item1">,</td> <td><input type="text" id="qty1">,</td>
<td><input type="text" id="price1">,</td> <td>fieldX1 t1 </td> ... more td
</tr>
<tr>
<td><input type="text" id="item2">,</td> <td><input type="text" id="qty2">,</td>
<td><input type="text" id="price2">,</td> <td>fieldX2,t2 </td> ... more td
<td><input type="text" id="item3">,</td> <td><input type="text" id="qty3">,</td>
<td><input type="text" id="price3">,</td> <td>fieldX3,t3 </td> ... more td
...
</table>
<input type="button" value="Calculate subtotal and total" ... />
</form>
Notes:
a) t{n} = subtotal field.
b) as mentioned above, number of rows is unknown, it could be 1 to 30.
What I'd like to do is: calculate subtotal and total.
each subtotal = qty{n} * parseFloat(price{n})
My attempt is to loop through the entire form, I'm able to retrieve
all the values for the qty{n} field,
but I don't know how to retrieve the value of its Corresponding
Price{n}.
var fQ=0,fP=0;
st = 0;
total = 0;
for (f=0; f < document.qr.elements.length; f++) {
if (document.qr.elements[f].name.indexOf('qty')>=0) {
// alert(document.qr.elements[f].name + ' ' + document.qr.elements[f].value);
fQ = document.qr.elements[f].value;
// alert(fQ);
}
else if (document.qr.elements[f].name.indexOf('priceLabel')>=0) {
fP = document.qr.elements[f].value;
}
// what do we do here? Or this is not the good way to go?
}
Maybe, loop through the entire form isn't a good idea... only data rows in a named table? If so, how?
Many thanks in advance.
EDIT 1:
Upon advice,
new code:
var i = 0, t=0,
element;
while ((element = forms[0].elements['qty' + i])) {
var subtotal = forms[0].elements['qty' + i] * forms[0].elements['price' + i];
forms[0].elements['total' + i].value = subtotal;
t = t + parseFloat(subtotal);
alert(t);
// ...
i++;
}
forms[0].elements['totalFinal'].value = t;
but err msg:
"ReferenceError: forms is not defined". How come? Thanks.