如何警告文本框输入给用户

时间:2016-10-02 20:55:37

标签: javascript jquery html

如果我有一个按钮和一个输入字段。当单击按钮时,如何向用户发出输入字段中的任何内容。

请解释您的代码。 尽可能简单。

4 个答案:

答案 0 :(得分:0)

<input type="text" id="input" />
<button onclick="displayEnteredText()">Display</button>
<script>
  function displayEnteredText() {
    var inputText = document.getElementById("input"); // get the element with id "input" which is the textField
    alert(inputText.value); // show the value of the input in alert message
  }
</script>

答案 1 :(得分:0)

一种可能的方法:

<!DOCTYPE html>
    <html>
    <head></head>
    <body>
     <input id="name" value="">
     <input type="button" value="show me the name" onclick="alert(document.getElementById('name').value)">
    </body>
    </html>

另一种可能的方法:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        window.onload = function () {
            var buttonElement = document.getElementById('button');
            buttonElement.addEventListener('click', function() {
                alert(document.getElementById('name').value);
            });
        }
    </script>

</head>
<body>
 <input id="name" value="">
 <input id="button" type="button" value="show me the name">
</body>
</html>

使用第二种方法,您可以分离责任,一个人可以创建de html,另一个人可以专注于创建javascript代码。

有几种方法可以做到这一点,但我认为在当前背景下有两个例子就足够了

答案 2 :(得分:0)

<body>
<input type="text" name="basicText" id="alertInput">
<button class="alertButton">Click me!</button>
</body>

<script type="text/javascript">


    $(".alertButton").click(function(){
        var value = $("#alertInput").val();
        alert(value + " was entered");
    });
</script>

为了显示您在警报中输入的内容,您需要引用文本框中的值。由于jquery在帖子中被标记,我用它来获取文本框中的内容。

答案 3 :(得分:0)

您也可以试试这个

<强> HTML

<input type="button" id="btnclick" style="width:100px" value="Click Me" />
<input type="text" id="txtbox">

<强> JS

$("#btnclick").click(function(){
var txtvalue = $("#txtbox").val();
alert("User enter " + txtvalue);
})

FIDDLE