2017-02-17 68 views
1

我想從所選單選按鈕拉idvalue。我在幾個職位,我碰到博客跨越這種風格的代碼來了,決定給它在角2用於從所選單選按鈕不起作用拉ID和值的腳本

var radios = document.getElementsByName('genderS'); 

for (var i = 0, length = radios.length; i < length; i++) { 
    if (radios[i].checked) { 
     // do whatever you want with the checked radio 
     alert(radios[i].value); 

     // only one radio can be logically checked, don't check the rest 
     break; 
    } 
} 

了一槍這是從這裏Get Radio Button Value with Javascript

我的方式摘錄努力實現它在我的角類是這樣

selected = {value1: '', value2: ''}; //where I want the results to be stored. 

//custom function with the snippet implemented 
getSelected() { 
    const radios = document.getElementsByName(this.quesForm.value.name); 

    for (var i = 0, length = radios.length; i < length; i++) { 
     if (radios[i].click){ 
      this.selected.value1 = radios[i].getAttribute("id"); 
      this.selected.value2 = radios[i].getAttribute("value"); 
      break; 
     } 
    } 
} 

//calling it here in an attempt to make sure it detects when the selection changes. 
ngOnChanges() { 
    this.getSelected(); 
    console.log(this.selected); 
} 

我的模板設置這樣

<div *ngFor="let ans of quesForm.value.answers"> 
    <input type="radio" 
     [attr.name] = "quesForm.value.name" 
     [attr.id] = "ans.id" 
     [attr.value] = "ans.answer" 
    /> 
    <label>{{ans.answer}}</label> 
</div> 

我沒有收到任何錯誤,但我也沒有看到任何結果日誌,我還在form標記之外顯示了結果以及保持空白的結果。

<p>{{selected | json}}</p> 

爲什麼不是這方面的工作?

回答

1

使用數據綁定和DOM事件,如:

模板:

<div *ngFor="let ans of quesForm.value.answers"> 
    <input type="radio" 
     [attr.name] = "quesForm.value.name" 
     [attr.id] = "ans.id" 
     [attr.value] = "ans.answer" 
     (click)="selectAnswer(ans)" 
    /> 
    <label>{{ans.answer}}</label> 
</div> 

組件:

selectAnswer(ans) { 
    this.selected = ans; 
    console.log(this.selected); 
} 

在角2訪問DOM直接爲generally bad practice,通常表示一個問題你設計。

+0

我該如何從選定的輸入中獲取值和ID? – Optiq

+0

它在回答對象 – shusson

+0

好吧,從來沒有想過我只是想出了大聲笑謝謝! – Optiq