Consider that i have the following html
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
To fetch the values i use
a = $('#other_floor_plans').val()
It returns the following
"["Pool","Office","Sprinkler","Boiler"]"
If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.
How to accomplish this?
答案 0 :(得分:3)
您的值是一种string
,其语法正确JSON
。只需将JSON.parse
解析为数组并使用您的语法。
const value = '["Pool","Office","Sprinkler","Boiler"]';
const array = JSON.parse(value);
console.log(array[0]);
答案 1 :(得分:0)
我认为你需要在标记中特别改变你的代码。
将您的输入标记更改为此<input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
然后通过jQuery获取值
var a = $('#other_floor_plans').val(),
a = JSON.parse(a);
console.log(a[0]);
你需要使用JSON.parse,因为你得到了json formate值,需要进行解析。
对于我的建议你只需用逗号分隔值
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="Pool, Office, Sprinkler, Boiler">
然后通过jQuery获得第一个值
var a = $('#other_floor_plans').val().split(",");
console.log(a[0]);
我猜这个更容易理解。
答案 2 :(得分:0)
您可以使用eval
函数将字符串转换为数组并获取值。
var a = "['Pool','Office','Sprinkler','Boiler']"; // or you can also assign like this var a ='["Pool","Office","Sprinkler","Boiler"]'
var firstItem = eval(a)[0];
console.log(firstItem); //output will be "Pool"
答案 3 :(得分:0)
如果在输入框中初始化值时执行了错误操作,则必须在不同的引号中包含值。 在那里你采取&#34;价值分配和&#34;也用于数组字符串,在第二个&#34;上截断你的字符串这就是为什么这只返回[在你的价值中。 尝试使用如下:
HTML
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
JQuery的
var a = $('#other_floor_plans').val();
a = JSON.parse(a);
console.log(a);