Populate Select Element With Json Data And Return Filtered Content Of Json
I want to display only parts of a .json that I scraped with scrapy. the scrapy output looks something like this and has about 500 entries: data.json [ { 'Content':['
Headi
Solution 1:
Try this
Demo
var arr = [{
"Content": ["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
"Titel": ["Heading of Paragraph1"]
},
{
"Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
"Titel": ["Heading of Paragraph2"]
}, {
"Content": ["<h2>Heading of Paragraph3</h2><p>the actual pargraph3</p>"],
"Titel": ["Heading of Paragraph3"]
}
];
//prepare the options firstvar options = arr.map( function( item ){
return"<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>"
} ).join( "" );
//set all the options to select and then bind change event
$( "select" ).html( options ).change( function(){
$( "#paraContent" ).html( "" );
var val = $(this).val();
$( "#paraContent" ).html( val.map( function( title ){
return arr.find( (s) => s.Titel[0] == title ).Content[0];
}).join( "</br>" ) )
//console.log(val);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formaction="/returnselected_paragraphs.js"><selectname="pargraphs"multiple></select><pid="paraContent"></p><inputtype="submit"></form>
Solution 2:
You can build the options list easily:
const options = json_data.reduce(
function (fragment, item)
{
const option = document.createElement("option");
option.value = item.Titel[0];
option.textContent = option.value;
fragment.appendChild(option);
return fragment;
},
document.createDocumentFragment()
);
Then append the options to your select (the document fragment will "merge" with the select and disappear, don't worry).
Solution 3:
From your reference on jsfiddle, you can modify that to the code below:
var data = [
{
"Content":["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
"Titel": ["Heading of Paragraph1"]
}
,
{
"Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
"Titel": ["Heading of Paragraph2"]
}
,
{
"Content": ["<h2>Heading of Paragraph3</h2><p>the actual
pargraph3</p>"],
"Titel": ["Heading of Paragraph3"]
}
]
$.each(data, function () {
var$option = $('<option/>').text(this.Titel[0]).val(this.Titel[0]);
$option.data("content",this.Content[0])
$('#selectCompany').append($option);
});
Here is the link to your modified code in action: https://jsfiddle.net/azqxhjgx/
You can use click event on option to display the content of the object where you want, something like this:
$("#selected > option").click(function(){
//do whatever with $this.data("content")
})
Post a Comment for "Populate Select Element With Json Data And Return Filtered Content Of Json"