简体   繁体   中英

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.

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';">

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

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

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 "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM