How to get the value of the nth element in a JSON list (using jQuery)?

How to get the nth value in a JSON file (and, possibly, these are children)?

For example, I have a set of courses and related events formatted in JSON that I use to populate multiple select lists, for example:

// extract from courselist.php
[{
    "optionValue": "Getting Research into Practice",
    "events": [
        {"date": "29 October"}
    ] 
},
{
    "optionValue": "Human Resources for Managers",
    "events": [
        {"date": "September 1"},
        {"date": "November 2"}
    ]
}]

I do this to create a form from this JSON:

$(function(){
$("select#coursetype").change(function(){
    $.getJSON("courselist.php",{id: $(this).val(), ajax: 'true'}, function(data){
        var options = ''; //item in select list
        options += '<option value=""></option>';
        for (var i = 0; i < data.length; i++) {
            options += '<option value="' + [i] + '">' + data[i].optionValue + '</option>';  
            $("#courselist").html(options);
            $('#courselist option:first').attr('selected', 'selected');
        };
    })
})  
});

.. which prints HTML line by line:

<select id="coursetype" name="coursetype">
    <option value="0">Getting Research into Practice</option>
    <option value="1">Human Resources for Managers</option>
</select>

Let's say the user selects Human Resources for Managers (value = "1") and $ _POST - the form, how can I later get the name of this course and event information from the POST value?

+3
source share
1 answer

JSON, :

var courseName = data[postValue].optionValue;
var courseEvents = data[postValue].events;
for(theDate in courseEvents){
    // do something with the date
}
+2

Source: https://habr.com/ru/post/1756489/


All Articles