首页 > 解决方案 > 未定义值获取带有 id 作为数组的文本框

问题描述

我必须从文本框中获取值,其名称为数组。但我得到未定义的响应。

<input id="text[0][0]" type="text" value="" class="form-control label text-center" placeholder=" 1" style="">
<button>Text Box Value</button> 

我试过jquery代码

var button = $("button")
button.on("click", function(){
   var cell= $("#text[0][0]").val()
   alert(cell)
}))

标签: jquery

解决方案


您可以使用\\在 jquery 选择器中转义方括号

https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/

var button = $("button")
button.on("click", function() {
  var cell = $("#text\\[0\\]\\[0\\]").val()
  alert(cell)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="text[0][0]" type="text" value="1">
<button>Text Box Value</button>

注意 document.getElementById('text[0][0]')在不转义方括号的情况下有效


推荐阅读