无法使用普通 JQuery/Javascript 检索输入字段的值

Can't retrieve the value of input fields using normal JQuery/Javascript

本文关键字:检索 Javascript 输入 字段 JQuery      更新时间:2023-09-26

嗨,我在检索输入字段的文本值时遇到问题。这两个输入字段隐藏在表行中,仅当在选择元素中选择特定选项时才会显示。我不确定这是否会影响出于某种原因访问输入字段数据。下面的函数显示了如何根据选择选项的值显示和隐藏表格行。

我尝试以普通的jquery方式和javascript方式获取值:

$('#doc_reference').attr('value'); document.getElementById('doc_reference').value

但是两者都没有运气,有人能帮忙吗?

//toggle doc_reference and y_reference dependent on modelling language chosen
  $("#langId").change(function() {
    var val = $(this).val();
    console.log(val);
    if(val == 1) {
        $('.hideShowTr').hide();
    }
    else if(val == 2) {
        $('.hideShowTr').show();
    }
  });
var docReference =$('#doc_reference').attr('value');
var yReference = $('#y_reference').attr('value');    
<tr class = 'hideShowTr' style='display: none;'>
    <td>
        <span style='display:block; position:relative; padding:0; z-index:0;'>
          <input type='text' name='doc_reference' id='doc_reference' style='position:absolute; width:195px; z-index:151;'></input>
        </span>
    </td>
</tr>
<tr class = 'hideShowTr' style='display: none;'>
    <td>
        <span style='display:block; position:relative; padding:0; z-index:0;'>
          <input type='text' name='y_reference' id='y_reference' style='position:absolute; width: 195px; top:2px; z-index:151;'></input>
        </span>
    </td>
</tr>

►元素中没有属性值。

使用此代码段检索值。

$('#doc_reference').val();

演示

$("#doc_reference,#y_reference").keyup(function() {
  alert($(this).val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr class='hideShowTr'>
  <td>
    <span style='display:block; position:relative; padding:0; z-index:0;'>
          <input type='text' name='y_reference' id='y_reference' style='position:absolute; width: 195px; top:2px; z-index:151;'>
        </span>
  </td>
</tr>