开发者

Grab some Array data from a Select tag

I am learning JQuery.

I got s Select Tag with some options in a very simple form like this:

(The开发者_开发百科 form was generated by the Server and the values in each Option was retrieved from the database.)

<select name="data[Site1][quotenumber]" id="data[Site1][quotenumber]"> 
<option name="editquote" value="[29,1]">1</option> 
<option name="editquote" value="[24,2]">2</option> 
</select>

To get the value from the option selected, I used this code:

var whatValue = $('#data\\[\\Site1\\]\\[quotenumber\\] :selected').val();
alert(whatValue);

Now that I can get the value from the Select Tag, but the returned value was like an array, i.e. [29,1].

What is the best way to get the two values in each option?

I mean to print them out like this way:

The first value is 29, and the second one is 1.

Please help if you could


This should work:

var whatValue = $('#data\\[\\Site1\\]\\[quotenumber\\] :selected').val();
alert(whatValue);

eval('var arr = ' + whatValue);
alert('The first value is: ' + arr[0]);
alert('The second value is: ' + arr[1]);


jQuery has no way of knowing that your value represents an array. Instead, it gets "[29,1]" as a string. You'll have exactly the same problem server-side.

It'd be better to use a lookup table and a unique id.

HTML:

<select name="data[Site1][quotenumber]" id="data[Site1][quotenumber]">  
    <option name="editquote" value="option-1">1</option>  
    <option name="editquote" value="option-2">2</option>  
</select>

Javascript:

var data = {
    'option-1': [29,1],
    'option-2': [24,2]
}

var whatId = $('#data\\[\\Site1\\]\\[quotenumber\\] :selected').val();
var whatValue = data[whatId];
alert(
    "The first value is " + whatValue[0] + ", " + 
    "and the second one is " + whatValue[1] + "."
);

Alternatively, you could use jQuery's $.parseJSON function, like this:

var whatValue = $.parseJSON(
    $('#data\\[\\Site1\\]\\[quotenumber\\] :selected').val()
);

That's better than using eval().


Value is really confusing, but if you really want to access the individual numbers, you can use for example regexp to match the string and get the values in matcher:

var whatValue = $('#data\\[\\Site1\\]\\[quotenumber\\] :selected').val();
var re = /\[([0-9]+),([0-9]+)\]/;
var m = re.exec(whatValue);
alert("The first value is " + m[1] + ", and the second one is " + m[2] + ".")


I would say that your problem is really how you are outputting your options.. why are the values in that form anyhow ?

EDIT

another thought is this I'm not sure what your trying to get the values out in javascript or jquery so...

assuming your posting this data if you leave the html the way it is you could just parse the value in php ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜