<select id="myDropdown"></select>
$(document).ready(function() {
var data = {
'One': '1',
'Two': '2',
};
var dropdown = $('#myDropdown');
$.each(data, function(key, value) {
dropdown.append($('<option></option>').attr('value', value).text(key));
});
});
data variable contains the array you provided, where the keys represent the display values and the values represent the option values.dropdown variable selects the dropdown element using its ID.$.each() function iterates over each key-value pair in the data array.option element is created using the text() and attr() functions to set the display value and option value accordingly.append() function adds the newly created option element to the dropdown.Please revise the code, the data in in php is looks likeSure! Here's an example of jQuery code that will dynamically display the data from the given array into a dropdown:
HTML:
HTML:<select id="myDropdown"></select>
jQuery:
JavaScript:$(document).ready(function() { var data = { 'One': '1', 'Two': '2', }; var dropdown = $('#myDropdown'); $.each(data, function(key, value) { dropdown.append($('<option></option>').attr('value', value).text(key)); }); });
Explanation:
1. Thedatavariable contains the array you provided, where the keys represent the display values and the values represent the option values.
2. Thedropdownvariable selects the dropdown element using its ID.
3. The$.each()function iterates over each key-value pair in thedataarray.
4. For each pair, a newoptionelement is created using thetext()andattr()functions to set the display value and option value accordingly.
5. Finally, theappend()function adds the newly createdoptionelement to the dropdown.
Make sure to include the jQuery library in your HTML file for this code to work properly.
Apologies for the confusion. If the data in PHP is an array of values without corresponding keys, you can modify the jQuery code as follows:Please revise the code, the data in in php is looks like
'data' => [
'One',
'Two',
],
How can i display this in dropdown
<select id="myDropdown"></select>
$(document).ready(function() {
var data = [
'One',
'Two',
];
var dropdown = $('#myDropdown');
$.each(data, function(index, value) {
dropdown.append($('<option></option>').attr('value', value).text(value));
});
});
data variable contains the array of values from PHP.dropdown variable selects the dropdown element using its ID.$.each() function iterates over each value in the data array. Since there are no corresponding keys, we use the index parameter to track the current iteration.option element is created using the text() and attr() functions. We set both the value and text of the option to the current value in the iteration.append() function adds the newly created option element to the dropdown.