how to use id of a button in if statement using javascript - javascript

I am a beginner to Javascript and am trying to perform arithmetic functions.
Here is my code below:
script
<script language="javascript" type="text/javascript">
function func(a,b)
{
var a = document.getElementById("a");
var b = document.getElementById("b");
if (document.getElementById("btnadd").Text == 'Add')
{
var c = a + b;
document.getElementById("rslt").innerHTML =c;
}
}
</script>
aspx
<asp:Button ID="btnadd" Text="Add" runat="server" OnClientClick="func(txtn1,txtn2)" />
<p id="rslt"></p>
My idea is, when I click say 'add' button the value of two textbox should be passed to the script and are assigned to two variables.
With those two variables all arithmetic (add,sub,div,mul) should be done.

What you could do is also pass the button that was clicked, using this. That way you know the text of the button that was clicked. And since you are using a server side button, be sure to include return false; from your JavaScript call to prevent it from posting back and clearing your <p> tag.
<asp:Button ID="btnadd" runat="server" Text="Add"
OnClientClick="func('txtn1', 'txtn2', this); return false;" />
function func(a, b, btn) {
var txtn1 = document.getElementById(a);
var txtn2 = document.getElementById(b);
var rslt = document.getElementById('rslt');
if(btn.value == 'Add')
rslt.innerHTML = parseInt(txtn1.value) + parseInt(txtn2.value);
}

According to here:
You have to use anonymous functions/handlers to react on such user-interactions without reloading the page. Also look at jquery (http://api.jquery.com/click/) which gives you a simpler api to write those things.
<script language="javascript" type="text/javascript">
function func(a,b) {
var a = document.getElementById("a");
var b = document.getElementById("b");
var btn = document.getElementsById("btnadd");
btn.onclick = function() {
var c = a + b;
// alert("Result = " + c );
document.getElementById("rslt").innerHTML =c;
}
}
</script>

Hope that your requirement is to perform arithmetic operations with two numbers from the text boxes.For that you need not pass text boxes as parameters to the script since it uses document.getElementById. directly access the textbox inside the script as follows:
<head><script>
function myFunction(a) {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x;
if(a==1)
x = +y + +z;
else if(a==2)
x=+y - +z;
else
x=0;
document.getElementById("demo").innerHTML = x;
}
</script></head>
<body>
<p>Click the button to calculate x.</p>
<br/>
<br/>Enter first number:
<input type="text" id="txt1" name="text1">Enter second number:
<input type="text" id="txt2" name="text2">
<button onclick="myFunction(1)">Addition</button>
<button onclick="myFunction(2)">Subtraction</button>
<p id="demo"></p>
</body>
The above code will perform addition and subtraction based on button click

function func(a,b) {
var a,b;
a=$("#a").val();
b=$("#b").val();
if ($("#btnAdd").val() == 'Add') {
$("#a").val(+(a) + +(b));
}
}
And Set button value to Add
Or if you want to reduce your code then use this code
if ($("#btnAdd").val() == 'Add') {
$("#a").val( +($("#a").val()) + +($("#b").val() ));
}

Related

ASP.Net MVC Javascript Keyboard not working

My virtual keyboard was working but when I added the button inside a Form instead of a Div it stopped working.
This is my javascript code:
$(document).ready(function () {
function input(e) {
//var u = document.rateformular;// duplicated with f and not used
var f = document.rateformular;
var b = f.elements["ratezeichen"];
var zeichen = b.value;
zeichen.value = zeichen.value + e.value
}
And the button has this onclick:
<div class="cities">
<input id="btn1" type="button" value="a" class="btn btn-default" onclick="input(this);" />
</div>
your input function has to be declared in the global scope
outside $(document).ready(function () {...
or
directly attached to global object window.input = function(e) { ...
This is what I did to fix my problem.
function input(e) {
var f = document.rateformular;
var b = f.elements["ratezeichen"];
if (b.value == 0) {
b.value = b.value + e.value;
}
else {
}
The main problem was in the scope and then I had to make a few changes in the code.
Thanks StackOverFlow.
The if cicle is to prevent that the user can input 2 letters, they only can type 1 letter, it's the max lenght of the TextBox, it's part of my application.

Changing Javascript variable value after onclick action

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); }}

Pixel to cm conversion script not working

The goal is to type in one text box a certain value (of pixels or centimeters) then to press a button, and the button to do some maths and show the result in a different text box.
What happens is, I'll get a result of 'NaN', implying that the string I inputted hadn't been converted properly. I've gone through hundreds of methods to fix this and it still doesn't work.
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conversion</title>
</head>
<body bgcolor=#FF0000>
<form id="conversions" name="conversions">
Pixel value :
<br>
<input type="text" name="pxvalue" id="pxvalue">
<br>
<input type="submit" name="convertcm" id="convertcm" value="Convert cm to px!">
<input type="submit" name="convertpx" id="convertpx" value="Convert px to cm!">
<br>Centimeter value :
<br>
<input type="text" name="cmvalue" id="cmvalue">
<br>
<br>Output :
<input type="text" name="output" id="output">
</form>
<!-- This is where all the JavaScript code goes -->
<script>
var form = document.getElementById("conversions");
var strcmvalue = form.elements["cmvalue"];
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue);
var pxvalue = ToInteger(strpxvalue);
var output = document.getElementById("output");
var ccmbutton = document.getElementById("convertcm").onclick = cm_to_pixel_conversion(cmvalue);
var cpxbutton = document.getElementById("convertpx").onclick = pixel_to_cm_conversion(pxvalue);
var cm_per_pixel = 0.026458333;
var px_per_cm = 37.795275591;
function pixel_to_cm_conversion(pvalue) {
cmconversion = pvalue / px_per_cm;
output.value = cmconversion.toString();
}
function cm_to_pixel_conversion(cvalue) {
pxconversion = cvalue / cm_per_pixel;
output.value = pxconversion.toString();
}
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
</script>
<!-- End of the JavaScript code-->
</body>
</html>
Because you are not passing a value to the method, you are passing an html element.
var strcmvalue = form.elements["cmvalue"]; //reference element
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue); //passing element, not the value
var pxvalue = ToInteger(strpxvalue);
You need strcmvalue.value or form.elements["cmvalue"].value
Next issue is the fact you read the values when the page loads, so you will only ever have the values from the time it loads.
So you should be reading the values and converting them to numbers inside of your methods, not when the page loads.
After that your click event is calling the function, not referencing it.
var ccmbutton = document.getElementById("convertcm").onclick = function () {
var num = parseInt(strcmvalue.value, 10);
cm_to_pixel_conversion(num);
return false;
};

how to store input box number in jQuery

Imagine how a normal calculator do. Use click button to input the data in a display box. Now i want to click a button to show "+" and also remove all the number in display but store it. So I can click to show the new number. After that, store those data include number1, "+" and number 2. For example: ("1","+" "2"). The reason of doing that but not using javascript for normal calculating is because I want to use Ajax to send to php and use php to execute the maths.However, I get stuck in this part.
var memory = "";
$("#add").click(function() {
memory += $show.val() + "+";
if($show.val().length >= 1){
$show.val("+");
} else {
$show.val("");
}
}
[Obligatory warning against evaluated code from a string on a server]
I would recommend trying to get a working version of your project using only javascript before trying more advanced concepts.
var memory = [];
$("#add").click(function() {
var val = $show.val();
if (val)
memory.push(val);
$show.val('+');
});
$('#submit').click(function () {
var s = memory.join('+');
memory = [];
$.get(...
});
Check Fiddle here
var one = $("#one");
var two = $("#two");
var add = $("#add");
var show = $("#show");
var equal = $("#equal");
var memory = "";
one.click(function(){
memory += "1";
show.val("1");
});
two.click(function(){
memory += "2";
show.val("2");
});
add.click(function(){
memory += "+";
if(show.val().length >= 1)
show.val("+");
else
show.val("");
});
equal.click(function(){
show.val(memory)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="show" type="text"/>
<input id="one" type="button" value="1"/>
<input id="two" type="button" value="2"/>
<input id="add" type="button" value="+"/>
<input id="equal" type="button" value="="/>

How to disable input attribute after 10 clicks?

I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}​
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>

Categories