EN VI

Javascript - Retrieve JSON and output to checkboxes?

2024-03-14 16:00:05
How to Javascript - Retrieve JSON and output to checkboxes

I'm currently retrieving this kind of JSON data from a PowerShell script:

[{"Name":"grp_SIR_RW"},{"Name":"grp_SIR_R"},{"Name":"grp_SPIE_RW"},{"Name":"grp_GOR_R"}]

I need to retrieve each names in this output and paste them into HTML checkboxes so my users can select one or many of them and the display needs to be well organized since I can have like 30 groups to display.

Solution:

To achieve this, you can use JavaScript to parse the JSON data and dynamically create HTML checkboxes for each group name. Here's a basic example of how you can do it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Group Selection</title>
</head>
<body>

<h2>Select Groups</h2>

<div id="checkboxes-container">
  <!-- Checkboxes will be dynamically added here -->
</div>

<script>
  // JSON data retrieved from PowerShell script
  var jsonData = [{"Name":"grp_SIR_RW"},{"Name":"grp_SIR_R"},{"Name":"grp_SPIE_RW"},{"Name":"grp_GOR_R"}];

  // Get the container where checkboxes will be added
  var checkboxesContainer = document.getElementById("checkboxes-container");

  // Loop through the JSON data and create checkboxes
  jsonData.forEach(function(group) {
    // Create a checkbox element
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.name = "group";
    checkbox.value = group.Name;
    
    // Create a label for the checkbox
    var label = document.createElement("label");
    label.appendChild(document.createTextNode(group.Name));
    
    // Add checkbox and label to the container
    checkboxesContainer.appendChild(checkbox);
    checkboxesContainer.appendChild(label);
    checkboxesContainer.appendChild(document.createElement("br")); // Add line break for spacing
  });
</script>

</body>
</html>

This code dynamically creates checkboxes for each group name in the JSON data. Each checkbox is accompanied by a label displaying the group name. You can customize the appearance and layout further according to your requirements.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login