Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing An Array of Values To Jquery

I have a button like so:

<button id='abc' value=['fred', 26]></button>

I want to know how I can access those two values via JQuery's .val() function.

I have tried $("#abc").val()[0] but that just appears to give me the first character which is the bracket "[".

I would like .val()[0] to instead give me the value "Fred".

like image 989
Petty_Crim Avatar asked Dec 01 '25 08:12

Petty_Crim


1 Answers

Your HTML is invalid. You should try;

<button id='abc' value="['fred', 26]"></button>

However, you should look at using valid JSON notation, to enable you to parse the data as an array. JSON requires double quotes for strings (rather than single '), so you should end up with;

<button id='abc' value='["fred", 26]'></button>

If you were to access $('#abc').val() directly now, you'd retrieve the string ["fred", 26]. To retrieve this data as an array, you should parse the data using jQuery.parseJSON();

var array = jQuery.parseJSON($('#abs').val());
for (var i=0;i<array.length;i++) {
    alert(array[i]);
};
like image 61
Matt Avatar answered Dec 04 '25 00:12

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!