如何获取单元格

时间:2016-04-27 12:51:52

标签: javascript jquery html

我有以下代码

<tr val='question'>
    <td>
        <input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '>
</tr>

如何找到嵌入在单元格中的输入框的值。

function saveUserDefQues(){

var table=document.getElementById("QuestionList");
var surveyquestionform=document.forms[0];
var count=$('#QuestionList tr').length
for (var i = 0; i<count; i++) {
var row = table.rows[i];
if(row.getAttribute('val')==='question')
    {
    var Cells = row.getElementsByTagName("td");;
    }

}       

}

4 个答案:

答案 0 :(得分:1)

document.querySelector('tr[val] > td > input').value;
Array.from(document.querySelectorAll('tr[val] > td > input')).forEach(function(entry, index, entries)
{
    entry.value; // you may store the value OR process with it AS you see fit
});

答案 1 :(得分:1)

由于您使用的是Jquery,因此可以这样做。

替换这行代码

var Cells = row.getElementsByTagName("td");

var Cells = $(row).find('td');

var inputValue = Cell.find('input').val(); // gives you value of input

建议

代码重构

我想重构您的代码,如下所示

<强> HTML

<tr data-val='question'>     // use data-* attribute to add custom attributes into tags
    <td>
        <input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '>
    </td>                    // close your td
</tr>

<强>脚本

function saveUserDefQues(){      

 var surveyquestionform = document.forms[0];  // not sure what this is for, so ill leave it as is.

 $('#QuestionList tr[data-val="question"]').each(function(){ //loop all tr's  which has the data-val set to question     
   var inputValue = $(this).find('td input').val();          //get the value of input
   console.log(inputValue);            
 });  

}

答案 2 :(得分:0)

$("tr[val='question'] > td > input").val()

但首先你需要编写一个有效的HTML。缺少</td>结束标记。您还需要将tr放在<table>

答案 3 :(得分:0)

See this Plunker

function getResult(){
    $( "tr" ).each(function( index ) {
  console.log($(this).find('input').attr('placeholder') );
});
}