Need to copy items of a list to text box
I want to create a selection list. When an item on the list is clicked same should be showing in a text box, when another item is clicked even that should be added to text box. I am trying to work out the code below but somehow its not doing its job. Any help will be highly appreciated.
<html>
<head>
<script type="text/javascript">
function register_click(num){
document.getElementById('boxclicked').value += num;
}
</script>
</head>
<body>
<td><ul>
<li id="2" onclick="register_click(1)">List item 1</li>
<li id="3" onclick="register_c开发者_Python百科lick(2)">List item 2</li>
<li id="4"onclick="register_click(3)">List Item 3</li>
</ul></td>
<input type='text' size="150%" width="100%" maxlength="" id="boxclicked">
</body>
</html>
I'm assuming that you want to do arithmetic, but you're function is actually doing string concatenation. For arithmetic you need to make sure that any 'number' is actually a number and not a string:
function register_click(num){
var box = document.getElementById('boxclicked');
box.value = box.value || 0
box.value = parseInt(box.value, 10) + num;
}
box.value
will be undefined on first click, so we make sure that it has a value, even if that value is 0
. parseInt converts a string to a number, we pass 10
to make sure that it does it in base 10.
JavaScript is funny sometimes, for instance:
"1" + 2 + 3 === "123" // true
2 + 3 + "1" === "51" // true
It always tries to coerce types, sometimes this is good, but it can lead to confusion like the above, when it works counter-intuitively. This is what you were running into with your original code. The value of the element was a string, which caused num
to become a string and be concatenated.
精彩评论