2016-10-02 67 views
-4

如果我有一个按钮和一个输入字段。点击按钮时,我将如何警告用户输入字段中的任何内容。如何提醒文本框输入给用户

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

+0

不仅仅是谷歌的onclick事件的人... –

+0

你尝试了什么? –

+0

当使用onclick事件时,只要我点击它,我就可以使按钮提醒我选择的消息。但我不知道如何使它在输入框中提醒什么 –

回答

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> 
+0

谢谢。我通读它并理解它。我的问题是我不知道函数document.getElementById。需要了解更多html/js。 –

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> 

有了你可以单独responsabilities第二种方法,一个人可以创建德HTML,和另一个人可以专注在创建JavaScript代码。

已存在几种方法可以做到这一点,但有两个例子,我认为是足以在目前情况下

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在帖子中被标记,我用它来获取文本框中的内容。

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