As I am new to JavaScript. I want to make a calculator, but I am stuck on getting button value into field. Suppose I have following button
<input id='add' type='button' onclick='ik();' value='1'>
and following field
<input type='text' id='one' class='fld'>
Hope I'll get clear with you replies...
As I am new to JavaScript. I want to make a calculator, but I am stuck on getting button value into field. Suppose I have following button
<input id='add' type='button' onclick='ik();' value='1'>
and following field
<input type='text' id='one' class='fld'>
Hope I'll get clear with you replies...
Share Improve this question edited Jul 21, 2016 at 18:42 Anthony Forloney 91.9k14 gold badges118 silver badges116 bronze badges asked Jul 21, 2016 at 18:41 ParamParam 11 gold badge1 silver badge2 bronze badges 3- thanks @AnthonyForloney – Param Commented Jul 21, 2016 at 18:45
- 1 Google it. You will find solution. – neer Commented Jul 21, 2016 at 18:52
- check out my updated code – Mojtaba Commented Jul 21, 2016 at 18:56
5 Answers
Reset to default 7You can customize it in anyway you want.
function ik(val){
document.getElementById('one').value = val;
}
<input id='add' type='button' onclick='ik(this.value);' value='1'>
<input type='text' id='one' class='fld'>
And, if you want to add to the current value:
function ik(val){
result = document.getElementById('one');
result.value = result.value? parseInt(result.value) + parseInt(val) : parseInt(val);
}
<input id='add' type='button' onclick='ik(this.value);' value='1'>
<input type='text' id='one' class='fld'>
While i can't see your code for some reason, if you included any in your post, here would be one way to achieve what you are describing:
var input = document.querySelector("#your-input-id")
var buttons = document.querySelectorAll("button.number-button")
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function(event) {
input.value = input.value + event.currentTarget.value
})
}
<input id="your-input-id" type="text" value="" />
<button class="number-button" value="2">2</button>
<button class="number-button" value="3">3</button>
This should do the trick =)
$(function () {
$("#add").on("click", function () {
$("#one").val($(this).val());
});
});
I would simply just do this.
$("#add").click(function() {
$("#one").val($(this).val());
});
You can also see it work here. https://jsfiddle/8uc66vsp/
Try This
<input type='text' id='one' class='fld'>
<input id='add' type='button' onclick='ik($(this).val());' value='1'>
<script>
function ik(str){
$("#one").val(str);
}
</script>