How to load Header HTML file in each page - javascript

I have an HTML Header page which is consist of nav bar which is loaded dynamically and i have several other pages also.
i want to include the Navbar (Header.html) in each of my page to reduce the code i am doing the right thing like this using J Query .load function and it is working fine also
the issue i a facing is my i have Bootstrap 4 navbar and in other pages i have an form by clicking on the submit of the form i am rendering an HTML table which has an export button also,and i am using table2export cdn to export table into the excel
so when i load my header with the table it shows an error Uncaught TypeError: $(...).table2excel is not a function when i remove and writing the navbar code in each page rather than loading it into each page then it is working fine
HTML
<div id="header"></div>
<h4 class="text-center">Date wise Outlet wise Sales Summary :</h4>
<form id="formId" method="get">
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()" />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required onchange="checkDate()"/>
<h4>Outlets:</h4>
<select name="outlet" id="myselect">
<option>ALL</option>
</select>
<div><br>
</div>
<div>
<br>
<button id="button" class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
<div class="loader"></div>
<div class="overlay"></div>
<div id="tbl"></div>
<button id="export-btn">
<i class="fa fa-file-excel-o" aria-hidden="true"></i> Export
</button>
<div style="padding-bottom: 100px">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gijgo#1.9.6/js/gijgo.min.js"
type="text/javascript"></script>
<script src="https://rawgit.com/unconditional/jquery able2excel/master/src/jquery.table2excel.js"></script> //using this one to export
<script type="text/javascript" src="JS/Datewiseolwise.js"></script> // this is for table rendering js code
<script type="text/javascript" src="JS/headerfooter.js"></script> //this is my header javascript file
<script type="text/javascript" src="JS/Date.js"></script>
<script type="text/javascript" src="JS/Outletlist.js"></script>
**javascript for loading the header in each page**
$(document).ready(function() {
$("#header").load("Header.html");
});
and here is my navbar code
<nav
class="navbar navbar-expand-sm bg-dark navbar-dark navbar fixed-top">
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul id="navbarId" class="navbar-nav mr-auto">
</ul>
</div>
<a class="navbar-brand" href="Header.html">HOME</a>
</nav>
<div style="padding: 30px"></div>
<div class="col-sm-12">
<div class="name"></div>
<hr style="border: solid 1px black">
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<script type="text/javascript" src="JS/Header.js">
</script>
i thing there is problem in placing thecdn of table2excel at right place but i have tried hard its not working and throwing same error
anyone out there please check what i am missing
header5.js script
$(document).ready(function() {
$.ajax({
url : "HeaderServlet",
method : "GET",
success : function(data) {
for (var item in data) {
var _menu = "";
var _submenuData = data[item];
if(_submenuData.length > 0) {
var _submenu = "";
for(var i = 0; i < _submenuData.length; i++) {
_submenu += "<a class='dropdown-item' href='" + _submenuData[i]["link"] + "'>" + _submenuData[i]["type"] + "</a>";
}
_menu = "<li class='nav-item dropdown'>"
+ "<a class='nav-link dropdown-toggle' href='' id='navbardrop' data-toggle='dropdown'> " + item + " </a>"
+ "<div id='drop' class='dropdown-menu'>"
+ _submenu
+ "</div>"
+ "</li>";
}
$("#navbarId").append(_menu);
}
var _logout = "<li class='nav-item'>" +
"<a class='nav-link' href='Logout'> Logout </a>" +
"</li>";
$("#navbarId").append(_logout);
}
});
$.ajax({
url : "LoginServlet",
method : "GET",
success : function(data) {
$(".name").text("Welcome '" +data[0].Name + "'-" +data[0].Companyname)
}
});
});

Hello first of open console and write simple "table2excel" check library load or not ?
If library is loaded then use like
$("#yourHtmTable").table2excel({
exclude: ".excludeThisClass",
name: "Worksheet Name",
filename: "SomeFile" //do not include extension
});
CDN

Related

bootstrap 5 popover with html content

I am trying to get separate the bootstrap5 popover content from the HTML attributes like you can do with other components, but I can't get it to work.
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover">Click to toggle popover</a>
<div id="customdiv" style="display: none">
<h1> popover </h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
Nobody answered properly with simple JavaScript without jQuery dependency. It's important because Bootstrap 5 doesn't depend on jQuery anymore.
HTML:
<a class="btn btn-link" data-bs-toggle="popover" data-bs-placement="bottom" data-bs-content-id="popover-content" tabindex="0" role="button">
Open Popover
</a>
<div id="popover-content" class="d-none">
Popover content with <strong>HTML</strong>.
</div>
JavaScript:
const list = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
list.map((el) => {
let opts = {
animation: false,
}
if (el.hasAttribute('data-bs-content-id')) {
opts.content = document.getElementById(el.getAttribute('data-bs-content-id')).innerHTML;
opts.html = true;
}
new bootstrap.Popover(el, opts);
})
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl,{html: true})
});
None of the answers really offered me a complete solution where the popover does not appear until the data-bs-trigger event happen so this is my solution:
Element that when hovering on will have popover:
<a class="btn btn-question-tag"
data-bs-toggle="popover"
data-bs-trigger="hover focus"
data-content-id="popover-27"
href="#">
element to trigger popover
</a>
Element that its inner html will be in the popover that appears.
<div style="display: none;" id="popover-27">
<div class="popover" role="tooltip">
This is the
</div>
</div>
javascript:
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
const popoverId = popoverTriggerEl.attributes['data-content-id'];
if (popoverId) {
const contentEl=$(`#${popoverId.value}`).html();
return new bootstrap.Popover(popoverTriggerEl, {
content: contentEl,
html: true,
});
}else{//do something else cause data-content-id isn't there.
}
}
There is a simple way to put an html element in popover container
you must put the html element directly in data-bs-content tag,
and set the data-bs-html="true" to parse that content as html
and also disable the sanitize to make the content readable as html
this code works for me try it too.
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" data-bs-toggle="popover"
data-bs-html="true" data-bs-sanitize="false"
data-bs-content='<div class="popover fs-6" role="tooltip">
<div class="popover-body">Providing your birthday helps make sure you get the right Facebook experience for your age. If you want to change who sees this, go to the About section of your profile. For more details, please visit our Data Policy.</div></div>'>Click to toggle popover</a>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
Bootstrap v5.2.0 and laravel 8 in app.js
document.addEventListener('DOMContentLoaded', function() {
var element = document.getElementById('myPopover');
if (element) {
var popover = new bootstrap.Popover(element, {
container: 'body',
html: true,
content: function() {
return document.getElementById('popover-content').innerHTML;
},
});
}
});
Laravel blade
<a tabindex="0" type="button" data-bs-toggle="popover" data-bs-placement="bottom" aria-label="Share this article socially" id="myPopover" >
<img src="{{asset('layout/icon_return.svg')}}" alt="share icon">
</a>
<div class="pop-in" id="popover-content" style="display:none;"> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group" role="group" aria-label="First group">
<a class="btn btn-secondary" href="https://www.facebook.com/sharer.php?u={{ $item->url }}" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/facebook.svg')}}" alt="Share Page on Facebook" ></a>
<a class="btn btn-secondary" href="https://twitter.com/intent/tweet?url={{ $item->url }}%2F&text={{ $item->title }}.&hashtags=css,html" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/twitter.svg')}}" alt="Share Page on Twitter"></a>
<a class="btn btn-secondary" href="https://www.linkedin.com/shareArticle?mini=true&url={{ $item->url }}%2F&item={{ $item->title }}" target="_blank" rel="noopener" type="button" ><img src="{{asset('layout/linkedin.svg')}}" alt="Share Page on LinkedIn" ></a>
</div>
</div>
</div>
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
return new bootstrap.Popover(popoverTriggerEl)
})
var popover = new bootstrap.Popover(document.querySelector('.element'), {
trigger: 'hover',
html: true,
content:function () {
return '<label>Test</label>';
},
})
Although the above answers looks fine but there is small correction here. Content option in bootstrap 5 is not working with innerHTML as it expects the type element/string/function to get the content from.
So as usual, first we will need to create div for the content with some id and then wrap it inside hidden div as this will be also shown in main flow. And then with html and content options provided by bootstrap popover, we will insert the custom popover content.
Also, instead of innerHTML, we will directly have document.getElementById('mypopover-content') as the popover content element to show as the content (and not document.getElementById('mypopover-content').innerHTML).
var popover = new bootstrap.Popover(document.querySelector('.example-popover'), {
container: 'body',
html: true,
content: document.getElementById('mypopover-content'),
})
body {
margin: 10px !important;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js"></script>
<a class="btn btn-primary example-popover" role="button" tabindex="0" title="Content demonstration popover"
>Trigger popover with other html content</a>
<div hidden>
<div id="mypopover-content">
<p>This is the custom popover html content that should be inserted into my example popover</p>
<button type="button" class="btn btn-primary">and the button as well</button>
</div>
</div>
var hideDiv = document.getElementsByClassName('hide')[0].style.visibility = 'hidden'
var popoverBtn = document.getElementById('btn-action')
var popover = new bootstrap.Popover(popoverBtn, {
placement: 'bottom',
html: true,
content: function() {
return document.getElementById('id-content-div');
}
})
var showDiv = document.getElementsByClassName('hide')[0].style.visibility = 'visible'
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<a type="button" class="btn btn-lg btn-danger" id="btn-action">Click to toggle popover</a>
<div id="id-content-div" class="hide">
<h1> popover </h1>
<p>Hello popover world</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
$(function() {
var options = {
html: true,
title: "Optional: HELLO(Will overide the default-the inline title)",
//html element
content: $("#popover-content")
//Doing below won't work. Shows title only
//content: $("#popover-content").html()
}
var exampleEl = document.getElementById('example')
var popover = new bootstrap.Popover(exampleEl, options)
})
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.5.0/font/bootstrap-icons.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="popover-content">
<div class="input-group">
<input type="text" class="form-control form-control-sm" placeholder="Search" name="search">
<div class="input-group-btn">
<button class="btn btn-danger" type="submit">
<i class="bi bi-search"></i>
</button>
</div>
</div>
<div class="col-sm-8"></div>
<button class="btn btn-success m-3">Button</button>
<input type="submit" class="btn btn-danger" placeholder="Button red">
</div>
<a id="example" tabindex="0" class="btn btn-lg btn-danger" role="button" data-bs-toggle="popover" title="Default: Html inside popover" data-bs-content="And here's some amazing content. It's very engaging. Right? This is default, but Can be empty">Html inside popover</a>
You can't have a zero length title and content. From the Bootstrap docs...
"Zero-length title and content values will never show a popover."
<a type="button" class="btn btn-lg btn-danger"
data-bs-toggle="popover"
data-bs-title="Hello">Click to toggle popover</a>
Demo

Can't add checkout and clear cart buttons in popover in bootstrap 5

I am using BootStrap version 5.0.0 beta-2, I'm trying to add button dynamically in my popover which I can't. I've included scripts in the following order:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
My code to update popover is like this:
// Updating Popover
function updatePopover(cart) {
popStr = "";
i = 1;
popStr = popStr + "<div class='my-2 mx-1'>";
for (item in cart) {
popStr = popStr + "<b>" + i + ". </b>";
popStr = popStr + document.getElementById('name' + item).innerHTML + " | <b>Qty:</b> " + cart[item] + "<br>";
i += 1;
}
// Adding Clear Cart and Checkout buttons
popStr = popStr + "</div> <a href='/shop/checkout'><button class='btn btn-primary' id='checkout'>Checkout</button></a> <button class='btn btn-primary' id='clearCart' onclick='clearCart();'>Clear Cart</button>";
console.log(popStr);
// Getting popcart by ID
var popcart = document.getElementById('popcart')
// Enabling popover
var popover = new bootstrap.Popover(popcart, 'data-bs-content')
// Setting new value of popcart
popcart.setAttribute('data-bs-content', popStr);
// Showing the popover
popover.show();
}
My HTML division is like this:
{% for i in product %}
<div class="col-xs-3 col-sm-3 col-md-3">
<div class="card align-items-center" style="width: 18rem; border: 0px;">
<img src="/media/{{i.product_img}}" class="card-img-top" alt="{{i.product_name}}">
<div class="card-body text-center">
<h6 class="card-title" id="namepid{{i.id}}">{{i.product_name}}</h6>
<p class="card-text">{{i.product_desc|slice:":25"}}{% if i.product_desc|length > 25 %}...{% endif %}</p>
<span id="divpid{{i.id}}" class="divpid">
<button id="pid{{i.id}}" class="btn btn-warning cart">Add to Cart</button>
</span>
<button id="vid{{i.id}}" class="btn btn-primary cart">View Product</button>
</div>
<!-- card body text end-->
</div>
<!-- card body items end-->
</div>
<!-- col-xs-3 col-sm-3 col-md-3 end-->
{% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %}
</div>
<div class="carousel-item">
{% endif %} {% endfor %}
</div>
Do this
$("#popcart").popover({
html: true,
sanitize: false
});
Okay so I went to BootStrap v5.0 's beta version's documentation and I got to know that by default it sanitized many HTML elements, thus even though I was writing code to add buttons they were being sanitized at the time of showing popover. To prevent the buttons from being sanitized, I added the following lines in my JS:
var myDefaultAllowList = bootstrap.Tooltip.Default.allowList;
myDefaultAllowList.button = ['type', 'onclick'];
Here providing the list of attributes that I don't want to be automatically sanitized.

Issues integrating response from OpenWeatherMap in to my HTML

I'm using the OpenWeatherMap API to get to display certain items in HTML and my code does not display them.
$('.`btn`').click(function() {
var city = $('.inputValue').val();
var key = '88da1611665dfe9338cd6679dee95466';
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather',
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric'
},
success: function(data) {
var temp = '';
$.each(data.weather, function(index, val) {
wf += '<p><b>' + data.name + "</b><img src=" + val.icon + ".png></p>" +
data.main.temp + '°F ' + ' | ' + val.main + ", " +
val.humidity + val.wind + val.uv
}, $("showWeather").html(temp));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="4">
<nav class="navbar navbar-light bg-light">
<p><b>Search for a city:</p></b>
<form class="d-flex">
<input type="search" class="inputValue" placeholder="" aria-label="Search">
<button class="btn btn-outline-success">
<i class="fas fa-search"></i>
</button>
</form>
</nav>
</div>
</div>
<div class="col-8">
<div class="row">
<h2 id="showWeather" class="date"></h2>
<p>Temperature:</p>
<p>Humidity:</p>
<p>Wind Speed:</p>
<p>UV Index:</p>
</div>
</div>
</div>
There's quite a few individual issues in your code:
You have backticks in the .btn selector which are invalid, remove them.
You need to prevent the standard form submission so that the AJAX call can fire and return data without the page refreshing. To do this call preventDefault() on the event which is fired, ideally on the submit of the form, not click of .btn.
</p></b> tags are the wrong way around
.html(temp) needs to be placed outside the each(), and definitely not as an additional argument passed to it
wf += should be temp += as that's what your variable is called
You can use map() along with template literals to build the HTML string more succinctly.
You're missing the # on $('showWeather')
wind is an object so you can't concatenate it to the string directly. Access its speed or deg properties (or both).
humidity is a property of main, not the weather you're looping through
There is no uv property anywhere in the response, so that needs to be removed.
With all that fixed, try this:
$('.d-flex').on('submit', function(e) {
e.preventDefault();
var city = $('.inputValue').val();
var key = '88da1611665dfe9338cd6679dee95466';
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather',
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric'
},
success: function(data) {
let html = data.weather.map(loc => `<p><b>${data.name}</b><img src="${loc.icon}.png" /></p>${data.main.temp}°F | ${loc.main}, ${data.main.humidity}%, ${data.wind.speed}kph # ${data.wind.deg}°`);
$("#showWeather").html(html);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="4">
<nav class="navbar navbar-light bg-light">
<p><b>Search for a city:</b></p>
<form class="d-flex">
<input type="search" class="inputValue" placeholder="" aria-label="Search" value="miami">
<button class="btn btn-outline-success">
Search
<i class="fas fa-search"></i>
</button>
</form>
</nav>
</div>
</div>
<div class="col-8">
<div class="row">
<h2 id="showWeather" class="date"></h2>
<p>Temperature:</p>
<p>Humidity:</p>
<p>Wind Speed:</p>
<p>UV Index:</p>
</div>
</div>
</div>

Code mirror not working with angular js binding variable

Html:
<body ng-app ng-controller="OrderFormController">
<!--<h1 class="errorHeader">List of Classes</h1>-->
<header>
<div class="container">
<div id="branding">
<h1>Apex <span class="highlight"> Editor </span> </h1>
</div>
</div>
</header>
<div class="col-md-12 col-lg-12">
<div class="panel with-nav-tabs panel-default">
<div class="panel-heading">
<ul class="nav nav-tabs">
<li class="active">Apex Editor</li>
</ul>
</div>
<div class="panel-body">
<div>
<input type="text" name="apexClass" id="autocomplete" placeholder="Type the name of the Apex class you want to edit"/>
</div>
<div class="btn-group-vertical" style="padding: 1%">
<button type="button" class="btn btn-primary" id="editBtn">Edit</button>
</button>
</div>
<div class="tab-content" align="left">
<div id='error' style='display:none'>{{apexClassWrapperError.message}}</div>
<div>{{apexClassWrapper.name}}</div>
<img src="../img/ajax-loader.gif" id="loaderImage" style='display:none'>
<form>
<textarea ng-model="apexClassWrapper.body" id="code" name="code" readonly="true" >{{apexClassWrapper.body}}</textarea>
</form>
</div>
<button type="button" class="btn btn-primary" id="saveBtn" ng-click="postdata(apexClassWrapper)">Save</button>
</div>
</div>
</div>
<script src="../js/makeEditable.js"></script>
<script>
$(function() {
var editor = CodeMirror.fromTextArea(document.getElementById("code"),{
linenumber : true,
matchBrackes: true,
mode: "text/x-apex"
})
});
</script>
<footer>
<p>Web based Apex Editor</p>
<p>Developed By - Nagendra Kumar Singh</p>
</footer>
</body>
CSS and JS files included at top:
<script src="../js/codemirror.js"></script>
<script src="../js/apex.js"></script>
<script src="../js/matchbrackets.js"></script>
<link href="../css/codemirror.css" rel="stylesheet"/>
The controller is a simple one fetching the class through a RESTApi.
function OrderFormController($scope, $http) {
$('#autocomplete').autocomplete({
type: 'POST',
serviceUrl: 'http://localhost:8989/getSuggestion',
onSelect: function (suggestion) {
console.log('suggestion.value -> '+suggestion.value);
var data = {
apexClassName:suggestion.value
};
var config = {
params: data
};
$('#loaderImage').show();
$http.get("http://localhost:8989/getApexBody",config).then(function (response) {
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
});
}
});
};
But I can only see {{apexClassWrapper.body}} in my text area, I dont see the real code when using CodeMirror, If I remove code mirror , I can see the class, but I cannot figure out a way to show the body with CodeMirror included.
There are no errors in console log and all the JS and CSS files are loaded perfectly. Please help.
Ok, So I think I may have figured it out. What I did is I set a timeout for the codemirror code to run as follows in the js file and removed it from the index.html.
$('#loaderImage').show();
$http.get("http://localhost:8989/getApexBody", config).then(function (response) {
$scope.apexClassWrapper = response.data;
$('#loaderImage').hide();
if(globalEditor) {
globalEditor.toTextArea();
}
setTimeout(function (test) {
var editor = CodeMirror.fromTextArea(document.getElementById('apexBody'), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-apex"
});
globalEditor = $('.CodeMirror')[0].CodeMirror;
}), 2000
});
The only issue in this answer is that, it creates multiple code editor window when I try to load different classes. How can I resolve that?
So finally got it working, defined a global variable and using the method toTextArea

How to create input suggestions with JQuery

I'm struggling to create an input field that auto-suggests from a list of strings. I've been trying a few different tutorials and finally looked at a pretty simple example from the official documentation, but for some reason I just can't get anything to work.
HTML for the input box
<div id="searchfield">
<input type="text" id="CollegeNameInput"
class="form-control biginput"
placeholder="Search for your University"
onkeydown="submitCollegeNameForm(event)">
</div>
JavaScript for autocomplete
$("#CollegeNameInput").autocomplete({
lookup: collegeList,
onSelect: function (suggestion) {
alert('you selected '+suggestion.value+' which has data'+suggestion.data);
}
});
I've placed the full html file here and the full javascript file here in case these samples aren't enough. There's a few commented out lines here and there as I've changed a few things around from a tutorial I'd been following.
The idea is that I'd like people to start typing the name of their university and a list of suggestions will pop up from them to select from. For whatever reason I can't seem to get the jquery UI plugin to make any suggestions show up at all. Any suggestions would be greatly appreciated!
In your html page you have only jquery-ui and bootstrap libraries so I'm guessing you are using jquery-ui autocomplete in that case you don't have a lookup option there... you need to pass the option as a source
So
$("#CollegeNameInput").autocomplete({
source: collegeList,
onSelect: function (suggestion) {
//var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value + ' <br> <strong>Symbol:</strong> ' + suggestion.data;
//$('#outputcontent').html(thehtml);
alert('you selected ' + suggestion.value + ' which has data' + suggestion.data);
}
});
Also looks like you have forgot to include the jQuery UI css file, include that too
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/redmond/jquery-ui.css">
Demo
/**
* Created by Jake on 1/16/2015.
*/
window.onload = function() {
//$("CollegeNameInput").style = 'background-color: red;';
}
//setup college list
var collegeList = [{
value: 'Purdue University',
data: 'purdue'
}, {
value: 'Cal Poly Slo',
data: 'calpolyslo'
}, {
value: 'Sample College',
data: 'samplecollege'
}, ]
function submitCollegeNameForm(event) {
if (event.keyCode == 13 || event.which == 13) {
messageBox = getCollegeNameElement();
messageString = messageBox.value;
sessionStorage.setItem('uniName', messageString);
window.location.href = "classPage.html";
}
}
function getCollegeNameElement() {
var panel = document.getElementById("CollegeNameInput");
return panel;
}
//// setup autocomplete function pulling from currencies[] array
$("#CollegeNameInput").autocomplete({
source: collegeList,
onSelect: function(suggestion) {
//var thehtml = '<strong>Currency Name:</strong> ' + suggestion.value + ' <br> <strong>Symbol:</strong> ' + suggestion.data;
//$('#outputcontent').html(thehtml);
alert('you selected ' + suggestion.value + ' which has data' + suggestion.data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!--jQuery UI-->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>
<!--Bootstrap-->
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.css">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.js"></script>
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">ClassChat</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home
</li>
<li>About
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="jumbotron" style="margin-top: 100px">
<h1>Jump into ClassChat!</h1>
<div class="row">
<div class="col-md-3">
<p>Enter your University:</p>
</div>
<div class="col-md-5">
<div id="searchfield">
<input type="text" id="CollegeNameInput" class="form-control biginput" placeholder="Search for your University" onkeydown="submitCollegeNameForm(event)">
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
</div>
<!-- /.container -->

Categories

Resources