2016-10-02 68 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