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_click(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:
box.valuewill be undefined on first click, so we make sure that it has a value, even if that value is0. parseInt converts a string to a number, we pass10to make sure that it does it in base 10.JavaScript is funny sometimes, for instance:
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
numto become a string and be concatenated.