Javascript/Jquery onClick using HTML Div not working - javascript

When I click on my "php1" div it doesn't do anything.
The location.reload() is a placeholder, just an easy way of knowing whether or not the onClick works.
<div class="php-task">
<h1>PHP</h1>
<div id="php1" class="text">
<p>Display/setvars</p>
</div>
</div>
$("#php1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "php/pagehandler.php",
data: {page: "task",task: 1},
success: function (response) {
location.reload();
}
});
});

Just to show you that it won't work for duplicate id elements (and that it does work as a reduced example for the first div with that id, which must be unique):
$("#php1").click(function (e) {
console.log('clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="php-task">
<h1>PHP</h1>
<div id="php1" class="text"><!-- clicking this will trigger the handler -->
<p>Display/setvars</p>
<p>clicking this will trigger the handler</p>
</div>
</div>
<div class="php-task">
<h1>PHP</h1>
<div id="php1" class="text"><!-- clicking this will NOT trigger the handler -->
<p>Display/setvars</p>
<p>clicking this will NOT trigger the handler</p>
</div>
</div>

I think in your case with multiple divs php1,php2,php3... it will be better to attach the click event using classes instead :
$(function() {
$(".php-task .text").click(function(e) {
e.preventDefault();
console.log('Task with id : ' + this.id + ' clicked.');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="php-task">
<h1>PHP</h1>
<div id="php1" class="text">
<p>Display/setvars</p>
</div>
</div>
<div class="php-task">
<h1>PHP</h1>
<div id="php2" class="text">
<p>Display/setvars</p>
</div>
</div>
<div class="php-task">
<h1>PHP</h1>
<div id="php3" class="text">
<p>Display/setvars</p>
</div>
</div><br><br><br>

Can you try below code? Might be your HTML is dynamically loaded after page load.
$(function(){
$('body').on('click', '#php1', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "php/pagehandler.php",
data: {page: "task",task: 1},
success: function (response) {
location.reload();
}
});
});
});

$(document).ready(function () {
$("#task").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "php/pagehandler.php",
data: {
page: "task"
},
success: function (response) {
location.reload();
}
});
});
});
Adding the following did the trick:
$(document).ready(function()

Related

How to fill forms using an API having associative array?

I need to use Jquery and AJAX to access an API which has this associative array-
{"1":"alamiz builder","2":"souroy builder","3":"vin selv builder","4":"gol mat builder","5":"sm dev builder","6":"zahi builder"}*
Because this array has numbers as keys, I am having a hard time displaying each value in a form element.
I have tried using $(selector).html(data["1"]) but this is just displaying the first character of the data.
My current code is-
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$.ajax({
type: 'GET',
url: 'https://interview.switchme.in/js/2019/builder_json.php',
success: function(data){
$("#b1").html(data["1"]);
}
});
</script>
</head>
<body>
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox"></div>
<div id="b2"><input type="checkbox"></div>
<div id="b3"><input type="checkbox"></div>
<div id="b4"><input type="checkbox" checked></div>
</div>
</body>
</html>
I expect that the checkboxes display all the data from the API dynamically.
In such a way-
<div id="b1"><input type="checkbox">alamiz builder</div>
You need use console.log(data) for detail about data structure.
I tried to reproduce with your JSON object, it worked.
Also need add for ajax call
contentType: 'application/json',
dataType: "json",
Updated:
It will have issue with CORS when you use $.ajax()
Try use $.getJSON(), it worked
$.getJSON('https://interview.switchme.in/js/2019/builder_json.php',function(data){
//console.log(data);
$("#b1").html(data["1"]);
})
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$.getJSON('https://interview.switchme.in/js/2019/builder_json.php',function(data){
//console.log(data);
$("#b1").html(data["1"]);
})
</script>
</head>
<body>
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox"></div>
<div id="b2"><input type="checkbox"></div>
<div id="b3"><input type="checkbox"></div>
<div id="b4"><input type="checkbox" checked></div>
</div>
</body>
</html>
Your $.ajax is returning JSON, which is a string - you need to make the code treat it like a JavaScript object, so add dataType: "json" to the options object:
$.ajax({
type: 'GET',
url: 'https://interview.switchme.in/js/2019/builder_json.php',
dataType: "json",
success: function(data) {
$("#b1").html(data["1"]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox"></div>
<div id="b2"><input type="checkbox"></div>
<div id="b3"><input type="checkbox"></div>
<div id="b4"><input type="checkbox" checked></div>
</div>
Try this way:
(And don't remember, javascript codes must be above of tag)
<div class='builder_checkbox'>
<div>Builders Filter 2</div>
<div id="b1"><input type="checkbox">
<span></span> </div>
<div id="b2"><input type="checkbox"> <span></span>
</div>
<div id="b3"><input type="checkbox"> <span></span>
</div>
<div id="b4"><input type="checkbox"checked>
<span></span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$.ajax({
type: 'GET',
url: 'https://interview.switchme.in/js/2019/builder_json.php',
success: function(value){
var data = JSON.parse(value);
$("#b1 span").text(data["1"]);
$("#b2 span").text(data["2"]);
$("#b3 span").text(data["3"]);
$("#b4 span").text(data["4"]);
}
});
</script>

Using ajax for every div with class/id

So I have asp.net core 2 project where I have one master view with this html:
<div>
#foreach (var factory in Model.factoryList)
{
<div class="factory-panel-content">
<div class="factory-main-info">
#factory.Name
<div class="city-name">#factory.CityName</div>
<div class="factory-some-value">
#factory.someValue
</div>
</div>
<div id="factory-plot-content">
</div>
</div>
}
And one partial view with (html only)
<div class="row">
<div class="col-md-4">
<div id="flot-line-chart" style="height: 100px"></div>
</div>
<div class="col-md-2">
<div id="flot-pie-chart" style="height: 100px"></div>
</div>
<div class="col-md-2">
<div id="gauge"></div>
</div>
What I need is to get partial view for every #factory-plot-content in my master view for each of my factory.
Using ajax like below change only one of the #factory-plot-content - the first one (I understand why) but I don't know what is the best way to call ajax.get foreach of factory divs.
My ajax: (Which I call in master page. It will be great to call it while foreaching factories)
$(document).ready(function () {
$.ajax({
url: '/home/ShowShortFactoryInfo',
success: function (data) {
$("#factory-plot-content").html(data);
}
});
})
The first idea I had is to make custom ids like "factory-plot-content-#Model.FactoryName" but I'm kinda sure that this is an ugly way to reach result I need.
You can try with following code:
<div>
<script>
var factoryNumber = 0;
</script>
#foreach (var factory in Model.factoryList)
{
<div class="factory-panel-content">
<div class="factory-main-info">
#factory.Name
<div class="city-name">#factory.CityName</div>
<div class="factory-some-value">
#factory.someValue
</div>
</div>
<div class="partial-data" id="factory-plot-content">
<script>
getPartialData(function(data){
let partialData = $(".partialData")[factoryNumber];
partialData.html(data);
factoryNumber++;
});
</script>
</div>
</div>
}
<script>
function getPartialData(cb){
$.ajax({
url: '/home/ShowShortFactoryInfo',
success: function (data) {
cb(data);
}
});
}
</script>
Hope it helps :)

JQuery not working for external html [duplicate]

This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 6 years ago.
I need to create few div elements after click the button. So I decide to make something like template in external file and append in head div tag using jquery.
$('.socket-element').on('click', function (e) {
$.ajax({
url: '/my-site/tags/socket-box.php',
success: function (data) { $('#room-place').append(data); },
dataType: 'html'
});
});
And my external html file:
<div class="socket-box room-box-element col-xs-2 ui-draggable ui-draggable-handle">
<div class="row">
<div class="row">
<div class="box-header col-xs-12">
<div class="row">
<div class="col-xs-2">
<img class="down-arrow" src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-right-b-128.png" width="14" height="18" />
</div>
<div class="col-xs-8">
<h6>Temperature</h6>
</div>
<div class="col-xs-2">
<img class="settings" src="https://cdn2.iconfinder.com/data/icons/flat-ui-icons-24-px/24/settings-24-128.png" width="18" height="18" />
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="row">
<div class="box-content col-xs-12">
<div class="row">
Test
</div>
</div>
</div>
</div>
So this code is working fine is add the external html on the original html file but when I need to use click event on appended html is not working.
So I need to use few events like click, draggable from jquery ui etc.
But when I need to use: this click event then for appended html is not working
$('.down-arrow').click(function (e) {
alert('Test');
});
How can I solve this problem.
Try this :
$('.socket-element').on('click', function (e) {
$.ajax({
url: '/my-site/tags/socket-box.php',
success: function (data) {
$('#room-place').append(data);
$('#room-place').ready(function(){
$('.down-arrow').click(function (e) {
alert('Test');
});
});
},
dataType: 'html'
});
});
Hope this will help:)
For dynamic events do write using event delegation like:
$(document).on("click",".down-arrow",function(){
//write your code here
})
Please Try to use the events inside the on ready function .. Trust me it will work properly.
$(document).ready(function(){
$('.down-arrow').click(function (e) {
alert('Test');
});
});
Please try this way.
Use event delegation
$(document).on('click', '.down-arrow',function(e){
});

$.mobile.navigate in jQuery Mobile 1.4 not working

When I press "btnNew" the click event fires but the page does not navigate to newLanguagePage, instead it goes back to my initial page (index.html).
Could anyone, please, tell me what my dumb head is doing wrong?
Here's my HTML
<!DOCTYPE html>
<html>
<body>
<div id="languagesAdmin" class="mobilePage" data-role="page">
<div data-role="header">
Back
<h1>NOTHNG</h1>
Help
</div>
<div class="banner">
<div class="logo"></div><div id="languagesTopImage" class="topBannerImage"></div>
</div>
<div class="ui-corner-all custom-corners">
<h2 class="ui-bar ui-bar-e adminHeader">Languages Menu</h2>
<div class="ui-body ui-body-e">
<div data-role="fieldcontain" class="filterDisabledCheckbox">
<label for="HideDisabledLanguages">Hide disabled Languages</label>
<input type=checkbox id="HideDisabledLanguages" name="HideDisabledLanguages" value="true" checked/>
</div>
<ul data-role="listview" id="lwLanguages" class="listViewMenu"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li><a id="btnNew" href="#" rel="external" data-role="button" data-icon="plus">New</a></li>
<li>Delete</li>
<li>Search</li>
<li>Refresh</li>
</ul>
</div>
</div>
</div>
<div id="newLanguagePage" class="mobilePage" data-role="page">
<div data-role="header">
Back
<h1>Inter Pay Less</h1>
Help
</div>
<div class="banner">
<div class="logo"></div><div class="topBannerImage"></div>
</div>
<div class="ui-corner-all custom-corners">
<h2 class="ui-bar ui-bar-e adminHeader">Languages Menu</h2>
<div class="ui-body ui-body-e">
New Language
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Delete</li>
<li>Search</li>
<li>Refresh</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Here's the JavaScript
var strBaseWSURL = "http://www.WHATEVER.com/";
var objLanguages = new Array();
var lngLanguagesCursor = -1;
//Language Object
function _Language(data) {
this.Id = data.Id;
this.Code = data.Code;
this.Name = data.Name;
}
//LanguageAdmin_pageinit
$(document).on('pageinit', '#languagesAdmin', function () {
try {
execJQueryAjaxAndGetJSON([], strBaseWSURL + "IPLObjectsWS.asmx/GetAllLanguages", loadLanguages);
}
catch (e) {//Report the error
alert("Error fetching the languages.")
return false;
}
//New_Click
$(document).on("click", "#btnNew", function () {
$.mobile.navigate("#newLanguagePage", { transition: "slide" });
});
//Languages_onclick
$(document).on("click", "#lwLanguages li a", function () {
lngLanguagesCursor = $(this).closest("li").index();
});
});
//LanguageDetails_pageinit
$(document).on('pageinit', '#languageDetails', function () {
var objCurrentObject = objLanguages[lngLanguagesCursor];
$("#languageid").val(objCurrentObject.Id);
$("#languagecode").val(objCurrentObject.Code);
$("#languagename").val(objCurrentObject.Name);
//Save_onclick
$(document).on("click", "#btnSaveCountry", function () {
var objCurrentObject = objLanguages[lngLanguagesCursor];
var objUpdatedLanguage = new _Language();
objUpdatedLanguage.id = objCurrentObject.id;
objUpdatedLanguage.Code = $("#languagecode").val();
objUpdatedLanguage.Name = $("#languagename").val();
execJQueryAjaxAndGetJSON(objUpdatedLanguage, strBaseWSURL + "IPLObjectsWS.asmx/SaveLanguage", savedLanguage);
});
});
//__________________________________________________________________________Application Functions
//__________________________________________________________Calback functions
//Goes thru the languages and adds them to the lisview
function loadLanguages(result) {
$.each(result.d, function () {
$("#lwLanguages").append($('<li>' + this.Name + '</li>'));
objLanguages[objLanguages.length] = new _Language(this);
});
$("#lwLanguages").listview("refresh");
}
function savedLanguage(result) {
alert("The object was saved successfully!");
}
//__________________________________________________________Main functions
//Executes a Webservice Method and send the returned JSON to a callback function
function execJQueryAjaxAndGetJSON(params, strURL, callBackFunc) {
//GetCountries
$.ajax({
type: "POST",
url: strURL,
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: callBackFunc,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ": " + XMLHttpRequest.responseText + "\n" + errorThrown);
}
});
}

Display next div on click

Say I have the following HTML layout:
<div class="main">
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
<div class="comment">
<div class="info">
<div class="data">
<img src="image.png" class="image-click" />
</div>
</div>
</div>
<div class="open-me"></div>
</div>
... etc ...
How would I make it so that if you click the image in one of the comment classes, it shows HTML in the next open-me class?
Here's what I have so far:
$(document).ready(function() {
$(document).on("click", ".image-click", function() {
$.ajax({
url: 'show_html.php',
type: "POST",
success: function() {
$(this).find(".open-me").html(); /* this is where I'm stuck */
}
});
});
});
this inside your AJAX success method isn't referring to the clicked element anymore. For that, we can set a context variable of this:
$(document).on("click", ".image-click", function() {
var self = $(this);
$.ajax({
url: 'show_html.php',
type: "POST",
success: function(data) {
self.parents(".comment").next(".open-me").html(data);
}
});
});
You can use this to access the sibling open-me. Also, you should save a reference to $(this) outside of the .ajax().
// outside the ajax function
var that = $(this);
// inside the ajax function
that.parent(".comment").next("open-me").html();
jQuery's documentation about next() is relevant.

Categories

Resources