2016-03-09 252 views
0

我正在嘗試編寫一個簡單的小部件來衡量Net Promoter Score。這是我到目前爲止:使用JavaScript提交HTML,提交按鈕

<!DOCTYPE html> 
<html> 
<body> 
<link type="text/css" rel="stylesheet" href="NPSstyle.css"/> 
    <h1>Net Promoter Score<h1> 
     <p class="question">How likely are you to recommend this tool to a friend or colleague?</p> 
<form id="myForm"> 

    <button type="button" id="button1">1</button> 
    <button type="button" id="button2">2</button> 
    <button type="button" id="button3">3</button> 
    <button type="button" id="button4">4</button> 
    <button type="button" id="button5">5</button> 
    <button type="button" id="button6">6</button> 
    <button type="button" id="button7">7</button> 
    <button type="button" id="button8">8</button> 
    <button type="button" id="button9">9</button> 
    <button type="button" id="button10">10</button> 
    <button type="submit" class="input submit">Submit</button> 
</form> 
<p class="explanation">Not likely............................................................Very likely</p> 


<script> 

var userRating 

document.getElementById('button1').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 1; 
} 
document.getElementById('button2').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 2; 
} 
document.getElementById('button3').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 3; 
} 
document.getElementById('button4').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 4; 
} 
document.getElementById('button5').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 5; 
} 
document.getElementById('button6').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 6; 
} 
document.getElementById('button7').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 7; 
} 
document.getElementById('button8').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 8; 
} 
document.getElementById('button9').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 9; 
} 
document.getElementById('button10').onclick = function() { 
    console.log(this.id + " was clicked") 
    userRating = 10; 
} 


</script> 

我目前正試圖弄清楚如何獲得提交工作。我希望用戶按下代表他們分數的按鈕,然後按提交以註冊他們的分數。現在,我只希望他們的分數在提交時顯示在控制檯中,但最終會被保存到服務器,這只是一個在瀏覽器中彈出屏幕的小部件。我開始在真空中做這件事來幫助自己學習。我希望有人指出我正確的方向或給我一個提示。這是我第一次嘗試JavaScript,所以我仍然在學習。謝謝!

+0

你的問題的信息不夠詳細。分數如何登記?你需要將分數提交給服務器嗎?你想觸發一個頁面加載,或者你想要在後臺發生?等 – Comptonburger

+0

我剛剛編輯我的問題更清楚,對不起! – Spance

+0

爲什麼你不使用單選按鈕進行選擇? – Barmar

回答

1

以與將onclick處理程序添加到按鈕的相同方式,您可以將onsubmit處理程序添加到窗體。

document.getElementById('myForm').onsubmit = function() { 
    console.log(userRating); 
}