2016-05-04 65 views
2

我想在一個函數中向用戶提出一系列問題。Javascript prompt()alternative - 等待用戶響應

如果我使用prompt(),可以在一個函數中提出所有問題。

function question(){ 
    var name = prompt("Enter your name"); 
    var age = prompt("Enter your age"); 
} 

但是,如果我嘗試使用輸入的標籤,這是不可能的。

function question(){ 
    document.write("Enter your name"); 

    // you can't wait until the user responds. It will simply execute all the lines at once. 

    name = document.getElementById("input").value; 
    document.write("Enter your age"); 
    age = document.getElementById("input").value; 
} 

如果我這樣做,我不能使用輸入標籤在一個函數中向用戶提問。我如何等待用戶回覆?

回答

1

除第一個輸入框外,您可以保持禁用所有輸入框。第二個可以在用戶對第一個響應時啓用。輸入行將繼續這樣。

這是一個小示範。請注意,這只是一個示例代碼,向您展示了設計模式。

<input id="name"></input> <button onClick="getInput()">Ok</button> 

<input id="address"></input> <button onClick="getInput()" disabled>Ok</button> 

和JS

var name, address; 

functon getInput() { 

    name = document.getelementById("name").value; 
    address = document.getElementById("address").value; 

    if (address !== "") 
     document.getElementById("address").removeAttribute("disabled"); 

} 

有很多種方法,提前比這可在JS。但可能你應該先研究這種模式。

0

你不能從一個函數中的相同輸入中取2個不同的值。你應該創建另一個輸入或一些按鈕來區分變量。例如:` 輸入您的姓名 輸入您的年齡 保存 VAR BSAVE = window.document.getElementById( 'BSAVE'); bSave.addEventListener(「click」,question);

var newName = window.document.getElementById('iName'); 
    var newAge = window.document.getElementById('iAge'); 

    function question() { 
     name=newName.value; 
     age=newAge.value; 
    } 
</script> 

`

0

document.write()是不是要求用戶輸入像prompt()寫HTML。你需要的是在用戶提交表單之前輸入驗證,如

function checkQuestion(){ 
    if(document.getElementById("name").value == "") 
    alert('name empty'); 
    if(document.getElementById("age").value == ""); 
    alert('age empty'); 
}