Member Avatar

Hi all. I have this code:

<html>
<title>
</title>
<head>
<script>
function add(){
var first=document.getElementById("form").value;
var second=[first];
for (i=0;i<second.length;i++){


var third=second.join("+");

}
document.one.answer.value=third;
}
</script>
</head>
<body>

<input type="text" id="form" onChange="add()"/>
<form name="one">
<input type="text" name="answer"/>
</form>
</body>
</html>

What I want to do is allow the user to enter an array of numbers (say 4,5,6) and eventually create a code that will take those numbers and do something with them (add them together, pass them to something else or just display them). I can't figure out why it won't work with join() but when I use split(), it seems to work well. Thoughts?

Recommended Answers

Hi,
Try somthing like this:

<script type="text/javascript">
        function add(){
            var first = document.getElementById("form").value;
            //The values will be separated by comma
            var second = first.split(",");
            var third = second.join(" + ");
            var x = eval(third);
            document.one.answer.value = third+" = "+x;
        }
    </script>

Change only the script. The values in …

Jump to Post

All 2 Replies

Hi,
Try somthing like this:

<script type="text/javascript">
        function add(){
            var first = document.getElementById("form").value;
            //The values will be separated by comma
            var second = first.split(",");
            var third = second.join(" + ");
            var x = eval(third);
            document.one.answer.value = third+" = "+x;
        }
    </script>

Change only the script. The values in first fields will be write separated by comma.

Member Avatar

Very nice. Now if I can only remember what I was going to use it for, I'll be great. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.