button click is not working inside jquery - javascript

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.

Related

CSHTML button with javascript onlick function only works some times?

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.

Tumblr like button not working after ajax load

I am using pjax and masonry in my tumblr theme. I just figured out how to get masonry to work after clicking a pjax'd link, but now the problem is that the like button is not working anymore. Here is my code so far:
html:
<article class="entry" id="{PostID}">
</article>
jquery:
$(document).ajaxComplete(function(){
$('#content').imagesLoaded(function(){
$('#content').masonry('reloadItems').masonry();
});
var $newPosts = $(data).find('.entry');
var $newPostIDs = $newPosts.map(function () {
return this.id;
}).get();
Tumblr.LikeButton.get_status_by_post_ids($newPostIDs);
});
I believe you need to use pjax:success. This should give you the data object.
$(document).on('pjax:success', function( event, data, status, xhr, options ) {
$('#content').imagesLoaded(function(){
$('#content').masonry('reloadItems').masonry();
});
var $newPosts = $(data).find('.entry');
var $newPostIDs = $newPosts.map(function () {
return this.id;
}).get();
Tumblr.LikeButton.get_status_by_post_ids($newPostIDs);
});
Source: https://github.com/defunkt/jquery-pjax#events

jQuery Eventhandler for an dynamically added object

I got an problem with dynamically added DOM objects in jQuery. First of all I use this:
var $input = $('#search-input');
var $usersList = $('#ulist');
$input.on('input', function () {
$.ajax({
type: 'get',
url: '/userlist',
data: {query: $input.val()},
success: function (response) {
var json = JSON.parse(response);
$usersList.empty();
$.each(json, function (index, val) {
$usersList.append("<div id=\"listelem\">" + val + "</div>");
});
}
});
});
<div id="ulist"></div>
<input id="search-input" type="text">
to insert divs into usersList. This works well, but now I want to get val from this div when I click on it to process it further. I wrote this piece of code:
$usersList.on('click','#listelem', function(){
alert("clicked");
});
When I click on div I got proper alert, but now I have no idea how could I took data from inside of this element.
I don't know the proper engineering but I have dealt with similar issue while I was developing some requirements. basically as I understood you want to find out the target of the event and drag a value from there? if so you can do something like this:
jQuery(document).on('click', '#listelem', function(event){
var x = event.target.val();// event.target.value; depending on your situation and availability of the method.
});
Hope this helps.
try this
$(document).on('click','#listelem', function(event) {
alert($(event.target).text());
});
jsfiddle
Thanks you for help. for me proper option was to call
var mem =event.target.innerText;
you can do that with the regular javascript, you don't need Jquery.
document.addEventListener("click", function(e) {
if(e.target) {
console.log("item clicked ", e.target.textContent);
}
});
This should do the job to get the value of current target.

Google Translate override select change event

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.

Insert a form field into a popup page using jquery

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);
});
} });

Categories

Resources