如何从文本框中获取字符串并在javascript中显示在页面中

时间:2014-09-29 17:54:16

标签: javascript string

我是javascript的新手,我有一个函数获取文本框值并将其返回,但我无法使用函数外的返回值。我希望函数返回一个字符串并在网页中显示它。以下是代码。

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<!DOCTYPE html>
<html>
<head>
<title> Inventory test </title>
</head>
<body>

<script type="text/javascript">

function function1(){

     var x = document.getElementById("text1").value;

     if (x.length == ""){
         alert ( "input is empty");
     }else{
         alert ( x + " " + "fine"); 
         return x;
     }
 }

</script>

First name: <input type="text" id="text1" name="text1" autofocus>

<button onclick="function1()"> submit </button>

<p id="p1">p1</p> 


</body>
</html>

4 个答案:

答案 0 :(得分:0)

而不是返回,只需直接指定您想要的内容,例如,使用

document.getElementById("p1").innerHTML = x

答案 1 :(得分:0)

您应该将文本输入的值设置为dom元素

function function1() {
    document.getElementById("p1").innerHTML = document.getElementById("text1").value;
}

答案 2 :(得分:0)

function function1()
{

 var x = document.getElementById("text1").value;

  if (x.length == "")
   {
    alert ( "input is empty");
   }
    else
   {
     alert ( x + " " + "fine"); 
   document.getElementById("p1").innerHTML = x;

 }

答案 3 :(得分:0)

试试这个

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<!DOCTYPE html>
<html>
<head>
<title> Inventory test </title>
</head>
<body>

<script type="text/javascript">

function function1(){

     var textValue = document.getElementById("text1").value;

     if (x.length == ""){
         alert ( "input is empty");
     }else{
         document.getElementById("p1").innerHTML = textValue;
     }
 }

</script>

First name: <input type="text" id="text1" name="text1" autofocus>

<button onclick="function1()"> submit </button>

<p id="p1">p1</p> 


</body>
</html>