Angular 5中如何处理选项字段的布尔过滤器?
Here's a straightforward way to implement this functionality using HTML and vanilla JavaScript. We'll set up a dropdown, listen for selection changes, and generate the required JSON object dynamically.
Step 1: HTML Structure
First, wrap your existing <option> elements in a <select> tag so we can interact with it (added a label for accessibility too):
<label for="number-select">Choose a number:</label> <select id="number-select"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="4">Four</option> </select>
Step 2: JavaScript Logic
We'll add an event listener to the dropdown that triggers whenever the selection changes. We start with the default all-false JSON object, then update the corresponding field based on the selected option:
// Grab the select element from the DOM const selectElement = document.getElementById('number-select'); // Map option values to their corresponding JSON keys const valueToKeyMap = { '1': 'one', '2': 'two', '3': 'three', '4': 'four' }; // Function to build the required JSON response function createResponse(selectedValue) { // Default state: all fields false const response = { one: false, two: false, three: false, four: false }; // Update the selected field to true if a valid value is provided if (valueToKeyMap[selectedValue]) { response[valueToKeyMap[selectedValue]] = true; } return response; } // Listen for selection changes selectElement.addEventListener('change', (event) => { const selectedValue = event.target.value; const jsonResponse = createResponse(selectedValue); // Example: Log the formatted JSON to the console console.log(JSON.stringify(jsonResponse, null, 2)); // If you need to send this to a server, uncomment the fetch call below: // fetch('/your-api-endpoint', { // method: 'POST', // headers: { // 'Content-Type': 'application/json', // }, // body: JSON.stringify(jsonResponse), // }); });
How It Works
- The
valueToKeyMapconnects the numericvalueof each option to the lowercase key in your JSON response. - The
createResponsefunction starts with the default all-false object, then toggles the relevant key totruebased on the selected value. - When the user picks an option, the
changeevent fires, we generate the JSON, and can either log it or send it to a backend server.
Initial Load Default
If you want to generate the default all-false JSON when the page first loads, just call createResponse() without a parameter:
// Log default response on page load const initialResponse = createResponse(); console.log(JSON.stringify(initialResponse, null, 2));
内容的提问来源于stack exchange,提问作者Kishan M

