从表中的元素中获取价值

时间:2016-03-03 21:06:23

标签: javascript jquery html

我有下一张桌子:

<table id="table_id">
   <tr>
      <td>Test</td>
      <td>Description</td>
      <td>Date</td>
   </tr>
   <tr>
      <td><select>
             <option val="1">Math</option>
             <option val="2">Chemistry</option>
             <option val="3">Biology</option>
          </select></td>
      <td><input type="text" id="txt_desc"/></td>
      <td><input type="text" id="date"/></td>
   </tr>
</table>

下一个用于获取值的JavaScript代码

val_test_op = '';           
parent.$('#table_id option:selected').each(function (index,value){
   test = $.text(value).trim();
   if ( index === 0 && test || index % 1 === 0 && test )    {   
       val_test_op += index +' TEST: ' + test;
       return;
   }                    
})

val_test_input = '';
parent.$('#table_id td>input').each(function (index,value){
test = this.value;
    if ( index === 0 && test || index % 2 === 0 && test )   {
        texto_examen_input += index +' Description: ' + test;
        return;
    }
    if ( index === 1 && test || index % 3 === 0 && test )   {
        texto_examen_input += index +' Date: ' + test;
        return;
    }
})

我的问题是:¿我如何从选项中获取值:在“每个函数”中选择并输入文本?

3 个答案:

答案 0 :(得分:0)

我添加了一个按钮来提醒所选值是什么。

function myFunction(){
    var theSelect = document.getElementById("table_id").getElementsByTagName("select")[0];
  var selectedOption = theSelect.options[theSelect.selectedIndex].text;
  alert(selectedOption);
}

document.getElementById("myButton").addEventListener("click", myFunction, false);

https://jsfiddle.net/e1hxn6kL/

答案 1 :(得分:0)

为您的选择提供ID,例如id =“opts”

然后

var opts = [];
$.each($("#opts:selected"),function(opt){
    opts.push(opt.Val());
}
var txt_desc = $("#txt_desc").Val();
var date = $("#date").Val();

或类似的

答案 2 :(得分:0)

我认为您不需要each函数来从表格中的字段中获取值。

如果您在字段中添加id,则可以直接使用jquery选择这些字段,然后使用val函数轻松获取其值。

<table id="table_id">
    <tr>
        <td>Test</td>
        <td>Description</td>
        <td>Date</td>
    </tr>
    <tr>
        <td><select id="txt_test">
            <option val="1">Math</option>
            <option val="2">Chemistry</option>
            <option val="3">Biology</option>
        </select></td>
        <td><input type="text" id="txt_desc"/></td>
        <td><input type="text" id="txt_date"/></td>
    </tr>
</table>

然后使用javascript:

val_test_op = $('#txt_test').val();
texto_examen_desc = $('#txt_desc').val();
texto_examen_date = $('#txt_date').val();

如果您真的想使用单个each函数来获取所有值,可以使用jquery提供的:input选择器并执行以下操作:

values = '';
$('#table_id').find(':input').each(function (index, input) {
    values += $(input).val();
});
相关问题