Can anyone please help me out in how to get or read two values from single textbox.
i.e when i read the first value it should be stored in string str1 , when operator button is clicked the textbox shld be cleared but must know which operator button was clicked and shld wait to accept second value.The second value shld be stored in str2.
This is like a simple calculator wherein we enter many number in one textbox.
Thank You
Here is my code:
window.onload = function () {
var value1 = "", value2 = "", result="";
document.getElementById('btnone').addEventListener('click', function () {
document.getElementById('textBox').value = document.getElementById('textBox').value + document.getElementById('btnone').value;
value1 = document.getElementById('textBox').value;
});
document.getElementById('btntwo').addEventListener('click', function () {
document.getElementById('textBox').value = document.getElementById('textBox').value + document.getElementById('btntwo').value;
value2 = document.getElementById('textBox').value;
});
document.getElementById('btnadd').addEventListener('click', function () {
document.getElementById('textBox').value = document.getElementById('textBox').value + document.getElementById('btnadd').value;
});
document.getElementById('btneql').addEventListener('click', function () {
result = value1 + value2;
});
You can do this using Jquery
By click() event get the value of your input $('.YourInput').val()
Increase your sum
Clear your input $('.YourInput').val("")
see Fiddle
Update
Using Javascript:
If the user click on number button: 0-9 the value will be concatenated with the previous value, if the user clicked on plus operation the given value in the text field will be memorised till the user gives a new value and click on equal
Operation.
Fiddle
var value1=value2=result=0;
function calc(val) {
value1= parseInt(document.getElementById(val).value);
document.getElementById("textBox").value=document.getElementById("textBox").value+value1;
value1=parseInt(document.getElementById("textBox").value);
}
function DoSumm(){
document.getElementById("textBox").value="";
value2=value1;
value1=0;
}
function FindResult(){
result=value1+value2;
alert(result);
document.getElementById("textBox").value=result;
}
<table>
<tr>
<td>
<input type="text" id="textBox" size="5"/>
<br/><br/>
</td>
</tr>
<tr>
<td>
<input type="button" id="btnone" value=" 1 " OnClick="calc(this.id)"/>
<input type="button" id="btntwo" value=" 2 " OnCLick="calc(this.id)"/>
<input type="button" id="btnthree" value=" 3 " OnClick="calc(this.id)"/>
<br/>
<input type="button" id="btnfour" value=" 4 " OnClick="calc(this.id)"/>
<input type="button" id="btnfive" value=" 5 " OnCLick="calc(this.id)"/>
<input type="button" id="btnsix" value=" 6 " OnClick="calc(this.id)"/>
<br/>
<input type="button" id="btnseven" value=" 7 " OnClick="calc(this.id)"/>
<input type="button" id="btneight" value=" 8 " OnCLick="calc(this.id)"/>
<input type="button" id="btnnine" value=" 9 " OnClick="calc(this.id)"/>
<br/>
<input type="button" id="btnzero" value=" 0 " OnClick="calc(this.id)"/>
<input type="button" id="btneql" value=" = " OnClick="FindResult()"/>
<input type="button" name="plus" value=" + " OnClick="DoSumm()"/>
<br/>
</td>
</tr>
</table>
You should post the related HTML, otherwise we have to reverse engineer it. Anyhow, perhaps you have something like:
<form>
<input type="button" id="btnone" name="btnone" value="0">
<br>
<textarea name="textBox"></textarea>
<br>
<input type="button" id="btntwo" name="btntwo" value="0">
<br>
<input type="button" id="btnadd" name="btnadd" value="Add">
<br>
<input type="button" id="btneql" name="btneql" value="Equal">
<br>
<input type="text" readonly name="result">
</form>
In your function you have:
window.onload = function () {
var value1 = "", value2 = "", result="";
Variables don't have a type in javascript, so there's no point in initialising them to a value unless you intend to actually use it, so:
var value1, value2, result;
Then there is:
document.getElementById('btnone').addEventListener('click', function () {
document.getElementById('textBox').value = document.getElementById('textBox').value + document.getElementById('btnone').value;
value1 = document.getElementById('textBox').value;
});
All that code for so little work! If you add a listener using addEventListener, then the element will be this within the function. Also, you can use the names of form controls to reference them as named properties of the form, so:
var textBox = this.form.textBox;
textBox.value = textBox.value + this.value;
You don't say what the value of btnone is (I've assumed it's zero), but in any case it will be a string, as will the value of the text box. So you need to convert them to Numbers, otherwise + will do concatenation not addition. The easy way is to use the unary + operator, so:
textBox.value = +textBox.value + +this.value;
Then you do:
value1 = document.getElementById('textBox').value;
So value1 is a string again, so do it in the other order:
value1 = +textBox.value + +this.value;
textBox.value = value1;
And keep going… The code looks quite turgid and I don't really know if the following does what you're trying to do (particularly the listener on the btnadd element), at least it "works":
window.onload = function () {
var value1 = "", value2 = "", result="";
document.getElementById('btnone').addEventListener('click', function () {
var textBox = this.form.textBox;
value1 = +textBox.value + +this.value;
textBox.value = value1;
});
document.getElementById('btntwo').addEventListener('click', function () {
var textBox = this.form.textBox;
value2 = +textBox.value + +this.value;
textBox.value = value2;
});
document.getElementById('btnadd').addEventListener('click', function () {
var textBox = this.form.textBox;
textBox.value = value1 + value2;
});
document.getElementById('btneql').addEventListener('click', function () {
result = value1 + value2;
this.form.result.value = result;
});
};
Related
Question:- i have write a code but it print values only once and i want to print value line by line nextupon the old value like a post ok?
var post = []
function getVal() {
// creating varable val for select all input data.
const val = document.querySelector('input').value;
document.getElementById('input').value = "";
console.log(val);
//store data in an array for print.
post.push(val)
//call for print the input value in span tag
document.getElementById('print1').innerHTML = val
console.log(post);
}
<input id="input" class="inp" type="text" name="textbox">
<button id="btn" class="postbutton" type="button" name="button" onclick="getVal()">Post</button>
<span id="print1"></span>
You can try using join , just adjust one line of code
replace
document.getElementById('print1').innerHTML = val
with
document.getElementById('print1').innerHTML = post.join('<br/>');
var post = []
function getVal() {
// creating varable val for select all input data.
const val = document.querySelector('input').value;
document.getElementById('input').value = "";
//store data in an array for print.
post.push(val)
//call for print the input value in span tag
document.getElementById('print1').innerHTML = post.join('<br/>');
}
<input id="input" class="inp" type="text" name="textbox">
<button id="btn" class="postbutton" type="button" name="button" onclick="getVal()">Post</button>
<br/>
<span id="print1"></span>
Replace the following line of function getVal()
document.getElementById('print1').innerHTML = val
With
document.getElementById('print1').innerHTML += val + "<br>"
var post = []
function getVal() {
// creating varable val for select all input data.
const val = document.querySelector('input').value;
document.getElementById('input').value = "";
console.log(val);
//store data in an array for print.
post.push(val)
//call for print the input value in span tag
document.getElementById('print1').innerHTML += val + "<br>"
console.log(post);
}
<input id="input" class="inp" type="text" name="textbox">
<button id="btn" class="postbutton" type="button" name="button" onclick="getVal()">Post</button>
<span id="print1"></span>
I have a form that looks like this:
<form action="/a1/configurer/1" method="post">
<label>Fill out a revenue (such as "salary")</label>
<input type="text" name="revenu_0[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_0[amount]">
Add revenus
In this add_field() function I want to add this :
<label>Fill out a revenu</label>
<input type="text" name="revenu_1[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_1[amount]">
And when clicking the button again, name is "revenu_2" and so on (incrementing).
I have tried this:
function add_field() {
i = 1;
var extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
i = i + 1;
document.getElementsByTagName('body')[0].appendChild(extra);
}
That's only a very small part of the solution and obviously, this doesn't increment.
How do I do this?
You are pretty close. The important piece you're missing is to make sure i is declared outside the add_field function scope. Then, each time you call the function, the previous value of i will be persisted in the outer scope. See below for a working example.
let i = 1;
function add_field() {
const extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
extra.setAttribute("placeholder", "Field " + i);
document.getElementsByTagName('form')[0].appendChild(extra);
i = i + 1;
}
<button onclick="add_field()">Add field</button>
<form></form>
Solution #1
var i = 1;
btn.onclick = () => {
var label = document.createElement('label'),
input = document.createElement('input'),
br = document.createElement('br');
label.innerHTML = 'Label text ';
input.type = 'text';
input.name = 'revenu_' + i + '[category]';
input.placeholder = 'Field #' + i;
myForm.appendChild(label);
myForm.appendChild(input);
myForm.appendChild(br);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Solution #2
var i = 1;
btn.onclick = () => {
var add = `
<label>Fill out a revenu</label>
<input type="text" name="revenu_${i}[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_${i}[amount]">
<br>
`;
myForm.insertAdjacentHTML('beforeend', add);
console.log(add);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Notice that in both cases:
button must have id="btn";
form must have id="myForm".
Obviously, if you change those ids in the HTML code, you need to change them in the JS code as well.
I am trying to create, at max, 8 buttons and I am successful at that, but I want to give the values to the buttons as A, B, C and so on..
Here is the code that I have done so far:
var buttonValue = 1;
function addButton(){
if(buttonValue <=8){
var targetDiv = document.getElementById('targetDiv');
var inputField = document.createElement('INPUT');
inputField.setAttribute('type','button');
inputField.setAttribute('id',"input-"+buttonValue+"");
inputField.setAttribute('class','controls');
targetDiv.append(inputField);
}
buttonValue++;
}
but I want to give the values to the buttons as A, B, C and so on.
The character code for A is 65 ("A".charCodeAt(0)). So you can use String.fromCharCode to create your values by adding buttonValue - 1 to 65:
inputField.setAttribute("value", String.fromCharCode(65 + buttonValue - 1));
// or
inputField.defaultValue = String.fromCharCode(65 + buttonValue - 1);
// or
inputField.value = String.fromCharCode(65 + buttonValue - 1);
// See below for details on .value vs. .defaultValue
BTW, you can save a fair bit of typing by using the reflected properties for the type, id, and class attributes:
inputField.type = 'text';
inputField.id = "input-" + buttonValue;
inputField.className = 'controls';
// ^^^^^^^^^ Note the slightly-different name
(Also note that +"" is unnecessary in your id code.)
For value, it's a bit complicated:
.value = ... sets the current value of the input, which is not the same thing as the value attribute
The value attribute sets the default value of the input, not its current value.
The reflected property for the value attribute is defaultValue, not value
You could convert the value to a string, with an offset.
BTW, you need a while loop for getting all buttons and you need appendChild to append the button to the div.
What you get
<div id="targetDiv">
<input id="input-1" type="button" value="A">
<input id="input-2" type="button" value="B">
<input id="input-3" type="button" value="C">
<input id="input-4" type="button" value="D">
<input id="input-5" type="button" value="E">
<input id="input-6" type="button" value="F">
<input id="input-7" type="button" value="G">
<input id="input-8" type="button" value="H">
</div>
function addButton() {
var buttonValue = 1,
targetDiv = document.getElementById('targetDiv'),
inputField;
while (buttonValue <= 8) {
inputField = document.createElement('input');
inputField.type = 'button';
inputField.id = "input-" + buttonValue;
inputField.value = (buttonValue + 9).toString(36).toUpperCase();
targetDiv.appendChild(inputField);
buttonValue++;
}
}
addButton();
<div id="targetDiv"></div>
I have a global variable :
var a;
I put my onclick function into my html div in concatenation PHP :
$number =' <div onclick="select(this,'."'250000'".');" > ';
$number .= ...etc... //php function
$number .='</div>';
to insert string into div value onclick (button) :
function select (price){
if ($(id).attr('class') == "table2") { //unselect button
$(id).attr('class', 'table1');
var price2=document.getElementById("price").value.split(",");
var removePrice = price;;
var price3 = jQuery.grep(price2, function (value) { return value != removePrice;});
document.getElementById("price").value = price3;
if (n.length == 0) i = 0;
} else {
$(id).attr('class', 'table2'); //select button
if (i == 0) {
document.getElementById("price").value = price;
a = Number(document.getElementById("price").value); //assign the value into a
i = 1;
} else {
$(id).attr('class','table3');
}
}
From there, I have checkbox HTML :
<div id="CourseMenu"><input type="checkbox" value="50000" />  Ekstra Bed <input type="checkbox" value="50000" />  Breakfast</div>
After that I have another function to sum 2 div value (checkbox) :
$(function($) {
var sum = 0;
$('#CourseMenu :checkbox').click(function() { sum = 0;
$('#CourseMenu :checkbox:checked').each(function(idx, elm) {
sum += parseInt(elm.value, 10);
});
var b = parseInt(a||0, 10) + parseInt(sum||0, 10);
$('#sum').html(b); //<--resulted NaN when sum with button
document.getElementById("price").value=b; //<-- assign b as div value
});
});
The purpose is to sum the total price (button & checkbox) into div value
<input type="hidden" id="price" name="price" value="" />
it works fine when the function sum only the checkbox, but when I try to show the sum with the button (global variable) it resulted in NaN
I think I already convert the string into number there, is there something wrong with my code?
I think you have a problem in passing the arguments in onclick event:
onclick="select(this,'250000');" => passing this as first argument try changing to onclick="select('250000')";
but your select function is expecting string as the first argument:
function select(price){ //<-- simplified
document.getElementById("price").value=price;
a = Number(document.getElementById("price").value);
}
Here is an actual solution for your X/Y problem.
The code will initialise the field and clicking buttons or checking checkboxes work independently.
function calc() {
var sum = parseInt($("#price").text(), 10);
$('#CourseMenu :checkbox:checked').each(function() {
sum += parseInt(this.value, 10);
});
$('#sum').val(sum);
}
$(function() {
$("#CourseMenu .btn").on("click", function() {
$("#price").text($(this).data("price")); // using the data attribute
calc();
});
$('#CourseMenu input:checkbox').on("click",function() {
calc(); //
});
calc(); // initialise in case the page is reloaded.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="CourseMenu">
<button type="button" class="btn" data-price="25000">25000</button>
<button type="button" class="btn" data-price="35000">35000</button>
<div id="price">0</div>
<br/>
<label>
<input type="checkbox" value="200" />200</label>
<label>
<input type="checkbox" value="300" />300</label>
<label>
<input type="checkbox" value="400" />400</label>
<br/>
<input type="text" id="sum" value="" />
</form>
PS: If you do nothing else on click of checkboxes, you can write
$('#CourseMenu input:checkbox').on("click",calc);
I'm trying to get a value from a function and then use it in other function but I'm not being able to do it...
the first function unidadesTotalCalculate fetches values from two inputs and then multiply them and prints it to an element.
This same function runs 3 times with different elements and then I need to to SUM the result of those three and print it to another element. This is second function, totalBarUpdateStandard().
Can you help me figuring out what is happening? I can't get the value from each function and use it.
function unidadesTotalCalculate(unidadeID, rangeID, print) {
var value = unidadeID.val();
var rangevalue = rangeID.val();
var valueSUM = value * rangevalue;
jQuery(print).text(valueSUM + '€');
return valueSUM;
}
function totalBarUpdateStandard() {
var value1 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-dialise-unidades'), jQuery('#doenteagudo-standard-dialise-range'), '#doenteagudo-standard-dialise-total');
var value2 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasma-unidades'), jQuery('#doenteagudo-standard-plasma-range'), '#doenteagudo-standard-plasma-total');
var value3 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasmaferese-unidades'), jQuery('#doenteagudo-standard-plasmaferese-range'), '#doenteagudo-standard-plasmaferese-total');
var valueTotal = value1 + value2 + value3;
jQuery('#demo').text(valueTotal + '€');
}
Below is a your solution to your scenario, hope it helps you, I think jQuery(print).text(valueSUM + '€'); was the cause of your problem ... it should be jQuery(print).val(valueSUM + '€') .. just put it an static HTML and test it
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<input id="doenteagudo-standard-dialise-unidades" value="2" />
<input id="doenteagudo-standard-dialise-range" value="2"/>
<input id="doenteagudo-standard-dialise-total" />
<input id="doenteagudo-standard-plasma-unidades" value="2" />
<input id="doenteagudo-standard-plasma-range" value="2"/>
<input id="doenteagudo-standard-plasma-total" />
<input id="doenteagudo-standard-plasmaferese-unidades" value="2" />
<input id="doenteagudo-standard-plasmaferese-range" value="2" />
<input id="doenteagudo-standard-plasmaferese-total" />
<div id="demo"></div>
<button id="t"></button>
<script>
function unidadesTotalCalculate(unidadeID, rangeID, print) {
var value = unidadeID.val();
var rangevalue = rangeID.val();
var valueSUM = value * rangevalue;
jQuery(print).val(valueSUM + '€');
return valueSUM;
}
function totalBarUpdateStandard() {
var value1 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-dialise-unidades'), jQuery('#doenteagudo-standard-dialise-range'), '#doenteagudo-standard-dialise-total');
var value2 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasma-unidades'), jQuery('#doenteagudo-standard-plasma-range'), '#doenteagudo-standard-plasma-total');
var value3 = unidadesTotalCalculate(jQuery('#doenteagudo-standard-plasmaferese-unidades'), jQuery('#doenteagudo-standard-plasmaferese-range'), '#doenteagudo-standard-plasmaferese-total');
//console.log(value1);
//console.log(value2);
//console.log(value3);
var valueTotal = value1 + value2 + value3;
jQuery('#demo').text(valueTotal + '€');
}
</script>
</body>
</html>
you should use val() method of jQuery to get the value of the field.
Thanks