2015-12-15 51 views
0

我試圖構建一個簡單的反饋表單。用戶將回答一系列是或否的問題。如果他們選擇否,那麼他們將被提供評論表格以包括文本。檢索反饋表單的單選按鈕值的問題

目前,我在檢索單選按鈕值時遇到問題。我試圖在控制檯中打印它們,但是當我選擇適當的選項時沒有任何反應。如果用戶選擇「否」,則需要能夠記住將提交的評論。

我的jsfiddle是在這裏:http://jsfiddle.net/787x18vx/

HTML

<p>You are providing feedback</p> 
<form> 
    <div id="question-1"> 
    <label for="question-1">Is this correct?</label> 
    <input type="radio" value="yes" name="choice-1" />Yes 
    <input type="radio" value="no" name="choice-1" />No 
    </div> 
    <div id="question-2"> 
    <label for="question-2">Another question</label> 
    <input type="radio" value="yes" name="choice-2" />Yes 
    <input type="radio" value="no" name="choice-2" />No 
    </div> 
    <div id="question-3"> 
    <label for="question-3">One more question</label> 
    <input type="radio" value="yes" name="choice-3" />Yes 
    <input type="radio" value="no" name="choice-3" />No 
    </div> 
    <br /> 
    <button>Send Feedback</button> 
</form> 

jQuery的

var firstInput = 'input[name=choice]'; 
var firstInputValue = $('input[name=choice-1]:checked').val(); 
$(firstInput).on('click', function() { 
    console.log(firstInputValue); 
    console.log($('input[name="choice-1"]:checked').val()); 
    console.log($('input[name="choice-2"]:checked').val()); 
    // if value === 'no' show comment form 
}); 
+0

http://jsfiddle.net/787x18vx/7/ – brettkc

+0

@brettkc謝謝開頭的所有標籤。我也喜歡這個解決方案... – mapr

回答

1

您正在使用input[name=choice]選擇未exisiting。使用input[type=radio]代替。

var firstInput = 'input[type=radio]'; 
var firstInputValue = $('input[name=choice-1]:checked').val(); 
$(firstInput).on('click', function() { 
    console.log(firstInputValue); 
    console.log($('input[name="choice-1"]:checked').val()); 
    console.log($('input[name="choice-2"]:checked').val()); 
    // if value === 'no' show comment form 
}); 

Fiddle

+0

爲什麼在控制檯打印時第一個值爲undefined?變量似乎不起作用。 – mapr

+0

@mapr因爲您在初始狀態下未設定值的單擊事件外設置'firstInputValue'。 –

+0

@mapr我創建了一個[fiddle](http://jsfiddle.net/787x18vx/8/),其中'firstInputValue'位於onclick事件函數中。此外,這只是解決正確檢索值的答案,它不會顯示三種選擇的所有值。它只顯示第一和第二選擇的值。 –

1

var firstInput = 'input[name=choice]'; 這是名爲choice,它不會出現在你的HTML專門找東西。

有兩個快速的方法。 首先,只要改變你的選擇:

$('input[type=radio]').on('click', function(){... 

這將觸發任何電臺的點擊功能

另一種方法是使用通配符選擇:

var firstInput = 'input[name^=choice]'; 

^應該是因此任何名稱以choice開頭的輸入都會被選中。

這種方法應該可行,但針對input[type=radio]可能是一個更好的解決方案,

+0

我應該使用'onclick'還是'onchange'?如果用戶想要回去改變東西會怎麼樣? – mapr

+0

要麼我會認爲會工作。更改會在初始點擊時觸發,然後在該值不會更改時進行任何點擊。無論何時,點擊都會觸發。這取決於你想要做什麼。 – neilsimp1

0

你缺少-1您的姓名

var firstInput = 'input[name=choice-1]'; 
0

你的選擇正在試圖獲得與名稱完全等於「標籤選擇'。您可以通過前綴以下

var firstInput = 'input[name|="choice"]'; 

這一搜索會得到它的名字與「選擇」