function pretest() {
var a = document.getElementById('pre').value;
var result = parseInt(a);
if (a <= 50) {
document.getElementById('val').value = 1;
}else if(50<a && a<= 80){
document.getElementById('val').value = 2;
}else{
document.getElementById('val').value = 3;
}
}
function posttest(){
var a = document.getElementById('post').value;
var result = parseInt(a);
if (a <= 50) {
document.getElementById('val1').value = 1;
}else if(50<a && a<= 80){
document.getElementById('val1').value = 2;
}else{
document.getElementById('val1').value = 3;
}
}
function all(){
var a = document.getElementById('val').value;
var b = document.getElementById('val1').value;
var c = parseInt(a) + parseInt(b);
if (!isNaN(c)) {
document.getElementById('total').value = c;
}
}
<input onkeyup="pretest();" type="text" id="pre" name="pretest">
<input onkeyup="all();" type="text" id="val" name="val" disabled="disabled">
<input onkeyup="posttest();" type="text" id="post" name="posttest">
<input onkeyup="all();" type="text" id="val1" name="val1" disabled="disabled">
<input onkeyup="total();" type="text" id="total" name="total" disabled="disabled">
i have 5 text field
A1 A2(value onkeyup from A1 and disabled is true)
B1 B2(value onkeyup from B1 and disabled is true)
C(A2+B2 and disabled textfield)
How to get value for C textfield ? i used onkeyup, but didn't work
There are several things amiss in your code.
never, ever use parseInt(foo) without the radix-argument, especially when foo is arbitrary input. parseInt will otherwise take input 012 and think it's an octal value you gave it. Thus, make that parseInt(a, 10) to get a decimal, or use Number(a)
onkeyup won't fire on a disabled element - how could it? Nobody will be able to press a key there, since it's disabled. What you probably want is onchange, however...
...onchange (or oninput, which is a little more trigger-happy and what I've used below) won't fire when you manually set an element's value; it doesn't in vanilla JS, nor when using jQuery's val() - you have to trigger it manually
your code example is rushed, incomplete and I had to work considerably longer and harder to understand what you want than should be necessary; regardless...
/*
Especially with function names like `all` and `total`, you will want
to make sure to set up some sort of namespacing, e.g. using the
Revealing Module Pattern or other. These functions are attached to
the global window object and can be overriden by anything and anybody,
causing at least hard-to-trace bugs, maybe worse
*/
function pretest() {
var a = document.getElementById('pre').value;
var result = parseInt(a, 10);
if (a <= 50) {
document.getElementById('val').value = 1;
} else if (50 < a && a <= 80) {
document.getElementById('val').value = 2;
} else {
document.getElementById('val').value = 3;
}
// you have to explicitly call all() here, as the input-event
// won't be fired when manually setting value
all();
}
function posttest() {
var a = document.getElementById('post').value;
var result = parseInt(a, 10);
if (a <= 50) {
document.getElementById('val1').value = 1;
} else if (50 < a && a <= 80) {
document.getElementById('val1').value = 2;
} else {
document.getElementById('val1').value = 3;
}
all()
}
function all() {
var a = document.getElementById('val').value;
var b = document.getElementById('val1').value;
var c = parseInt(a, 10) + parseInt(b, 10);
if (!isNaN(c)) {
document.getElementById('total').value = c;
}
total();
}
total = function() {
//TODO implement
}
document.getElementById('pre').addEventListener('input', window.pretest);
document.getElementById('post').addEventListener('input', window.posttest);
<label for="pre">PRE</label><br>
<input type="text" id="pre" name="pretest">
<br><br>
<label for="val">val</label><br>
<input type="text" id="val" name="val" disabled="disabled">
<br><br>
<label for="post">POST</label><br>
<input type="text" id="post" name="posttest">
<br><br>
<label for="val1">val1</label><br>
<input type="text" id="val1" name="val1" disabled="disabled">
<br><br>
<label for="total">TOTAL</label><br>
<input type="text" id="total" name="total" disabled="disabled">
You can get value as from normal text input
function myFunction(){
document.getElementById("textPlace").disabled = true;
console.log(document.getElementById("textPlace").value)
}
<input type="text" onkeyup="myFunction()" id="textPlace">
Related
Previously I made an onchange input, there are several inputs that have the same thing called by id. How do I call multiple
ids in one line of code? I tried to write it like this but failed:
function minmax() {
const inp_field = document.querySelectorAll("#input1, #input2, #input3, #input4");
let val = parseFloat(inp_field.value),
min = parseFloat(inp_field.min),
max = parseFloat(inp_field.max);
if (val < min) {
inp_field.value = min;
} else if (val > max) {
inp_field.value = max;
} else {
inp_field.value = val;
}
}
<input id="input1" type="text" onchange="minmax()" min="0.01" max="94.99">
<input id="input2" type="text" onchange="minmax()" min="0.1" max="99.99">
<input id="input3" type="text" onchange="minmax()" min="5" max="25">
<input id="input4" type="text" onchange="minmax()" min="1" max="10">
Assuming that you want to update each input value based on its min/max attributes as it changes:
There's no real need for those ids. If you wanted to group them you could use a class instead, but here I'm just picking up the inputs by element name.
Remove the requirement for inline JS and use addEventListener to attach listeners to each input.
You can use this (the context referring to the clicked element) in the function to make the code more concise.
You can remove this.value = val since the input value is already set.
Finally, while max/min aren't specified as attributes on a you can use with type="text" apparently you can still use them. But you may want to change to type="number".
const inputs = document.querySelectorAll('input');
inputs.forEach(input => {
input.addEventListener('change', minMax);
});
function minMax() {
const val = parseFloat(this.value);
const min = parseFloat(this.min);
const max = parseFloat(this.max);
if (val < min) this.value = min;
if (val > max) this.value = max;
}
<input type="text" min="0.01" max="94.99">
<input type="text" min="0.1" max="99.99">
<input type="text" min="5" max="25">
<input type="text" min="1" max="10">
I doubt you really need all that... try this and see if it serves your need.
function minmax(inp_field) {
let val = parseFloat(inp_field.value),
min = parseFloat(inp_field.min),
max = parseFloat(inp_field.max);
//below we call a function that checks if the value contains any scientific/engineering notation
val = decimalCount(val)
if (val < min) {
inp_field.value = inp_field.min;
} else if (val > max) {
inp_field.value = inp_field.max;
} else {
inp_field.value = val;
}
}
function decimalCount(val){
let valStr = val.toString(); //convert float to string
//check if the value include e-... example 1e-7
if(valStr.includes('e-')){
//get the value before the scietific notation
let beforeE = valStr.substr(0,valStr.indexOf('e'));
//the following removes a comma. example 0.000000017 == 1.7e-7
beforeE = beforeE.replace('.','')
//get the number of zeros after the scientific notation
let decimalPlace = valStr.substr((valStr.indexOf('-') + 1)) - 1
//we set a variable for the zeros after the .
let zeros = '.';
//assign the zeros to appear after the .
for(let i=0;i<decimalPlace;i++){
zeros += 0;
}
//concatenate the results and return the value for display
return 0 + zeros + beforeE;
}else{
//else, we return the min/max as it is
return val;
}
}
<input id="input1" type="text" onchange="minmax(this)" min="0.01" max="94.99">
<input id="input2" type="text" onchange="minmax(this)" min="0.00000001" max="99.99">
<input id="input3" type="text" onchange="minmax(this)" min="5" max="25">
<input id="input4" type="text" onchange="minmax(this)" min="1" max="10">
If your aim is to keep all the inputs in sync whenever one of them is changing, then a slight adjustment is required using forEach.
Keep in mind, however, that querySelectorAll produces a NodeList, not an Array:
function minmax() {
const inp_fields = document.querySelectorAll("#input1, #input2, #input3, #input4");
inp_fields.forEach(inp_field => {
let val = parseFloat(inp_field.value),
min = parseFloat(inp_field.min),
max = parseFloat(inp_field.max);
if (val < min) {
inp_field.value = min;
} else if (val > max) {
inp_field.value = max;
} else {
inp_field.value = val;
}
});
}
Just make sure to change your input fields type to number and set a proper default value (for example, 0), because otherwise your calculations will yield to NaN being set to all the other fields upon modifying any of them.
You can do this with a for loop.
function minmax() {
const inp_field_arr = ["input1", "input2", "input3", "input4"];
for (let i = 0; i < inp_field_arr.length; i++) {
inp_field = document.getElementById(inp_field_arr[i]);
let val = parseFloat(Number(inp_field.value)),
min = parseFloat(Number(inp_field.min)),
max = parseFloat(Number(inp_field.max));
if (val < min) {
inp_field.value = min;
} else if (val > max) {
inp_field.value = max;
} else {
inp_field.value = val;
}
}
}
<input id="input1" type="text" onchange="minmax()" min="0.01" max="94.99">
<input id="input2" type="text" onchange="minmax()" min="0.1" max="99.99">
<input id="input3" type="text" onchange="minmax()" min="5" max="25">
<input id="input4" type="text" onchange="minmax()" min="1" max="10">
A more efficient way of doing this, though, would be to get the value in the onChange part. This can also fix some errors that may occur.
You can do this by removing the let val, let min, and let max, and instead using onchange="minmax(parseFloat(this.value), parseFloat(this.min), parseFloat(this.max))", and making the function declaration function minmax(val, min, max).
More information about:
for loop MDN DigitalOcean DevDocs Wikipedia
Number MDN
like this ,ids are can change according your code ,like this, ids are can change according to your code,but logical is this
const elements=document.qeuerySelectorAll('#id, #id2,#id3');
elements.foreEach(funcion(element){
console.log(element);
});
Consider to use classes, instead of element ids, when you are dealing with multiple elements. And is, also, a best practice.
Then you can use a function like getElementsByClassName()
I´m trying to do different javascript validations before sending a form, the problem is that I haven´t been able to prevent the form from submit, it checks the conditions and sends alerts when a conditions hasn´t been satisfied but it sends the form anyways. I want the button to either be disabled until everything is right or send a message telling user, to check the cuenta.
Thanks in advance. This is my code:
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post">
Enter CLABE account:
<input name="clabe" id="clabe" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control" id="control" maxlength="1" size="2" required >
Again:
<input name="clabe2" id="clabe2" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr>
Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();" >
<hr>
Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="submit" id="myBtn" value="Guardar Cambios" onclick ="return compareclabe();" ><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
<script>
function compareclabe(){
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if( x3 != z3){
alert("keys are not equal");
return false;
}else if (x3 == z3){
this.someFunc(); //I want to call function someFunc and then
if the result is true, execute the next code
if (true){
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
return true;
}
}else{
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x,'37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10 ) {
digito_control = 0;
var dg = digito_control;
}else{
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z){
alert("checkig digit is not equal");
return false;
}
else if (dg == z){
alert("checkig digit is equal");
return true;
}
}
</script>
I changed form submit button type to "button" and if all the validations are passed, then submit form from javascript. See below code
function compareclabe() {
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if (x3 != z3) {
alert("keys are not equal");
return false;
} else if (x3 == z3) {
this.someFunc(); //I want to call function someFunc and then if the result is true, execute the next code
if (true) {
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
$('#form').submit(); //submit form if all validation succeeds
}
} else {
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x, '37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10) {
digito_control = 0;
var dg = digito_control;
} else {
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z) {
alert("checkig digit is not equal");
return false;
} else if (dg == z) {
alert("checkig digit is equal");
return true;
}
}
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post" id="form"> <!-- I included an id to form -->
Enter CLABE account:
<input name="clabe" id="clabe" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control" id="control" maxlength="1" size="2" required> Again:
<input name="clabe2" id="clabe2" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr> Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();">
<hr> Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="button" id="myBtn" value="Guardar Cambios" onclick="return compareclabe();"><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
But there are many validation plugins where you can easily implement. No need to code from begining. Refer this for an example -> https://jqueryvalidation.org/
You can disable the button by default, and add event listeners to all the inputs in your form. But be weary of other ways to submit the form, like the enter key. I would add an onsubmit function just to prevent all ways the event can happen when you don't want it to.
const form = document.querySelector('form')
const inputs = [...form.querySelectorAll('input')] // convert node list to array
const isValid = () => {
let valid = false
disableButton()
// handle your conditions here
if (valid) enableButton()
return valid;
}
inputs.forEach( input => input.addEventListener('input', isValid))
form.onsubmit = event => if (!isValid()) event.preventDefault()
Or ES5 if you prefer:
var form = document.querySelector('form');
var inputNodes = form.querySelectorAll('input');
var inputs = Array.prototype.call.slice(inputNodes); // convert node list to array
var isValid = function() {
var valid = false;
disableButton();
// handle your conditions here
if (valid) enableButton();
return valid
}
inputs.forEach( function(input) {
input.addEventListener('input', isValid);
});
form.onsubmit = function(event) {
if (!isValid()) event.preventDefault();
};
It's also worth noting that HTML5 has a lot of built-in validation you can take advantage of.
var x1 = document.getElementById("x1");
var x2 = document.getElementById("x2");
function ThisEvent(){// needs a lot of work done to it
if (x1.value==1) {
x2.value--;
} else if (x1.value==2) {
x2.value++;
} else if (x1.value==3) {
x2.value+=5;
}
}
<input type="text" value="0" id="x1" onblur="ThisEvent()"> x1 </br>
<input type="text" value="0" id="x2"> x2
what is happening now is the digit is being added instead of incrementing when 3 is the input if x1. how do you make it increment by more than just one, without it being added it as a digit?
if (x1.value == 3) {
x2.value = parseInt(x2.value) + 5;
}
It's interpreting it as a string. You can parseInt the x2.value in the calculation.
The value of the input is a String, you need to convert it to a Number in order to perfom an addition on it.
You could do it like this:
function ThisEvent() { // needs a lot of work done to it
var valX1 = Number(x1.value);
var valX2 = Number(x2.value);
if (valX1 == 1) {
valX2--;
} else {
if (valX1 == 2) {
valX2++;
} else {
if (valX1 == 3) {
valX2 += 5;
}
}
}
x2.value = valX2;
}
jsFiddle: https://jsfiddle.net/v1utqv7f/
im trying to make a simple perimeter calculator for a projector screen.
The code should take the response from a radio button input and the diagonal length to calculate the perimeter accordingly.
here is my code atm:
<html>
<body>
<script language="javascript">
function calc() {
var form = document.forms.Calculator;
var A = Number(getSelectedValue(form.elements.A));
var B = Number(getSelectedValue(form.elements.B));
if (A = 0) {
L = 0.8;
H = 0.6;
} else if (A = 1) {
L = 0.872;
H = 0.49;
} else {
L = 0.922;
H = 0.386;
}
form.elements.Total.value = 2 * B * (L + H);
}
function getSelectedValue(flds) {
var i = 0;
var len = flds.length;
while (i < len) {
if (flds[i].checked) {
return flds[i].value;
}
i++;
}
return "";
}
</script>
<title>Calculator</title> <pre>
<form name="Calculator">
<label>A</label>
4:3: <input name="A" type="radio" onChange="calc()" value="0" checked>
16:9: <input name="A" type="radio" onChange="calc()" value="1">
2.39:1: <input name="A" type="radio" onChange="calc()" value="2">
<label>B</label>
Screen Size: <input name="B" type="text" onChange="calc()" checked>
<label>Total</label>
<input type="text" name="Total" onChange="calc()" readonly size="10"><br>
<input type="submit" value="Submit Calculation"> <input type="reset" value="Clear">
</form>
</pre>
</body>
</html>
Your function getSelectedValue is wrong. It loops trough an array of elements to see which one is checked. You are trying to do the same for B which is only one element so that is not going trough the loop and thus returns ''.
So instead of
var B = Number(getSelectedValue(form.elements.B));
try
var B = Number(form.elements.B.value);
Also, your if else statements are wrong. It should be == instead of =:
if (A == 0) {
L = 0.8;
H = 0.6;
} else if (A == 1) {
L = 0.872;
H = 0.49;
} else {
L = 0.922;
H = 0.386;
}
I must admit, I don't know much about JavaScript that is why my question might sound little bit silly.
But what I'm trying to do is grab values from selected by name radio groups.
It looks like this
function calc() {
var op1 = document.getElementsByName('form[radio1]');
var op2 = document.getElementsByName('form[radio2]');
var op3 = document.getElementsByName('form[radio3]');
var result = document.getElementById('result');
result.value = 0;
result.value = parseInt(result.value);
for (i = 0; i < op1.length; i++) {
if (op1[i].checked) result.value = parseInt(result.value) + parseInt(op1[i].value);
}
for (i = 0; i < op2.length; i++) {
if (op2.options[i].selected) result.value = parseInt(result.value) + parseInt(op2[i].value);
}
for (i = 0; i < op3.length; i++) {
if (op3.options[i].selected) result.value = parseInt(result.value) + parseInt(op3[i].value);
}
return false;
}
And this is my form. Im using rs form for joomla.
<form action="index.php" enctype="multipart/form-data" id="userForm" method="post">
<input name="form[radio1]" value="25" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio1]" value="35" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input name="form[radio2]" value="20" id="radio20" type="radio">
<label for="radio20">Description1</label>
<input name="form[radio2]" value="30" id="radio21" type="radio">
<label for="radio21">Description2</label>
<input type="hidden" value="0" id="result" name="form[result]">
<input type="submit" class="rsform-submit-button" onclick="calc()" id="submit" name="form[submit]" value="submit">
And everything would be OK, as the function is working. the only trouble is that I have about 80 radiograms.
Is there a way to shorten it?
Use arrays of objects (like all the radio buttons, for instance) and iterate over them. Start like this:
var opts = [],
numOpts = 80;
for (var i=0; i<numOpts, i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
Edit: let's have a go at the full function. The only thing I'm not 100% sure about is whether you mean to use opX[i].checked or opX.options[i].selected (since your code does different things for op1 and op2/3). Shouldn't be too hard to extrapolate if I've guessed wrong, though.
function calc()
{
var opts = [],
numOpts = 80,
value = 0,
result = document.getElementById('result'),
i, j, opt;
for (i=0; i<numOpts; i++)
{
opts.push(document.getElementsByName('form[radio' + i + ']'));
}
numOpts = opts.length;
for (i=0; i<numOpts; i++)
{
opt = opts[i];
for (j=0; j<opt.length; j++)
{
// or did you mean:
// if (opt.options[j].selected) ?
if (opt[j].checked)
{
value = value + parseInt(opt[j].value, 10);
}
}
}
result.value = value;
return false;
}
jQuery is a great library that's like using JavaScript on steroids. It is well worth learning and there are plenty of examples out in the wild.
You can write complex "selectors" quite like this:
$('input[name=form[radio1]]').attr('checked').each(function() {
result.value = $(this).attr('value')
})
(I'm not sure if it will accept a name like "form[radio1]" as valid, but give it a try.