i need help please,
im trying to check "if" condition inside a function and print it to the input field
but i always get false, why this if statement inside the function always return false?
and how can i fix it, Thanks.
<body>
<label>Value1:</label>
<input id='v1' type="number"><br><br>
<label>Value2:</label>
<input id='v2' type="number"><br><br>
<label>Value3:</label>
<input id='v3' type="number"><br><br>
<button onclick="calculateTriangle()">Answer</button>
<input id='ans'><br><br>
<script>
function calculateTriangle() {
var V1 = document.getElementById('v1').value;
var V2 = document.getElementById('v2').value;
var V3 = document.getElementById('v3').value;
console.log(V1);
console.log(V2);
console.log(V3);
var an = Triangle(V1,V2,V3)
document.getElementById('ans').value=an;
}
function Triangle(a,b,c){
if (a+b>c && a+c>b && b+c>a){
return true;
}
return false;
}
</script>
</body>
Parse your input values as an integer. Use these lines of code instead of yours. The values from your input fields are string.
So when you check a + b > c it concatenates a + b. Say you put a = 1 and b = 2 then it makes a + b = 12 instead of 3.
var V1 = parseInt(document.getElementById('v1').value);
var V2 = parseInt(document.getElementById('v2').value);
var V3 = parseInt(document.getElementById('v3').value);
if (a+b>c && a+c>b && b+c>a){
return true;
} else {
return false;
}
Related
I have an input tag as follows as part of a form submission.
<input type=“checkbox” id=“allowcheatmode” name=allowCheatMode value=“NO” onchange=“allowCheatModes()”>
And allowCheatModes in a JS function
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElementById(“allowcheatmode”).value = “YES”
} else {
document.getElementById(“allowcheatmode”).value = “NO”
}
But this is not working when I am trying to print the allowcheatmode variable after form submission. What am I doing wrong here?
1) You have included an invalid character “ and ”. You should use " in both HTML and JS.
var x = document.getElementById(“allowcheatmode”).checked
2) There is no function named getElemenetById, instead use getElementById.
3) Add if-else code in the onChange function itself. So that it can trigger when checkbox value changes
NOTE I've added an extra label to just show the current state of the checkbox. You can skip that part.
function allowCheatModes() {
var x = document.getElementById("allowcheatmode").checked
if (x) {
document.querySelector("label").textContent = "YES"
document.getElementById("allowcheatmode").value = "YES"
} else {
document.querySelector("label").textContent = "NO"
document.getElementById("allowcheatmode").value = "NO"
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
<label for="allowcheatmode">NO</label>
Shouldn't it be this:
function allowCheatModes(){
var x = document.getElementById(“allowcheatmode”).checked
if (x) {
document.getElemenetById(“allowcheatmode”).value = “YES”
} else {
document.getElemenetById(“allowcheatmode”).value = “NO”
}
}
Try this
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
if (isChecked) {
document.getElementById("allowcheatmode").value = "YES";
} else {
document.getElementById("allowcheatmode").value = "NO";
}
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
The code above will be valid, because you had typo in getElemenetById (should be getElementById, not getElemeNETById). Anyway, you will see nothing in this case, because input with type="checkbox" have no view. You can improve your code adding some div element:
function allowCheatModes(){
var isChecked = document.getElementById("allowcheatmode").checked;
document.getElementById("allowcheatmode-view").innerHTML = isChecked ? "YES" : "NO";
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" onchange="allowCheatModes()">
<div id="allowcheatmode-view">NO</div>
P.S.: "condition ? ifTrue : ifFalse" is ternary operator, the short form of "if"
You did two things wrong
First thing
You put if outside the function, please put if inside the function
function allowCheatModes() {
...
}
Replace with
function allowCheatModes() {
...
if(x){
...
}
}
Second thing
The function name you are using is wrong, you should use getElementById, not getElemenetById
document.getElemenetById
Replace with
document.getElementById
Below is my adjusted snippet, you can refer to it.
Have a good day :)
function allowCheatModes(){
var x = document.getElementById("allowcheatmode").checked;
if (x) {
document.getElementById("allowcheatmode").value = "YES"
} else {
document.getElementById("allowcheatmode").value = "NO"
}
console.log(document.getElementById("allowcheatmode").value);
}
<input type="checkbox" id="allowcheatmode" name="allowCheatMode" value="NO" onchange="allowCheatModes()">
I need to understand how to do real time calculation on Edit.js
By searching and looking around i came up with this code in Edit.js of the Contact Module.
calculate_amount: function (){
var units = $("input[name='cf_852']");
var value = $("input[name='cf_854']");
$(units, value).on('keyup', function(){
if (units.val() != '' && value.val() != ''){
var currentamount = units.val() * value.val();
$("input[name='cf_856']").val(currentamount);
}
});
}
Have i done something wrong? Because it doesn't work..
Thanks for all the help!
I should write your keyup function like this:
I tested, it's OK
calculateAmount: function (){
var units = $("input[name='cf_1512']");
var value = $("input[name='cf_1514']");
$(document).on('keyup',"input[name='cf_1512'], input[name='cf_1514']", function(){
if (units.val() != '' && value.val() != ''){
var currentamount = units.val() * value.val();
$("input[name='cf_1518']").val(currentamount);
}
})
},
You must call you function into the function registerBasicEvents.
If the registerBasicEvents function is not available in Edit.js of Contacts module so add it.
registerBasicEvents: function (container) {
this._super(container);
this.calculate_amount();
}
You should pass id's of element instead reference of element for Keyup function. Please find below code snippet and modify your code in vTiger. As I checked all syntax and function written correctly in your script. Just pass the comma separated id's and execute the code. Thanks!
var units = $('#Contacts_editView_fieldName_cf_1512');
var value = $('#Contacts_editView_fieldName_cf_1514');
$('#Contacts_editView_fieldName_cf_1512, #Contacts_editView_fieldName_cf_1514').on('keyup', function(){
if (units.val() != '' && value.val() != ''){
var currentamount = parseFloat(units.val()) * parseFloat(value.val());
$("#Contacts_editView_fieldName_cf_1516").val(currentamount);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Input1: <input type="text" id="Contacts_editView_fieldName_cf_1512"/><br/>
Input2: <input type="text" id="Contacts_editView_fieldName_cf_1514" /><br/>
Result: <input type="text" id="Contacts_editView_fieldName_cf_1516"/>
Pretty new to this Javascript thing.
I want to change a Javascript variable when a user inserts a number into an input field in my HTML document and clicks a button.
I'm assuming you'd use a function, but how do you gather the data and change the variable?
The stuff I tried to make looks a little something like this.
HTML
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value;
}
but it's not working!
Edit 1:
Wow. I didn't think I'd get this kind of attention. I also found it a bit strange it didn't work at first.
The question I'm asking is partly for a calculator here: https://titomagic.com/debug
It's simple, you type in a number, click the button and it calculates (based on other variables) to a result on the bottom.
Here's a link to the Javascript file, if you wanna have a look: https://titomagic.com/js/bursdagskalkulator.js
To those of you asking; yes, I've been testing with a console.log and the variable is not changing. It's not affecting the other variables (as it should?).
Also I've never heard of JSfiddle.
I discovered few things in the summarizeGjester() function. First of all I moved all the Javascript code in the bursdagskalkulator.js file inside the summarizeGjester() function. Also I converted var antallGjester to integer using parseInt() function, because it was treated as string before.
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester); //integer conversion
Also the first Boolean comparison was changed to
if ((antallGjester < 10) && (antallGjester > 0)), so that the second one would work if there’s 0 value: else if (antallGjester === 0).
function summarizeGjester() {
var antallGjester = document.getElementById("gjesterAntallInput").value;
antallGjester = parseInt(antallGjester);
var fastPris = 1500;
var fastPrisDifferanse = 10;
var gjestePris = 120;
var gjesteDifferanse = antallGjester - fastPrisDifferanse;
var gjesteSum = gjestePris * gjesteDifferanse;
var gjesterTotalt = 0;
if ((antallGjester < 10) && (antallGjester > 0)) {
console.log("antallGjester < 10");
gjesterTotalt = 1500;
} else if (antallGjester === 0) {
console.log("antallGjester === 0");
gjesterTotalt = 0;
} else {
console.log("else");
gjesterTotalt = fastPris + gjesteSum;
}
document.querySelector('#results').innerHTML = gjesterTotalt;
}
<form>
<div class="form-group">
<label for="gjesterAntall">Antall barn:</label>
<input type="number" class="form-control" id="gjesterAntallInput">
</div>
<button class="btn btn-lg btn-warning" onclick="summarizeGjester()" type="button" id="sumGjester">Legg sammen</button>
</form>
<h1 class="text-center" style="font-size:80px;"><strong><span id="results">0</span>,-</h1>
I hope this helps :-)
HTML
<input type="number" id="inputField" ClientIDMode="static">
<button onclick="changeTheVariable()" type="button" id="pushMe"></button>
Javascript
var a = 0;
function changeTheVariable() {
a = document.getElementById('inputField').value;
alert(a);
}
Use Static ClientIDMode for stable id and access after page rendering
PlaceHolders canh change childe's id
I suppose this will work for you
var a = 0;
function changeTheVariable() {
a = document.getElementById("inputField").value || a;
document.getElementById("result").innerText = parseFloat(a);
}
<input type="number" id="inputField">
<button onclick="changeTheVariable()" type="button" id="pushMe">Click me</button>
<div>Result: <span id="result"></span></div>
Edited:
The reason behind this code is not running in jsfiddle is here.
After making the changeTheVariable() global variable this code will work in jsfiddle also. Here https://jsfiddle.net/1b9cfmje/
Use the following javascript code:
window.onload = function(){ var a = 0; window.changeTheVariable = function() { a = document.getElementById("inputField").value || a; document.getElementById("result").innerText = parseFloat(a); }}
I'm making a quiz with a text input. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function check() {
var s1 = document.getElementsByName('s1');
if(s1 == 'ō') {
document.getElementById("as1").innerHTML = 'Correct';
} else {
document.getElementById("as1").innerHTML = 'Incorrect';
}
var s2 = document.getElementsByName('s2');
if(s2 == 's') {
document.getElementById("as2").innerHTML = 'Correct';
} else {
document.getElementById("as2").innerHTML = 'Incorrect';
}
//(...etc...)
var p3 = document.getElementsByName('p3');
if(p3 == 'nt') {
document.getElementById("ap3").innerHTML = 'Correct';
} else {
document.getElementById("ap3").innerHTML = 'Incorrect';
}
}
</script>
</head>
<body>
1st sing<input type="text" name="s1"> <div id="as1"><br>
2nd sing<input type="text" name="s2"> <div id="as2"><br>
<!-- ...etc... -->
3rd pl<input type="text" name="p3"> <div id="ap3"><br>
<button onclick='check()'>Check Answers</button>
</body>
</html>
Every time I check answers it always says Incorrect and only shows the first question. I also need a way to clear the text fields after I check the answers. One of the answers has a macro. Thanks in advance.
The method getElementsByName returns a NodeList, you can't really compare that against a string. If you have only one element with such name, you need to grab the first element from that list using such code instead:
var s1 = document.getElementsByName('s1')[0].value;
To make it more flexible and elegant plus avoid error when you have typo in a name, first add such function:
function SetStatus(sName, sCorrect, sPlaceholder) {
var elements = document.getElementsByName(sName);
if (elements.length == 1) {
var placeholder = document.getElementById(sPlaceholder);
if (placeholder) {
var value = elements[0].value;
placeholder.innerHTML = (value === sCorrect) ? "Correct" : "Incorrect";
} else {
//uncomment below line to show debug info
//alert("placeholder " + sPlaceholder+ " does not exist");
}
} else {
//uncomment below line to show debug info
//alert("element named " + sName + " does not exist or exists more than once");
}
}
Then your code will become:
SetStatus('s1', 'ō', 'as1');
SetStatus('s2', 's', 'as2');
//...
document.getElementsByName('s1') is an array you should use document.getElementsByName('s1')[0] to get certain element(first in this case)
I want to keep a value from a form by a js function
with document.getElementById("form1")
but in the form there are dynamic inputs amount1 , amount2 ect... (i dont know how many - its from database)
how do i reach form1.amount (p)
when p is the index of the amount ?
thanks
You can retrieve it like this:
var frm = document.getElementById("form1");
if (frm) {
var valueA = frm["amount" + 1].value;
}
A more complete example:
<html>
<form id="f1">
<input name="input1" value="text" type="text" />
</form>
<script>
var f = document.getElementById("f1");
if(f)
{
alert(f["input"+1]);
alert(f["input"+1].value);
}
</script>
</html>
You can get all input elements of a form by use of "getElementsByTagName". Like this:
var form = document.getElementById("form1");
var inputs = form.getElementsByTagName("input");
That way the array "inputs" contains all input elements contained in your form.
Ioannis is pretty much there. To get the value of the ith amount input, use:
var value = document.forms['form1'].elements['amount' + i].value;
A little more robustly:
function getIthAmount(i) {
var o = document.forms['form1'];
o = o && o.elements['amount' + i];
if (o) {
return o.value;
}
}