简体   繁体   中英

Objects (JSON or otherwise) as the value in a html tag

I am trying to write a web application that has dependent menus and I think it would be best to just put in objects in the value fields so I can just the value of the checked fields. The reason I am asking about putting in JSON instead of just the values is because I may need to put tuples of values in there later.

Ex:

var a = $('.optionsGroup:checked');

where a yields:

[ <input type=​"checkbox" name=​"optionsGroup" class=​"optionsGroup" id=​"optionsGroup" onclick=​"selectGroupFamily(this,1,'Math 8','class')​" value=​"{classId:​1}​">, 
  <input type=​"checkbox" name=​"optionsGroup" class=​"optionsGroup" id=​"optionsGroup" onclick=​"selectGroupFamily(this,3,'Math 9','class')​" value=​"{classId:​3}​"> ]

and the rest of the code:

var bar = function(key,val){
    console.log(val);
    console.log(typeof val);
    b = $(val);
    console.log(b.val()); 
    var obj = $.parseJSON(b.val()); //some error here saying unexpected type c
    console.log(obj);
    console.log(obj.classId);
}
$.each(a,bar);

Ideally I'd like to get the output:

...html line...
string
object
1 etc.

Your code works fine if you change the JSON in value like

value='{"classId":"1"}'

Notice the double quotes around property name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM