Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

building the value attribute of an option tag using jQuery

I have a function like this where I’m dynamically generating the option tag of a select.

function colorInfo(data) {
    console.log("Color Info");
    console.log(data);
    let colorData = JSON.parse(data);

    console.log(colorData);

    $.each(colorData, function (key, value) {
        $("#lineupColors").append(
        $("<option></option>")
           .attr("value",'{"colorId":'+value.colorId+',"colorCode":'+value.colorCode+'}')
          .text(value.colorName)
      );
    });
  }

Since I am defining the value as a Json object, how can I add double quotes such that the value would look like {"colorId":"1","colorCode":"#FFFFFF"}.

Right now it is coming out like this – which is not a valid JSON :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"colorId":1,"colorCode":#FFFFFF}.

>Solution :

Need to set the JSON.stringify(object) as the attribute. See example how to manipulate the "input" object.

function colorInfo(data) {
  console.log("Color Info");
  console.log(data);
  let colorData = JSON.parse(data);

  console.log(colorData);

  $.each(colorData, function(key, value) {

    const yourObject = {
      colorId: value.colorId,
      colorCode: value.colorCode
    }

    // you can even set by property name
    var key = "colorCode"
    yourObject[key] = value.colorCode

    // once object is ready to serialize:
    $("#lineupColors").append(
      $("<option></option>")
      .attr("value", JSON.stringify(yourObject))
      .text(value.colorName)
    );
  });
}

colorInfo(JSON.stringify([{
    colorId: 12,
    colorCode: "black",
    colorName: "jonnie",
  },
  {
    colorId: 132,
    colorCode: "#ff0",
    colorName: "yellow"
  }
]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<select id="lineupColors">
</select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading