Reputation: 21
I want to make a getJSON search based on the selected option. For instance: if I choose Italian in the select option menu I want the getJSON query to look like json.w1.Italian.
I know that this code is not correct, that's why I'm asking for help.
Here's the code:
<select name="language">
<option selected="selected" value="english">English</option>
<option value="german">German</option>
<option value="spanish">Spanish</option>
<option value="italian">Italian</option>
<option value="french">French</option>
<option value="portuguese">Portuguese</option>
<option value="dutch">Dutch</option>
<option value="romanian">Romanian</option>
<option value="greek">Grek</option>
<option value="bulgarian">Bulgarian</option>
</select>
<div id="language"></div>
<div id="results"></div>
<script>
$("select")
.change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
$("#language").text(str);
var query = json.w1.str;
$.getJSON("lang.json", function(json) {
$("#results").text(query);
});
})
.change();
</script>
Upvotes: 2
Views: 1362
Reputation: 10260
Hey you seem to have alot of code you dont need in your example. Without seeing your result json I think you want something like this.
https://jsfiddle.net/vpeLq3k4/
$( "select" )
.change(function () {
var lang = $( "select option:selected" ).val();
$( "#language" ).text( lang );
$.getJSON( "lang.json", function( json ) {
$( "#results" ).text( json.w1.lang );
});
});
If you post an example of what json is returned we can probably help a little more.
Upvotes: 0
Reputation: 337560
Your code is a lot more complex than it needs to be - to get the chosen value of a select
you can simply call val()
. Then you can use bracket notation to retrieve an item from an object using the key as a string. Try this:
$('select').change(function () {
var lang = $(this).val();
$("#language").text(lang);
$.getJSON('lang.json', function(json) {
$('#results').text(json.w1[lang]);
});
}).change();
Upvotes: 2