code to set a select box option value as an object

前端 未结 3 1746
一个人的身影
一个人的身影 2020-12-25 12:49

in an html page i have got, i have a select box like this with values.


                        
    
提交评论

  • 2020-12-25 13:33

    You can use parseJSON to convert the string to an object when using it, but the value needs to be a string.

      var option = $('select').val();
      var selected = $.parseJSON(option);
      alert( selected.name + ': ' + selected.age );
    
    0 讨论(0)
  • 2020-12-25 13:38

    No, not just like that. Values have to be strings. I'd strongly recommend to use something like jQuerys .data() method to hold Arrays or Objects in an expando property.

    If it must be in the value, you just need to JSON decode (.parse) it:

    var myValue = JSON.parse(this.value);
    
    myValue.age; // 40
    myValue.name // rajiv
    

    But again, I don't think this is a good solution. Have a look at http://api.jquery.com/jQuery.data/ Also, jQuery will automatically convert Arrays and Objects if you put the JSON strings in any data- HTML5 attribute. For instance:

    <option value="A" data-info="{'name':'rajiv',age:'40'}">something</option>
    

    If you access that node with jQuery now, we automatically got that object in it's data expando

    $('option').data('info').name; // === rajiv
    
    0 讨论(0)
  • 提交回复
    热议问题