```where, `type="text"` represents the input box type For text, `id="inp"> JAVAscript input integers and sum-Front-end Q&A-php.cn

JAVAscript input integers and sum

PHPz
Release: 2023-05-12 15:50:39
Original
1076 people have browsed it

JavaScript is a programming language widely used in Web development. It can facilitate the development and interaction of front-end pages. Today we will learn how to input integers and sum them in JavaScript.

In JavaScript, you can create a text input box on a web page through the following code:

Copy after login

Among them,type="text"indicates that the input box type is text,id="inputNum"Indicates that the identifier of the input box is "inputNum", which is convenient for later calling in JavaScript.

Next, we need to create a summation function, which can be implemented through the following code:

function sum() { var input = document.getElementById("inputNum").value; // 获取输入框中的值 var nums = input.split(","); // 将输入的字符串以逗号为分隔符拆分成数字数组 var total = 0; for (var i = 0; i < nums.length; i++) { total += parseInt(nums[i]); // 将数组中的每个元素转换为整数并累加 } alert("总和为:" + total); // 弹出提示框显示结果 }
Copy after login

In the above code,document.getElementById("inputNum")Indicates getting the element whose id is inputNum,.valuemeans getting the value entered in the element.input.split(",")means splitting the input string into a numeric array using commas as delimiters.total = parseInt(nums[i])means converting each element in the array to an integer and accumulating it. Finally, a prompt box pops up to display the calculation results through thealertfunction.

Finally, we need to create a button in the web page. When the user clicks the button, the sum function written above is called. The following is the complete code:

         输入整数并求和
         
Copy after login

In the above code,onclick="sum()"means that the summation functionsum()is called when the user clicks the button . Enter several numbers on the page, separated by commas, and click the "Sum" button to get their sum.

The JavaScript method for inputting integers and summing them is very simple and can be easily implemented through the above code. In actual web development, we can modify and optimize it as needed to achieve more complete functions.

The above is the detailed content of JAVAscript input integers and sum. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!