I've got a wierd issue:
<div id="translate">
Translate
<div id="google_translate_element" style="display:none">
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: "sv" }, "google_translate_element");
};
</script>
</div>
</div>
Which gives me the following:
<div class="skiptranslate goog-te-gadget" style="">
<div id=":1.targetLanguage">
<select class="goog-te-combo">
</select>
</div>
Powered by
<span style="white-space: nowrap;">
</span>
</div>
I cannot however seem to hijack the change event being triggered when selecting a new language.
I've tried by doing the following:
var $textfield = find("#google-translate");
var $popup = find("#google_translate_element");
var $select = $popup.find("select");
$textfield.click(function () {
$popup.fadeIn("fast");
return false;
});
$select.bind("change", function () {
$popup.fadeOut("fast");
});
Have anyone got a solution for this?
BR, Henric
The code below suggested by MjrKusanagi works wonderfully.
$("body").on("change", "#google_translate_element select", function (e) {
console.log(e);
console.log($(this).find(":selected").text());
console.log($(this).find(":selected").val());
});
To view all data inside the drop down
$(".goog-te-combo").find("option").each(function () {
console.log($(this).text() + ", " + $(this).val() + "\n");
});
I finally solved this by using a reoccuring check on the language.
Not the prettiest solution, but it does the job. :)
var firstMenuValue = $("#main-menu li:first").text();
var checkIfTranslated = function () {
var check = function () {
if (firstMenuValue != $("#main-menu li:first").text()) {
firstMenuValue = $("#main-menu li:first").text();
$("#google_translate_element").fadeOut("fast");
}
};
setInterval(check, 2000);
};
checkIfTranslated();
I hope this helps out somebody at least.
My guess is that you would need to verify that the HTML from Google has been injected before running your JS code.
I can't seem to find a callback event on the TranslateElement just make a check for a HTML item you know is suppose to be there before running your code.
Google Translate Widget - Translation complete callback
This is what works for me flawlessly:
$("body").on("change", ".goog-te-combo", function (e) {
if($(".goog-te-combo").val() == 'ar'){
$("html").children().css("direction","rtl");
}
else{
$("html").children().css("direction","ltr");
}
});
This is how I change the page direction from ltr (left-to-right) to rtl (right-to-left) when Arabic (ar) is selected as language, and vice-versa.
Related
Right now, I have a javascript function which is triggered onclick. However, I want the same function to be triggered when DOM is loaded. Following code works, however, I don't want to put 'script' tag in the middle of the view. Calling the function from the body tag is not an option here.
<script>document.addEventListener("DOMContentLoaded",function(){extractions.RefreshCheck(#check.ID)});</script>
Code snippet of where I want to implement this:
#foreach (var check in Model.FailedChecks)
{
<li class="#( check.IsOK ? Html.Raw("bg-success") : Html.Raw("bg-danger") ) " cid="#check.ID">
#Html.ActionLink(check.Display, "XList", "XList", new { filter = check.GetQuery(), Layout = check.Layout }, new { target = "_blank" });
<span class="glyphicon glyphicon-refresh" onclick="extractions.RefreshCheck(#check.ID);" onload="initAutoRefresh"></span>
#*<script>document.addEventListener("DOMContentLoaded",function(){extractions.RefreshCheck(#check.ID)});</script>*#
</li>
}
Above codes work, but I do not want that script tag in my view. So I tried to add the following code in my javascript file using 'onload' eventlistner and it does not work. I think this is the problem.
#foreach (var check in Model.FailedChecks)
{
<li class="#( check.IsOK ? Html.Raw("bg-success") : Html.Raw("bg-danger") ) " cid="#check.ID">
#Html.ActionLink(check.Display, "XList", "XList", new { filter = check.GetQuery(), Layout = check.Layout }, new { target = "_blank" });
<span class="glyphicon glyphicon-refresh" onclick="extractions.RefreshCheck(#check.ID);" onload="extractions.InitAutoRefresh()"></span>
</li>
}
And my InitAutoRefresh function :
var extractions= {
InitAutoRefresh: function () {
if (document.readyState === 'complete') {
RefreshCheck();
console.log("function already loaded in DOM")
} else {
document.addEventListener('DOMContentLoaded', function () {
RefreshCheck();
console.log("function loaded in dom");
});
}
},
RefreshCheck: function(intCheckId){
$('li[cid=' + intCheckId + ']').addClass('bold');
$.get(window.location + '/Home/UpdateIntegritycheck?checkId=' + intCheckId, function(data){
$('li[cid='+intCheckId+']').replaceWith(data);
});
}
}
Function RefreshCheck works fine on click (i.e. it updates record). I would be more than happy to get your feedbacks. Thank you.
One approach is to define custom attribute on your html tags on which you can fire conditionaly according to the tag value. Example :
<span data-click-on-dom-ready="true" onclick="extractions.RefreshCheck(#check.ID);" ></span>
Then far away from your partial view, you can put the following:
$(document).ready(function () {
$("[data-click-on-dom-ready='true']").trigger('click');
});
Try this code:
#section scripts{
<script>document.addEventListener("DOMContentLoaded", function () { xtractions.RefreshCheck(id) });</script>
}
if you are using jquery then you can use
$(document).ready(function () {
your code here
});
I have the following function, I want to get called everytime, user types something in the typeahead input field.
function getAllActiveUsers() {
var userList = $('#usersTable').jqGrid('getGridParam').userData;
var userNames = {};
if(userList) {
// Return the list of all active users
$(userList).each(function() {
if(this.userStatus != 1) {
// If the user is verified
// Could be active/inactive
userNames.user = this.username;
}
});
}
return JSON.stringify(userNames);
}
HTML:
<div id="the-basics">
<input class="typeahead" type="text" data-provide="typeahead" placeholder="User List">
</div>
I have been browsing through, the examples, but do not understand how to implement this functionality.
Edit:
Why it doesn't work when I initialize as :
$('.typeahead').typeahead({
source : getAllActiveUsers
});
Try this
$(document).ready(function(){
$('.typeahead').keyup(function(){
getAllActiveUsers();
});
});
You can use .keyup jquery function
$( ".typeahead" ).keyup(function() {
getAllActiveUsers();
});
Taken from the reference you gave you can specify the class .typeahead inside the id #the-basics:
$(document).ready(function(){
$('#the-basics .typeahead').typeahead({
//code here;
}
}
Since the page can't be manipulated safely until the document is ready you should be using $(document).ready.
Also, try to use your browser console and check if you can reach $('#the-basics .typeahead')
You can use Jquery Keyup which gets triggered when a key is released.
$( ".typeahead" ).on('keyup',function() {
getAllActiveUsers();
});
if your text box coming dynamically then you should try
$(document).on("keyup", ".typeahead" , function() {
getAllActiveUsers();
});
try this and let us know if its works or not.
It should be possible
var getAllActiveUsers = function(q, cb, cb2) {
// cb for sync, cb2 for async
var userList = $('#usersTable').jqGrid('getGridParam').userData;
var filterted = /* whatever you want to do with q */;
cb(filtered);
};
$('.typeahead').typeahead({
/* Options */
},
{
source : getAllActiveUsers
});
I am new to html and java script. I try to create a button and get the JSON back from a URL and add the result to a drop down list. After the Nodejs server is up and running, if you enter http://localhost:8080/restapi/test/projects, it will return {example} as the result.
So there are couple questions here:
1) for some reason, the button click is not working inside jquery
2) $.getJSON can only used inside jquery, is there any other way to obtain JSON from a URL respond?
$(document).ready(function () {
$(document).on('click', '#button1', function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, function (data) {
$.each(data, function (index, d) {
var option = document.createElement('option');
option = d;
selector.add(option);
});
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='first'>
<h1>project options</h1>
<button id='button1'>Get Projects</button>
</div>
<div id='second'>
<h2>all projects</h2>
Projects: <select id='selector'></select>
</div>
Thanks for any tips.
{example} is not valid JSON. Try {"1":"example"}
Also, option = d; will overwrite your option. Try option.value = d;
Here is a cleaned up version for you :
$(document).ready(function () {
$('#button1').click(function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, {"1":"example","2":"other example"},function (data) {
$.each(data, function (index, d) {
selector.options[selector.options.length] = new Option(d,d);
});
});
});
});
Fiddle: https://jsfiddle.net/trex005/65hc1srh/
Try the following:
$(document).ready(function () {
$('body').on('click', '#button1', function() {//this sintax is used most for dynamically added elements
var selector = $('#selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, function (data) {
$.each(data, function (index, d) {
var option ='<option>'+d+'</option>';
selector.append(option);
});
})
})
})
the click button is actually working... maybe there's a problem with the response.
you can check the network log by opening the inspector.
to open the inspector on chrome use right click and then 'inspect' or 'inspect element'.
this is what happened when i click the button.
for the second question you can make an AJAX request using the XMLHttpRequest object.
It will not worked because you did not do the exact thing clicked.All you have done is that $(document).click() which don't know what elements or document to click.
You should have used
$('#button1').on('click',function() {
});
for button click which tells that it will response only when the button is clicked.For your better understanding I am giving the code snippet
$(document).ready(function () {
$('#button1').on('click',function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, function (data) {
$.each(data, function (index, d) {
var option = document.createElement('option');
option = d;
selector.add(option);
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id='first'>
<h1>project options</h1>
<button id='button1'>Get Projects</button>
</div>
<div id='second'>
<h2>all projects</h2>
Projects: <select id='selector'></select>
</div>
It will work.If not then please check your api url.
I am new to Jasmine and seem to be struggling to get what I think is a fairy standard kind of thing running.
I am loading an HTML file via a fixture and trying to call a click on an element on the dom. This I would expect result in the call to the method of the JS file I am trying to test. When I try and debug this in developer tools the method that should be called in my js file never hits a breakpoint. As such I assume that code is not being called and therfore does not toggle the expand/collapse class.
My test:
describe("userExpand", function () {
beforeEach(function () {
loadFixtures('user-expand.html');
//userControl();
//this.addMatchers({
// toHaveClass: function (className) {
// return this.actual.hasClass(className);
// }
//});
});
//this test works ok
it("checks the click is firing", function () {
spyOnEvent($('.expanded'), 'click');
$('.expanded').trigger('click');
expect("click").toHaveBeenTriggeredOn($('.expanded'));
});
//this doesn't
it("checks the click is changing the class", function () {
//spyOnEvent($('.collapsed'), 'click');
var myElement = $('.collapsed');
myElement.click();
expect(myElement).toHaveClass('.expanded');
});
Part of the fixture:
<div class="wrapper">
<div class="row group">
<div class="col-md-1" data-bordercolour=""> </div>
<div class="collapsed col-md-1"> </div>
<div class="col-md-9">None (1)</div>
The JS I am trying to test:
var userControl = function () {
"use strict";
var collapse = '.collapsed';
var expand = '.expanded';
var userList = $(".userList");
function toggleState() {
var currentControl = $(this);
if (currentControl.hasClass('all')) {
if (currentControl.hasClass('expanded')) {
toggleIcon(currentControl, collapse);
userList.find(".user-group-summary").hide()
.end()
.find(".user-group-info").show();
} else {
toggleIcon(currentControl, expand);
userList.find(".user-group-summary").show()
.end()
.find(".user-group-info").hide();
}
} else {
currentControl.parent().nextUntil('.group').toggle();
currentControl.toggleClass("expanded collapsed");
currentControl.parent().find(".user-group-summary").toggle()
.end()
.find(".user-group-info").toggle();
}
};
function toggleIcon(ctrl, currentState) {
var details = ctrl.closest('div.row').siblings('.wrapper');
details.find(currentState).toggleClass('expanded collapsed');
if (currentState === expand) {
details.find('.detail').hide();
} else {
details.find('.detail').show();
}
}
userList.on('click', '.expanded, .collapsed', toggleState);
$('[data-bordercolour]').each(function () {
$(this).css("background-color", $(this).data('bordercolour'))
.parent().nextUntil('.group')
.find('>:first-child').css("background-color", $(this).data('bordercolour'));
});
return {
toggleState: toggleState
};
}();
The code works fine in normal use so I am sure I am missing something obvious with the way Jasmine should be used. Any help would be appreciated.
Update:
I can make the togglestate method fire by using call in the test rather than triggering a click event:
it('checks on click of icon toggles that icon', function () {
var myElement = $('.collapsed');
userControl.toggleState.call(myElement);
expect(myElement).toHaveClass('expanded');
});
This seems a little strange as all the examples I can find are quite happy with click. Gets me off the hook but I would still like to know what I am missing.
It's hard to give a precise hint without the source code. Does click on .collapsed involve asynchronous action(s)? If so, wrapping the test in runs(...); waitsFor(...); runs(...); may solve the problem. Check the Jasmine introduction for how to do this.
When I've added select2 to all selects in my app it worked very nice except when in my select is this property(it works when I don't use select2):
onchange="'refresh()'"
Function refresh:
function refresh()
{
document.forms[0].submit();
}
This is how I run select2
$("select").each(function(){
var this1 = $(this);
if(this1.attr('multiple')!='multiple')
{
this1.select2();
}
});
How to pass this? Or maybe there is some mechanism inside the select2 that deals with that kind of problems? All kinds of suggestions are welcome:D
you need to update this:
$(#Select/Input Element).select2();
$("#select/input element").change(function () {
var valueToSet = $("#select/input element").select2('data').text;
$('#hiddent field to which data to be set').val(valueToSet);
});
Not sure to understand. When one of yours selects changes, you want to call the refresh method? In that case :
$("select").each(function(){
var $this = $(this);
if($this.attr('multiple')!='multiple'){
$this.select2();
$this.change(refresh);
}
});
Remove single quote from onchange="'refresh()'. Try as mentioned below :
<input type="checkbox" onchange="Refresh();"/>
And your script will be defined as below :
<script type="text/javascript">
function Refresh() {
alert('refresh');
}
</script>