2017-04-20 42 views
0

如何在html中輸入th的值?我的問題在第五,它不會得到輸入的價值。看到我的JavaScript代碼。任何人都知道解決這個問題的想法嗎?這段代碼很好,但是當我在內部添加輸入字段時,它不起作用。我在這裏錯過了什麼?有沒有可能的方法來實現我的目標?注意:我只需要輸入第五個。使用javascript獲取th標籤內的輸入值

<tr>     
    <th colspan="3">Learning Areas</th> 
    <th colspan="2">Term 1</th> 
    <th colspan="2">Term 2</th> 
    <th colspan="2">Term 3</th> 
    <th colspan="2">Term 4</th> 
    <th>Ave</th> 
</tr> 
</thead> 
<tbody> 
@foreach($card['AllGrade'] as $subject) 
      {!! Form::hidden('grade_id[]',$subject['grade_id']) !!} 
    <tr> 
     <th colspan="3">{!! $subject->subject !!}</th> 
     <th colspan="2">{!! $subject->term_1 !!}</th> 
     <th colspan="2">{!! $subject->term_2 !!}</th> 
     <th colspan="2">{!! $subject->term_3 !!}</th> 
     <th colspan="2"><input text="term_4" value="{!! $subject->term_4 !!}" class="form-control" name="term_4"></th> 

     <th colspan="2" name ="ave" id ="ave" value=""> total</th> 


     </tr> 
@endforeach 


<script type="text/javascript"> 
$("tbody tr").each(function() { 
    var total = 0; 
    var ave = 0; 
    var count = 1; 
    $(this).children('th').not(':first').not(':last').each(function() { 
     //"this" is the current element in the loop 
     var number = parseInt($(this).html()); 
     total += number; 
     ave = total/count; 
     count++; 

    }); 
    $(this).children('th').last().html(ave); 
}); 
</script> 
+0

不知道你的html是怎麼樣的''。我會更新與呈現的HTML問題。 – GreeKatrina

+0

正如以下,科多索斯先生的回答是正確的。 – Chee

回答

0

在你var number = parseInt($(this).html());,你會得到你的字面上的input html代碼,所以你應該使用其他方法訪問它的價值。

我覺得我應該這樣做,而不是:

$(this).children('th').not(':first').not(':last').each(function() { 
    //"this" is the current element in the loop 
    var number = ($(this).children('input').length == 0) ? $(this).html() : $(this).children('input').first().val(); 
    total += parseInt(number); 
    ave = total/count; 
    count++; 
}); 

它應該工作,因爲現在你正確地訪問它。

+0

是的,這是我想要的。如果term_4中沒有數據,如何在輸入中添加關鍵事件?那麼平均值將立即更新。順便說一句,謝謝你的這個想法。它意味着很多! – Chee

+0

正如你可以看到[這裏](http://stackoverflow.com/a/1207393/6560435),你需要首先爲輸入定義一個名字,並且設置綁定到'change'事件 –

+0

改變,但用戶可以對輸入進行更改,但不會在Ave列中給出值。看看這個:if('。form-control'){(this).on('keyup','td:eq(4)input',function(){('。form-control')。上( 「輸入」,函數(){ VAR dInput = THIS.VALUE; 總+ = parseInt函數(dInput); AVE =總/計數-1; }); 的console.log(AVE) ; $(this).parent()。next()。html(ave); }); } $(this).children('td')。last()。html(ave); – Chee