Microsoft translator AJAX API, dropdown to change languageTo and languageFrom? - javascript

I am trying to write a translator box for my website. So far, I've been able to get working code from a tutorial:
<input id="ori" type="text" />
<button onclick="translate();">Translate</button>
<div id="trans"></div>
<script>
var languageFrom = "en";
var languageTo = "fr";
function translate() {
document.getElementById('trans').innerHTML="Translating... please wait";
var text= document.getElementById('ori').value;
window.mycallback = function(response) {
document.getElementById('trans').innerHTML=response;
}
var s = document.createElement("script");
s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=<MY-APP-ID>&from=" + languageFrom + "&to=" + languageTo + "&text=" + text;
document.getElementsByTagName("head")[0].appendChild(s);
}
</script>
(Script it from here: http://wizardsoweb.com/microsoftbing-translator-ajax-example/2011/05/?wpmp_switcher=desktop)
Basically, once I fill in my APPID, it will translate the text in the ori text box to French. Of course, this all works fine, but here's what I'm trying to do:
I want there to be two drop down menus. One will populate the languageFrom variable with a specified language, and another drop down menu which will populate the languageTo variable with a specified language.
I've already posted about this matter in a different post: Update script var's with value from drop down?. That way, when you select a value from the drop down menu, it populates the variable. I have a working example of this on jsFiddle:
http://jsfiddle.net/charlescarver/hk2bJ/1/
(I included my API key so it's easier to work on)
SO, I think the problem with this is that the script which controls the translation is loaded when the variables are empty, and then doesn't update when a drop down option is selected.
I think this can be fixed by calling the script when the button is clicked, instead of when the page is loaded. How can this be accomplished? The Microsoft support is poorly documented and I can't find a solution there or on google. Here's a link to the API documentation: http://msdn.microsoft.com/en-us/library/ff512385.aspx

You're trying to attach event handlers to objects (select1 & select 2) that essentially don't exist yet (looking at your jsfiddle example) - which breaks the rest of your script, since you're actually failing to attach anything.
So you'll need to do something like this (not the greatest of conventions, but it demonstrates the point)
window.onload = function()
{
document.getElementById("select1").onchange = function() {
languageFrom = this.value;
}
document.getElementById("select2").onchange = function() {
languageTo = this.value;
}
}
(Which means you'll only attach the events once everything is loaded & available)
Something you can also do inline with your html elements, like seen below:
From: <select id="select1" onchange="languageFrom=this.value">
<option value="en">En</option>
<option value="fr">Fr</option>
</select>
To: <select id="select2" onchange="languageTo=this.value">
<option value="en">En</option>
<option value="fr">Fr</option>
</select>
Or Alternatively do everything inside your translate function (which means you don't need to attach anything to your dropdowns nor define any global variable)
function translate() {
document.getElementById('trans').innerHTML="";
var text= document.getElementById('ori').value;
window.mycallback = function(response) {
document.getElementById('trans').innerHTML=response;
}
var languageFrom = document.getElementById("select1").value;
var languageTo = document.getElementById("select2").value;
var s = document.createElement("script");
s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=8B841CA7C1A03443682C52AD07B7775A7BD5B3AA&from=" + languageFrom + "&to=" + languageTo + "&text=" + text;
document.getElementsByTagName("head")[0].appendChild(s);
}

Related

How to get Text and Value in element SELECT by #ID 100% AngularJS

There is a better way to do AngularJS, with fewer lines of code that my example ..?
The idea is to make it 100% with AngularJS and jqLite.
Link Example My CODE solution: http://jsfiddle.net/EOM/xecymL9t/
HTML:
<div data-ng-controller="Main" data-ng-app>
<select id="yo" data-ng-model="selection" data-ng-change="sample(selection)" required="required">
<option value="11" selected="selected">Name 2</option>
<option value="10">Name 1</option>
<option value="">SELECT DEFAULT ANGULAR INIT</option>
<option value="12">Name 3</option>
</select>
View Show in Console to Browser (F12)
AngularJS:
function Main($scope, $document) {
$scope.sample = function(myvalue) {
// Get By ID
var e = $document[0].getElementById('yo');
// Get all options select
e = angular.element(e).find('option');
// Loop
angular.forEach(e, function(v, k){
// Is option selected..?
if(angular.element(v).prop('selected')){
// Get Text option selected
console.log('Text: '+angular.element(v).text()); // Text
}
});
console.log('Value: '+myvalue) // Value
}}
This is a bit shorter, but I don't know if you consider it 100% AngularJS + jqLite. AngularJS docs say you should use standard DOM APIs for advanced queries (jqLite's find is limited to lookups by tag name)
function Main($scope, $document) {
$scope.sample = function(myvalue) {
var e = $document[0].getElementById('yo')
.querySelector('[value="' + myvalue + '"]');
// Get Text option selected
console.log('Text: '+angular.element(e).text()); // Text
console.log('Value: '+myvalue) // Value
}
}
You can check the the solution here
Based on solution "jbMartinez", I saw a simpler solution shortens the handles.
And retrieve the text of the option selected.
With respect to compatibility "Niclas Larsson" is to have >= IE9 or higher, since I am using AngularJS 1.5.0 and it does not support for <= IE8
Are saying, see it as a final solution or it may be a better way ..?
Code Example only change in JS:
function Main($scope, $document) {
$scope.sample = function(myvalue) {
var myval = (myvalue)?myvalue:'';
// Get text select
var mytext = $document[0].querySelector('#yo [value="' + myval + '"]').text;
// Show Text option selected in console
console.log('Text: '+mytext); // Text
console.log('Value: '+myval) // Value
} }
Link Example Run HERE

Get script on option select with this value

I am using a select box to pull some data that is built into the site. However there are a few modules that run a script , and using the select option , that script is not firing when its selected. Do i have to run the full script within my option function , or can it be called to execute again when its selected.
Here is my script and html. Option Value "MESSAGE12" - needs a script to run when selected.
if(unescape(location.href).indexOf("http://football")!=-1||unescape(location.href).indexOf("http://6")!=-1) {
var currentServer=baseURLDynamic;
xmlBaseURL = baseURLDynamic + '/fflnetdynamic' + year + '/';
} else {
var currentServer=baseURLStatic;
}
function getHomePageModule(thisSelection) {
if(thisSelection=="")
document.getElementById("homePageModule").innerHTML = "Your selected module will appear here!";
else {
var url = currentServer + "/" + year + "/home/" + league_id + "?MODULE=" + thisSelection.toUpperCase();
$.get(url, function(data){
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
});
}
}
<select onchange="getHomePageModule(this.value)">
<option value="default">Select A Module</option>
<option value="MESSAGE12" >Get HPM#12</option>
<option value="LIVESCORING" >Link To Live Scoring</option>
<option value="LIVESCORING_SUMMARY" >Live Scoring Summary</option>
</select>
<div id="homePageModule">Your selected module will appear here!</div>
Here is a link to my demo select box - http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE11
And a link to the MESSAGE12 content i'm wanting to fire up in the select box
http://football29.myfantasyleague.com/2015/home/72758?MODULE=MESSAGE12
Any advice appreciated
Instead of using innerHTML (which doesn't evaluate <scripts>), you could try using jQuery's .append() method.
Change:
document.getElementById("homePageModule").innerHTML = $(data).find('#pageContent').html();
to:
$("#homePageModule").append($(data).find('#pageContent').html());
(This also replaces the call to getElementById with a jQuery selector.)
If that doesn't work, you might need to take a look at the content returned by the call to $(data).find('#pageContent').html() and make sure your scripts are there, and/or move the scripts into a function that can be called after the .append() finishes.

Option value doesnt showup in dropdown - jquery

I am trying to add new options in a dropdown based on the other dropdown value.
the new added option doesnt appear in the dropdown on my custom webkit browser.
When I try to debug it the values are present in the dropdown, just it doesnt show up in the front end.
I have attached the code but its working in jsbin :(
When I click the empty dropdown and then click New button value doesnt show up but if I dont click the empty dropdown and click new button directly values appear normally.
https://jsbin.com/kikicuhabo/1/edit?html,css,js,output
It is a good practice to write HTML in lower case, and to close the tags.
If you want to use jQuery I recommend to select elements alway with the "$('')" instead of mixing with the "document. ... "
Since yours it is a custom browser I would try a solution in Vanilla JS.
function AddToCB(p_oCB, p_sText) {
var oSelect = document.querySelector(p_oCB);
var iNewLast = oSelect.length;
var sDisplay = p_sText + (iNewLast + 1);
var oNewItem = document.createElement('option');
oNewItem.innerHTML = sDisplay;
oNewItem.setAttribute('value', sDisplay)
oSelect.appendChild(oNewItem);
oSelect.selectedIndex = iNewLast;
return iNewLast;
}
function AddOption() {
var select = document.querySelector("#cmb");
var text = select.options[select.selectedIndex].value;
AddToCB('#list', text);
}
<select name="cmbColor" id="cmb">
<option>AA</option>
<option>BB</option>
<option>CC</option>
</select>
<input type="button" class="float-right" VALUE="New" onClick="AddOption()" >
<select name="list" id="list">
</select>

jquery, get value of different select list

I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle

Allowing for multiple selectors within one function in jquery

I have a drop down box in which allows for a "category" to be selected, if it is changed it loads the new category as shown in the code below. I have since introduced a "Sub-Category" system and am in need of modifying this code slightly. I found the following information to be very helpful:
How to attach different events on multiple selectors through .on function in jquery?.
However, it doesn't quite solve my problem... I could use that to run two separate events for each selector within the same function but I need to run both simultaneously in the event both a "category" and "sub-category" are selected. Though they need to also be capable of running separate, in the event only one is selected. I'm fairly new to js/jquery so the more info you can provide the better! Thank you very much!
<script type='text/javascript'>
$(document).ready(function()
{
$('select#selectCategory').change(function()
{
var cat = $('select#selectCategory').val();
var subcat
if(cat > 0)
{
var param = '&category_id=' + cat;
}else{
var param = '';
}
var href = './videoroom.php?action=video_gallery'+ param +'&page=1';
window.location.href = href;
});
});
</script>
Here is the HTML section related to the already written jquery code:
<select style="min-weight:100px;" name="filter_by_cat" id="selectCategory">
<option value="0">All</option>
<option value="9">Wizard101</option>
<option value="10">Pirate101</option>
<option value="11">Pet Derby</option>
<option value="14">Misc/Fun</option>
</select>
And here is the new bit I added for the newly created Sub-Category:
<select style="min-weight:100px;" name="filter_by_subcat" id="selectSubCategory">
<option value="0">All</option>
<option value="21">General PvP</option>
<option value="22">PvPC Matches</option>
<option value="23">PvP Guides</option>
<option value="24">Miscellaneous</option>
</select>
Add the event listener to both dropdowns and check both of them when either is changed:
jsFiddle
$('#selectCategory, #selectSubCategory').change(function() {
var cat = $('#selectCategory').val();
var subcat = $('#selectSubCategory').val();
var params = [
'action=video_gallery',
'page=1'
];
if (cat > 0) {
params.push('category_id='+ cat);
if (subcat > 0) {
params.push('subcategory_id='+ subcat);
}
}
var href = './videoroom.php?'+ params.join('&');
window.location.href = href;
});
I'm assuming you only want the subcategory choice to be taken into account when the main category is selected. If that's not the case, move the second if-statement outside the first one.
I also refactored your code a little to make it more easily extensible and (IMO) cleaner. I'm adding all the params to an array and them just joining them at the end. If you need to add any more params, just put them in the array as well.

Categories

Resources