I am developing an application with jQuery mobile and json bring data.
I have a problem loading content when I click on a button but if I enter directly to link the content is there.
Please, look:
if you click on any image it shows a page without content: http://www.example.com.ar/catalogoar/
But if you enter http://www.example.com.ar/catalogoar/arma_ampliada.html?id_arma=1 the content is there.
I can't find the problem. I already try with
$("#tabla_arma").table('refresh');
Please, learn how jQuery Mobile works before you post any more related questions. I am not trying to attack you but people here don't like this kind of questions.
To be able to solve this problem you need to understand how jQuery Mobile page handling works, and you can't solve this problem.
When jQuery Mobile handles pages only first HTML files is fully loaded into the DOM, all intermediate files are loaded only partially. When I say partially I mean HEAD will be stripped away and only FIRST data-role="page" will be loaded.
So if you have 2 pages, for example lets say first one is called index.html and second one is called arma_ampliada.html. When second page is initialized only content inside data-role="page" <div> will load into the DOM, everything else is going to get discarded, including HEAD javascript you need to load your data.
Read more about it here, you will also found solutions.
Your arma_ampliada.html page should look like this:
<html>
<head>
<title>Catálogo de Armas</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<!-- CSS -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.2.css" />
<link rel="stylesheet" href="css/listview-grid.css">
<link rel="stylesheet" href="css/estilos.css">
<!-- JS -->
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function()
{
$.mobile.defaultPageTransition = 'slide';
});
</script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<!-- <script src="js/cordova.js"></script> -->
</head>
<body>
<div data-role="page" data-theme="a" id="demo-page" class="my-page">
<script>
var armas;
function obtenerArmaAmpliada(id_arma){
$.ajax({
type: 'GET',
data: {'id_arma' : id_arma},
dataType : 'jsonp',
url: 'service/datos.php?jsoncallback=?',
success:function(data){
armas = data.armas;
mostrarArmas();
},
error: function() {
alert("error");
}
});
}
function mostrarArmas ()
{
$("#arma_ampliada").html('');
$.each(armas, function(indice, receta)
{
$("#arma_ampliada").append('<tr><td><img src="'+receta.foto+'" class="ui-li-thumb" ><h2>'+receta.marca+'</h2><p>'+receta.modelo+'</p></td></tr>');
});
$("#tabla_arma").table('refresh');
}
$(function(){
var Url = location.href;
Url = Url.replace(/.*\?(.*?)/,"$1");
Variables = Url.split ("&");
for (i = 0; i < Variables.length; i++)
{
Separ = Variables[i].split("=");
eval ('var '+Separ[0]+'="'+Separ[1]+'"');
}
obtenerArmaAmpliada(id_arma);
});
</script>
<div data-role="header" style="overflow:hidden;">
<h1>Catálogo de Armas</h1>
Opciones
<div data-role="navbar">
<ul>
<li>Marcas</li>
<li>Calibre</li>
<li>Tipo</li>
</ul>
</div>
</div>
<div role="main" class="ui-content">
<div id="tabla_arma">
<table id="arma_ampliada">
</table>
</div>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
Related
Working on a personal project with a navigation bar. I am using jquery x.load() to load html pages into a specific div. The pages load correctly into the div. However, one of the is using a jquery flipswitch. I am trying to read the state of this flipswitch, to no prevail. I have a main javascript file that loads the individual pages, which is basically my x.load(). I have a working jquery script for reading the switch state, that works when placed directly into the developers console. I have attempted this code both inline in the individual page as well as my main javascript file. When I place it inside the individual page, it will at times cause a race condition to develop.
I am looking for any suggestions, advice, or direction on being able to read the status of the flipswitch from the individual pages.
The first section of code is my javascript file. The second section of code, is both my individual page, as well as my main html page that loads the individual html page, respectively.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm'),
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" href="apt.css">
</head>
<body>
<header class="page-header">
<div class="apartment-name">Carlson Casa</div>
<div class="data-top">
<ul class="top-data">
<li>Time</li>
<li>Outside Temp</li>
<li>Inside Temp</li>
<li>Menu<span></span></li>
</ul>
</div>
</header>
<main class="main-content">
<nav class="side-nav">
<ul>
<li>Apartment</li>
<li class="nav-label">Living Room</li>
<li>Alarm control</li>
<li>Chandelier</li>
<li class="nav-label">Bedroom</li>
<li>Lights</li>
<li>Alarm Clock</li>
</ul>
</nav>
<div class="content">
Controls go here
</div>
</main>
<script src="jquery-2.1.4.js"></script>
<script src="main.js"></script>
</body>
</html>
As you are using jQuery Mobile Flipswitch of type checkbox, you can get the status by checking the property checked. Here is a jQuery Mobile Flipswitch playground:
var cases = {false: "Unchecked", true: "Checked"};
function getStatus() {
$("#statusLeft").html(cases[$("#LeftSwitch").prop("checked")]);
$("#statusRight").html(cases[$("#RightSwitch").prop("checked")]);
}
$(document).on("change", "#LeftSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusLeft").html("Changed to "+cases[status]);
});
$(document).on("change", "#RightSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusRight").html("Changed to "+cases[status]);
});
function toggleLeft() {
var status = $("#LeftSwitch").prop("checked");
$("#LeftSwitch").prop("checked", !status).flipswitch("refresh");
}
function toggleRight() {
var status = $("#RightSwitch").prop("checked");
$("#RightSwitch").prop("checked", !status).flipswitch("refresh");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="content">
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<span id="statusLeft">Unchecked</span>
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
<span id="statusRight">Unchecked</span>
</form>
<button class="ui-btn" onclick="getStatus();">Get Status</button>
<button class="ui-btn" onclick="toggleLeft();">Toggle Left</button>
<button class="ui-btn" onclick="toggleRight();">Toggle Right</button>
</div>
</div>
</body>
</html>
By using the change event instead of click you will be notified of the flipswitch toggling also if you are setting the status in code.
Additional notes:
About what you are defining "race condition" i believe you are referring to one of the common mistakes when using jQuery Mobile, i.e. document.ready vs. page events. Please read this post here, and also take some time to read the whole story in deep in this great post of Omar here: jQuery Mobile “Page” Events – What, Why, Where, When & How? (you will find here some other useful posts about this topic).
Moreover: you are trying to update the flipswtches manually by setting the ui-flipswitch-active class by yourself, but i believe you will run into the problem of keeping the status and the ui consistent. So, you may better use the standard JQM way to set the flipswitch status by using flipswitch.refresh. There is already an example in my code snippet.
The last note: until you strongly need it - and you know how to versioning jQuery Mobile - please use the same version of these libraries in all your files, so in your case i believe the pair jQuery 2.1 + JQM 1.4.5 shall be just fine.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm');
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')});
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
I've inherited a project and am very green regarding UI. This project uses Bootstrap, nvd3, and flot on Chrome. There is a layout view in which jQuery is referenced, and then partial views for each page are rendered in the layout body. On a dashboard page, the graphs don't show up unless jQuery is again referenced in the scripts, but that reference causes the sidebar to cease working. Referencing easing can be duplicated in the dashboard scripts to get both the graphs to appear and the sidebar to function, but one graph still doesn't work properly. This leads me to believe that jQuery and its libraries are being referenced multiple times on the layout and partial views, wiping out the references that display graphs, activate the sidebar, render graphs correctly, etc.
If that's correct, is there a way to trace each jQuery reference? I've tried deleting multiple references in the source code by sight, moving layout references into the HTML body, testing what's being hit through Chrome Developer Tools, re-calling references as described above as a band-aid, and searching here for similar questions, but nothing seems to achieve both the correct visual and functionality. Also, can a duplicated jQuery reference on a different partial view that shares the same parent layout nullify references in any other partial view? Please opine if there's another possible solution not considered here, because I'm ultimately trying to get the sidebar and graphs working properly. Thanks in advance for looking at this.
Here's the layout with references:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>#ViewBag.Title</title>
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<link rel="shortcut icon" href="/favicon.ico" />
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/icons")
#Scripts.Render("~/bundles/modernizr")
#RenderSection("headcontent", required: false)
<!-- page specific stylesheets -->
<!-- nvd3 charts -->
<link rel="stylesheet" href="/Content/lib/novus-nvd3/nv.d3.min.css">
<!-- owl carousel -->
<link rel="stylesheet" href="/Content/lib/owl-carousel/owl.carousel.css">
<!-- google webfonts -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400&subset=latin-ext,latin' rel='stylesheet' type='text/css'>
<!-- datepicker -->
<link rel="stylesheet" href="/Content/lib/bootstrap-datepicker/css/datepicker3.css">
<!-- date range picker -->
<link rel="stylesheet" href="/Content/lib/bootstrap-daterangepicker/daterangepicker-bs3.css">
<!-- timepicker -->
<link rel="stylesheet" href="/Content/lib/bootstrap-timepicker/css/bootstrap-timepicker.min.css">
<!-- ion.rangeSlider -->
<link rel="stylesheet" href="/Content/lib/ion.rangeSlider/css/ion.rangeSlider.css">
<!-- bootstrap switches -->
<link href="/Content/lib/bootstrap-switch/build/css/bootstrap3/bootstrap-switch.css" rel="stylesheet">
<!-- 2col multiselect -->
<link href="/Content/lib/multi-select/css/multi-select.css" rel="stylesheet">
<!-- multiselect, tagging -->
<link rel="stylesheet" href="/Content/lib/select2/select2.css">
<!-- main stylesheet -->
<link href="/Content/css/style.css" rel="stylesheet" media="screen">
<!-- moment.js (date library) -->
<script src="/Content/lib/moment-js/moment.min.js"></script>
[styles omitted...]
</head>
<body>
[header omitted...]
<!-- main content -->
<div id="main_wrapper">
[messages omitted...]
#RenderBody()
</div>
<!-- side navigation -->
<nav id="side_nav">
#Html.Partial("~/Views/Shared/_SidebarLeft.cshtml")
</nav>
<!-- jQuery -->
<script src="/Content/js/jquery.min.js"></script>
<!-- easing -->
<script src="/Content/js/jquery.easing.1.3.min.js"></script>
<!-- bootstrap js plugins -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- top dropdown navigation -->
<script src="/Content/js/tinynav.js"></script>
<!-- perfect scrollbar -->
<script src="/Content/lib/perfect-scrollbar/min/perfect-scrollbar-0.4.8.with-mousewheel.min.js"></script>
<!-- common functions -->
<script src="/Content/js/tisa_common.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>
And here's the dashboard HTML:
#using Project.Models
#model DashboardViewModel
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="heading_b">Prices Chart</div>
<div class="panel-body">
<div id="nvd3_cumulativeLine" style="width: 100%; height: 300px">
<svg></svg>
</div>
</div>
</div>
</div>
</div>
</div>
Finally, here are the dashboard scripts, with removal of jQuery causing the chart to disappear, removal of easing causing the sidebar to cease pop-outs, and removal of both causing the chart to disappear but leaving sidebar functionality intact.
#section Scripts{
<!-- page specific plugins -->
<!-- jQuery DUPLICATE -->
<script src="/Content/js/jquery.min.js"></script>
<!-- easing DUPLICATE -->
<script src="/Content/js/jquery.easing.1.3.min.js"></script>
<!-- nvd3 charts -->
<script src="/Content/lib/d3/d3.min.js"></script>
<script src="/Content/lib/novus-nvd3/nv.d3.min.js"></script>
<!-- flot charts-->
<script src="/Content/lib/flot/jquery.flot.min.js"></script>
<script src="/Content/lib/flot/jquery.flot.pie.min.js"></script>
<script src="/Content/lib/flot/jquery.flot.resize.min.js"></script>
<script src="/Content/lib/flot/jquery.flot.tooltip.min.js"></script>
<!-- clndr -->
<script src="/Content/lib/underscore-js/underscore-min.js"></script>
<script src="/Content/lib/CLNDR/src/clndr.js"></script>
<!-- easy pie chart -->
<script src="/Content/lib/easy-pie-chart/dist/jquery.easypiechart.min.js"></script>
<!-- owl carousel -->
<script src="/Content/lib/owl-carousel/owl.carousel.min.js"></script>
<!-- dashboard graph functions -->
<script src="/Content/js/apps/tisa_dashboard.js"></script>
<script type="text/javascript">
function cumulativeTestData() {
var closes = JSON.parse('#Html.Raw(Json.Encode(Model.Coordinates))')
return [
{
key: "Prices",
values: closes
},
];
}
</script>
}
You are correct in thinking that there is a conflict when loading the same script multiple times. Only load each script one time.
I can see why trying to remove those scripts from the partial view caused your partial views to fail. You are not loading the scripts until after the partial view. They do not exist until after everything in your partial view has been loaded and executed.
In your layout, move the scripts to the header (preferred) or at least to a point before you pull in the partial view. Then in your partial view, make sure there are no references to scripts which have already been loaded.
In partial views I often use a script wrangler to load in scripts which may or may not have been dynamically loaded. Here is something you can use to attempt to load scripts. It checks to see if a script by the same name has already been loaded on the page (specifically in the header tag) and if it has, it does not attempt to load it again. It's not the prettiest, but it gets the job done.
mycode = function()
{
//Put all your custom javascript here.
//This will run when the scripts below have successfully been processed.
}
var headTag = document.getElementsByTagName("head")[0];
var initialScripts = ["/scripts/jquery-2.1.4.min.js",
"/scripts/jquery-ui.min.js",
"/scripts/jquery.timepicker.min.js"];
var neededScripts = [];
for (var z = 0; z < initialScripts.length; z++) {
if (!isScriptLoaded(initialScripts[z]))
neededScripts.push(initialScripts[z]);
}
if(neededScripts.length)
addScripts(neededScripts, headTag, function () { mycode(); delete mycode; }, 0);
else {
mycode(); delete mycode;
}
function addScripts(scriptsToLoad, loadTag, callback, i) {
if (i >= scriptsToLoad.length)
return;
var script = scriptsToLoad[i];
var scriptTag = document.createElement('script');
scriptTag.setAttribute('type', 'text/javascript');
scriptTag.setAttribute('src', script);
if (i >= (scriptsToLoad.length - 1)) {
scriptTag.onload = callback;
}
else {
scriptTag.onload = function () {
console.log("Added script file " + script);
addScripts(scriptsToLoad, loadTag, callback, i + 1);
}
}
loadTag.appendChild(scriptTag);
}
function isScriptLoaded(url) {
var tags = document.getElementsByTagName('script');
for (var i = tags.length; i--;) {
var existingName = tags[i].src.split('/');
existingName = existingName[existingName.length-1];
var newName = url.split('/');
newName = newName[newName.length-1];
if (existingName == newName) return true;
}
return false;
}
I am using AngularJS to display results of my API (my first attempt at AngularJS), and want to use Jquery to add some effects to the page.
The problem is, Jquery seems to load before Angular has time to add images and other elements to the page. This prevents the JQuery effects from working I have been through numerous answers and tutorials, which center around the following solutions, none of which have worked for me.
Another approach suggested was to put the JQuery into "directives", but how would I put the contents of 3 large javascript libraries into an AngularJS directive? Sorry, I'm new in Javascript!
Here are the unsuccessful attempts:
$(window).load(function() {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
<!-- after Angular is loaded !-->
angular.element(document).ready(function () {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
<!-- after Jquery-main is loaded !-->
$(document).ready(function() {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
Here are the relevant extracts of my code:
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>MyWebpage</title>
<!-- Template includes !-->
<link media="all" rel="stylesheet" href="./css/slider-revolution.css">
<link media="all" rel="stylesheet" href="./css/all.css">
<link media="all" rel="stylesheet" href="./css/style.css" class="color">
</head>
<body ng-app=“myApp">
<div ui-view></div>
</body>
<!-- Application Dependencies -->
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-ui-router/build/angular-ui-router.js"></script>
<!-- Template scripts !-->
<!-- Application Scripts -->
<script src="scripts/app.js"></script>
<script src="scripts/indexController.js"></script>
app.js :
...
state('index', {
url: '/',
templateUrl: '../views/indexView.html',
controller: 'IndexController as user'
...
indexView.js
...
<!— JQuery plugin gallery -->
<div class="gallery responsive">
<div class="mask" ng-if=“myStuff.banner">
<ul class="slideset">
<ul style="margin:0px; padding:0px">
<li class="slide" data-transition="slidedown" data-slotamount="10" data-masterspeed="300" data-thumb="" ng-repeat="banner in user.banner" width="300">
<! -- load a big ol’ picture !—>
<img ng-src="../../storage/img/{{banner.image.image_url}}">
<div class="caption text-box lfl lfl" data-x="-91" data-y="140" data-speed="300" data-start="800" data-easing="easeOutExpo">
<h1><span>{{banner.banner_title}}</span></h1>
<a class="more" href="{{banner.banner_link}}">READ MORE</a>
<div style="" class="tp-leftarrow tparrows default"></div>
<div style="" class="tp-rightarrow tparrows default"></div>
</div>
</li>
</ul>
</div>
</div>
...
indexController.js:
...
// gets all the data from my API, including image src
vm.getMyStuff = function() {
$http.get('http://localhost:8888/api/public/myapistuff).success(function(myStuff) {
vm.myStuff = myStuff;
}).error(function(error) {
vm.error = error;
});
}
}
})();
$(window).load(function() {
// load JQuery plugins
$.getScript("./js/plugins.all.min.js");
});
I am following this tutorial to integrate SignalR to my project http://venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/
So basically this is my View where I want to show my table.
#{
ViewBag.Title = "PatientInfo";
}
<h2>PatientInfo</h2>
<h3>#ViewBag.pName</h3>
<h5>#ViewBag.glucoseT</h5>
#if (Session["LogedUserFirstname"] != null)
{
<text>
<p>Welcome #Session["LogedUserFirstname"].ToString()</p>
</text>
#Html.ActionLink("Log Out", "Logout", "Home")
<div class="row">
<div class="col-md-12">
<div id="messagesTable"></div>
</div>
</div>
<script src="/Scripts/jquery.signalR-2.2.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/SignalR/Hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.dataHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
alert("connection started")
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages() {
var tbl = $('#messagesTable');
$.ajax({
url: '/home/GetMessages',
contentType: 'application/html ; charset:utf-8',
type: 'GET',
dataType: 'html'
}).success(function (result) {
tbl.empty().append(result);
}).error(function () {
});
}
</script>
}
My project is running but the table doesn't appear at all. I started by pasting the view because I believe that the scripts are not executed in the first place; The Alert Message is NOT being shown even if I try to add one directly after
$(function () {
alert("I am an alert box!");
This is my Layout.cshtml file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<div class="content-wrapper">
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#p_table").dataTable();
});
</script>
#RenderSection("scripts", required: false)
</body>
</html>
I am using Visual Studio 2012, MVC4.
Please Help..
Make sure you have placed all your script tags from the view inside the scripts section of the view:
#section scripts {
... your <script> tags come here
}
The reason why your alerts don't work is because you have directly put them inside the body of the view which gets rendered at the #RenderBody() call of the Layout. But as you can see it's only at the end of this Layout that we have references to the scripts such as jQuery and signalr.
Now they will appear at the proper location: #RenderSection("scripts", required: false).
By the way use the console window in your webbrowser to see potential script errors you might have. For example in your case it would display that jQuery is not defined error.
Another remark: don't include signalR script twice: right now you seem to have included jquery.signalR-2.2.0.js in your view and jquery.signalR-2.2.0.min.js in your Layout.
I'm trying to update the content of a div (#slide-content) on clicking certain navigation elements (h2.pagenav). The content structure is uniform, and each requested HTML document contains two such nav elements ('Previous','Next'). However, my listener only fires once—for click events on the initial nav button present at page load, and I don't understand why.
My understanding is that when using jQuery's append() function instead of html(), the appended content should be registered with the DOM and thus available for event listening. Lil' help?
The page structure is pretty simple:
The HTML
<?php require('common.php'); ?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ethogram Lab</title>
<link rel="stylesheet" href="css/foundation.css"/>
<link rel="stylesheet" href="css/foundation-icons.css"/>
<link rel="stylesheet" href="css/app.css"/>
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<div id="slide-content">
<div class="slide">
<div class="row">
<div class="row">
<!---- content ---->
</div>
<div class="row">
<div class="small-4 small-centered columns">
<h2 data-link="slide_0" class="medium button expand text-center pagenav">Start <i class="fi-play"></i></h2>
</div>
</div>
</div>
</div>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script src='js/app.js'></script>
</body>
</html>
The Javascript
And here is the relevant it of app.js
/**
* PAGE VARS
*/
var DS = '/';
var WEBROOT = "127.0.0.1"+DS+"ethogram"+DS;
var PHP = ".php";
/**
* DOM LISTENERS
*/
$(".pagenav").click(function() {
console.log("*** pagenav listener has fired");
var loc = $(this).attr('data-link');
var pageNum = loc.substr(-2) == "_" ? loc.substr(-1) : loc.substr(-2);
var URL = WEBROOT+"slides"+DS+loc+PHP;
$.get(URL, function(data) {
$("#slide-content").html('').append(data).fadeIn();
});
});
The ".on()" function should be used. ".live()" is deprecated.
.on() function
$("body").on("click", ".pagenav", function() {
// do something
});
You should use
$("body").on ("click",".pagenav",function(){
// Your code go here
})
This function will detect the items created programatically
See Documentation