Reputation: 131
I am currently using dreamweaver and I am trying to build a simple translator function. I have a drop down with multiple options (each language designated by specialized id's) and I want the user to select the language of choice and have the chosen HTML string translated. So far I have tried everything and I can't seem to get this to work, and this I thought would be the simplest way. Any thoughts or edits would be huge help. p.s. I'm a total beginner
JQuery:
$("#French").click(function(){
$("#AppartmentB").replaceWith("maison");
});
HTML:
<select name="selectmenu" id="selectmenu">
<option value="option1" id="English">English</option>
<option value="option2" id="French">French</option>
</select>
<div data-role="page" id="AppartmentPage" class="page">
<h1 class="TopText" align="center" id="AppartmentT">Appartment</h1>
<h1 class="BotText" align="center" id="AppartmentB">Appartment</h1>
</div>
Upvotes: 2
Views: 4104
Reputation: 66
I put together a basic example. Essentially, the JS has a database of translations. I've only put in one item with 1 key, text
. The JS listens for any changes to the language select dropdown menu.
This is essentially how many localization libraries work. Check out jquery-localize if you want to implement something more robust.
// Translation database
var translations = {
'en': {
'text': 'Apartment'
},
'fr': {
'text': 'Maison'
}
}
// Li
$("#languageSelect").change(function() {
var str = '';
$("#languageSelect option:selected").each(function() {
var langCode = $(this).val();
str += translations[langCode]['text'];
});
$("#translatedText").text(str);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="languageSelect">
<option value="en" selected="selected">English</option>
<option value="fr">French</option>
</select>
<div data-role="page" id="AppartmentPage" class="page">
<h1 id="translatedText">Apartment</h1>
</div>
Upvotes: 4
Reputation: 1180
You're replacing the whole matched tag instead of its contents, and you can't listen to a click event on a select option.
Try to listen to the change
event of your select element, and use the languages as option values.
HTML:
<select name="selectmenu" id="selectmenu">
<option value="english">English</option>
<option value="french">French</option>
</select>
JS:
$("#selectmenu").on('change', function() {
var chosenLanguage = $(this).val();
switch (chosenLanguage) {
case 'french':
$('#AppartmentB').text('Maison');
break;
case 'english':
$('#AppartmentB').text('Appartment');
break;
}
});
See a full working example here: https://jsfiddle.net/r76hLLte/
Upvotes: 0