gnubala
gnubala

Reputation: 103

How can I concatenate value in HTML and JavaScript?

For example

<input type="text" name="disp">
<input type="button" name="but0" value="0" onclick=""+"calc.disp.value=0"+"">

Here if I click the button 0 means it should display the 0 in text box. If I click the button it should concatenate in that box. But it replaces that is the code is wrong.

Upvotes: 2

Views: 16379

Answers (4)

vishnu
vishnu

Reputation: 1

var sum = document.getElementById("id1").value 
    + document.getElementById("id2").value 
    + document.getElementById("id3").value;

Upvotes: 0

Luke Duddridge
Luke Duddridge

Reputation: 4347

If you are allowed to use jQuery I would suggest that as the code needed then becomes a lot easier to see what is going on:

First add an id attribute to each input.

<input type="text" name="disp" id="textBox">
<input id="button0" type="button" name="but0" value="0">

you want to add 0s? so if you entered 1 then you hit the 0 button it will show 10 then again will change to 100:

<script type="text/ecmascript">
$(document).ready(function()
{
  $("#button0").click(function()
  {
    var textVal = $("#textBox").val();
    $("#textBox").val(textVal + 0);
  });
});
</script>

Example here

Upvotes: 1

Ankur
Ankur

Reputation: 111

Hi you can do it by following way

<input type="text" name="tst" id="tst">
<input type="button" value="0" onclick="javascript:document.getElementById('tst').value = document.getElementById('tst').value + this.value "

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

As far as I understand it, you want each button click to add 0 to the text box contents. So it starts out empty, and when you push the button the first time, the contents changes to 0. Pushing it a second time changes the contents to 00.

Assuming that's correct, try this:

<input type="text" name="disp">
<input type="button" name="but0" value="0" onclick="calc.disp.value=calc.disp.value + '0';">

Upvotes: 5

Related Questions