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
});
Related
I have a download button set up on a web page that is iteratively assigned an ID based on the how many questions are posted.
Here is the button:
<input data-bind="attr: { id: $index() }" type="button" value="Download" class="download" />
Here is the the JS function that finds the number assigned and does the onclick:
#Scripts.Render("~/bundles/knockout")
<script type="text/javascript">
var SDNo = 0;
$(document).ready(function () {
SystemJS.import('sd/questions').then(function (modules) {
//Code here for another section that fills out the questions not relevant apart from assigning SDNo
});
SystemJS.import('sd/download').then(function (modules2) {
var attachVM = new modules2.Attachment();
//$("#download").click(function () {
$("input[class^='download'], input[class*=' download']").each(function () {
$(this).click(function () {
var id = $(this).attr('id');
let passedValue = id.concat("-" + SDNo);
attachVM.download(passedValue);
});
});
});
The above function allows me to go off to a typescript file and handle the required API call to GET a file
that code is here:
typescript
export class Attachment {
async download(ID: Number) {
window.open(await WebApi.getJSON('SD', 'Download', Number));
}
}
So yeah it'll work then it'll randomly stop working for no reason that I can find and obviously no errors thrown, via debugging it doesn't even get into the typescript file at all nothing happens. But then sometimes it goes all the way through into the controller doing what it needs to do.
As per #LouysPatriceBessette
$("input[class^='download'], input[class*=' download']").each(function () {
$(this).click(function () {
var id = $(this).attr('id');
let passedValue = id.concat("-" + SDNo);
attachVM.download(passedValue);
});
to
$("input.download").on("click", function() {
var id = $(this).attr('id');
let passedValue = id.concat("-" + SDNo);
attachVM.download(passedValue);
});
And it works consistently now thank you again.
On Ajax Success, li element is appended to ul.
$.ajax({
..
success: function (response) {
response.data.forEach(function (x) {
$("#ulMain").append('<li class="liSub">' + x + '</li>');
}
});
It creates sth like this:
<ul>
<li class="liSub">ABC</li>
<li class="liSub">BCF</li>
</ul>
I want the dynamically added li elements to fire an alertbox on click.
But the code below is not being hit.
$(document).ready(function () {
$(".liSub").on("click", function () {
alert("Fired");
});
});
Interestingly, If I run the document.ready section of the code using F12 - Console, it works. What stops it run normally, and lets it run through console?
You missed . prefix for class and use event delgation for created dynamic dom elements
$("ul").on("click", '.liSub', function () {
alert("Fired");
});
Since it is an element loaded dynamically, try delegating it:
$(document).ready(function () {
$("body").on("click",".liSub", function () {
alert("Fired");
});
});
It is because when your page is ready, the ajax call is not finished. You can try this :
$(document).ready(function () {
$("#ulMain").on("click",".liSub", function () {
alert("Fired");
});
});
It will bind the click to the #ulMain which exists at the execution and will delegate the event to .liSub at the moment of the click. It creates only one binding which is also better for global performance.
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.
I am new to javascript n jquery. I used javascript along with jquery on my script tag.When jquery is not added, the javascript works fine,but when a jquery function is added, the script is not working.....shall i convert both to javascript or both to jquery or am i missing anything.Here is my script
<script type="text/javascript">
function getLocations() {
$.post('#Url.Action("getLocations","Home")', { 'id': $("#cities").val() },
function (data) {
$("#loca").html(data).show();
});
}
$(function () {
$('.submit').on('click', function () {
var ck = "";
var city = $("#cities option:selected").text();
var location = $("#loca option:selected").text();
alert(city+"and"+location)
}
});
</script>
here i am loading location based on the city selected.Its works fine when the onclick is not there,But when added ,location are not loading n the function is not calling.I have tried by butting alert inside it.Do i need do any thing else for both to work....Thank You
you forgot a )
$(function () {
$('.submit').on('click', function () {
...
}) // <---
});
if you properly indent the code blocks and if you look on the javascript console, this kind of errors become easier to be detected. Just adopt an indent style and write code adhering to it.
I'm trying to insert a form field into a popup page. For some reason the form field doesn't get inserted. Any pointers. Pasted below is the code:
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var AgentId = $form.find("#AgentId").val();
var ReportName = $form.find("#ReportName").val();
var Params = $form.find("#Params").val();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
$.post(urlstring, { AgentId: AgentId, ReportName: ReportName, Params: Params },
function (data) {
window.open(urlstring);
$("#divfrmInfo").append($form);
});
} });
HTML for my popup window :
<html>
<head></head>
<body>
<h2>AddToCart</h2>
<form name="frmContact">
<div>
<div class="CartHeader">
<ul>
<li>
<span class="CartImage"></span>
<span class="Title">To Add Listing(s) to Cart</span>
<span class="SubTitle">Select your personal cart or add listings to a contact</span>
</li>
</ul>
</div>
**<div id="divfrmInfo"></div>**
</div>
</form>
</body></html>
Looking at it some more you could do something like this, in opener document.
$(".ddlAddListinTo li").click(function () {
...
function (data) {
$(window.open(urlstring)).load ( function() {
// Here "this" will be the window.
$(this.document).find("#divfrmInfo").append($form.clone())
});
}
This way you attach to load event for popup by jQuery.
Have a look at .clone() for the append part. If it is not cloned it will be "ripped" from your main document and placed inside the popup.
Old answer:
...
Here is a fiddle (With fixed typo/formatting).
Next problem is in your script you say:
$(".ddlAddListinTo li").click
However, there are no elements in DOM with class ddlAddListinTo.
OK, by comment:
after window.open(urlstring); you are still in DOM of document from where you opened the window. As such:
$("#divfrmInfo")
will look for an element in original document with that ID, not in the popup.
If you add something like this in the popup document*:
$(window).load(function() {
// Call function "fill()" in opener.
window.opener.fill(document);
});
And this in your opener document:
function fill(what) {
// Here "what" is document of popup.
what.getElementById("divfrmInfo").innerHTML = "TEST";
}
I think the selector in your AJAX callback is unable to get DOM elements in the popup. Try this:
var tmpWin = window.open(urlstring);
$(tmpWin.document).find("#divfrmInfo").append($form);
THe problem is you are tring to aceess the DOM of the spawned page before it is there. The window is loaded but the HTML is still being loaded at the time you are trying to access it. You will need to change the parent and popup page. On the parent page you will need a function to return what you want to populate the pop up with. On the popup page you will want to call the function on the parent page when the DOM is ready.
Something like:
Parent Page
//Add this OUTSIDE your document ready
function getContent(){
return $("#frmPostToEmailReports");
}
Popup
//Include Jquery in your prefered way
<script>
$(document).ready(function () {
$("#divfrmInfo").append(window.opener.getContent());
});
</script>
Alos make sure to remove where you attempt to pupulate in the success function. Also see: How to get element and html from window.open js function with jquery
Previous Useless Answer Below
See this answer to get you started.
Instance you will want something like:
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var AgentId = $form.find("#AgentId").val();
var ReportName = $form.find("#ReportName").val();
var Params = $form.find("#Params").val();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
$.post(urlstring, { AgentId: AgentId, ReportName: ReportName, Params: Params },
function (data) {
var popup = window.open(urlstring);
popup.document.$("#divfrmInfo").append($form);
});
} });