Window onload function is not working properly? - javascript

This is my code :
I have used window onload function to populate ui elements but it is not working properly.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Regalo - Shop</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/bootstrap.min.css" />
<script src="<%=request.getContextPath()%>/resources/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(window).on('load',function(){
alert("OK");
<c:forEach var="item" items="${itemList}">
var name= '${item.desktopbrand}';
var details='${item.details}';
var id = '${item.desktopid}';
var price = '${item.desktopid}';
var catagory = '${item.catagory}';
var spanTag = '<div class="col-sm-6 col-md-4"> <div class="thumbnail"> <img data-src="img/Desktop/'+ id +'.jpg"> <div class="caption"><h3>'+ name+ '</h3> <p>'+ price+ '</div> </p> <p><button type="button" class="btn btn-success btn-lg" onclick="details()">Show Details</button></p><p><button type="button" class="btn btn-success btn-lg" onclick="addToCart()">Buy now</button></p></div></div></div>';
$("#" + catagory).append(spanTag);
</c:forEach>
});
</script>
</head>
<body>
<h1>Gens Cooner</h1>
<div id="gen" class="container"></div>
<h1>Ladies Cooner</h1>
<div id="lad" class="container"></div>
<h1>Childrens Cooner</h1>
<div id="chil" class="container"></div>
</body>
</html>
I try to find the issue but couldn't. Your help would be highly appreciated.

window.onload = function(){ alert('Working!!'); }
Use above function and make sure you use only one window.onload function in a page

Related

Iterate through a JSON list with JS function

I'm looking for a way to append some JSON results, I'm working with a list (array?) and there's multiple elements, I know I can add some styling directly in the JS code but I'm more comfortable with this method. How can I iterate through elements and implement in some divs, then create similar divs with the next elements.
The only way to achieve that goal afaik is like this:
$("#article").append(data[i].datetime + data[i].headline + "<br />" + "<hr />" + data[i].summary);
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Project JS 02</title>
<link rel="stylesheet" href="assets/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" id="getnews">Get News!</button>
<h1 id="headline"></h1><br>
<h3 id="datetime"></h3><br>
<div id="summary"></div><br>
<h6 id="source"></h6><br>
</div>
</div>
</div>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
document.getElementById("getnews").addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
for (i in data)
{
$("#headline").append(data[i].headline);
$("#datetime").append(data[i].datetime);
$("#summary").append(data[i].summary);
$("#source").append(data[i].source);
}
})
})
</script>
</body>
</html>
You can do this by creating the elements (with jQuery) as needed, and appending them to a container:
$("#getnews").on("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$('#data').text("...loading...");
$.getJSON(newsurl, function (data) {
$('#data').html("");
data.forEach(function (article) {
$('#data').append(
$('<h1>').text(article.headline),
$('<h3>').text(article.datetime),
$('<div>').text(article.summary),
$('<h6>').text(article.source)
);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary search"
style="width: 100%" id="getnews">Get News!</button>
<div id="data"></div>
First: remove the ids. If you want to create similar containers, the ids will be there multiple times, that won't work.
Second: Take the div with $('.row.vertical-center-row') and clone it.
Third: set the values at the cloned HTMLNode und append it to $('.container.container-table')
Something like that (untested):
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" class="getnews">Get News!</button>
<h1 class="headline"></h1><br>
<h3 class="datetime"></h3><br>
<div class="summary"></div><br>
<h6 class="source"></h6><br>
</div>
</div>
</div>
<script>
document.getElementsByClassName("getnews").forEach((el)=>el.addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
var $elClone = $('.row.vertical-center-row').clone(true).appendTo($('.container.container-table'));
for (i in data) {
$(".headline", $elClone).append(data[i].headline);
$(".datetime", $elClone).append(data[i].datetime);
$(".summary", $elClone).append(data[i].summary);
$(".source", $elClone).append(data[i].source);
}
})
}));
</script>

onClick with Bootstrap is not working

I want to achieve that after a click on a button (Bootstrap 3.3.7.1) it is marked as active. For that I actually just copy paste a code I found here on stackoverflow. But still, when I test it, the button doesn't show any behavior.
Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="template :: head">
</head>
<body>
<div class="container">
<form method="post" action="specifyDetails">
<h2>Chose what you want to trade</h2>
<label>
<select th:name="Products" class="selectpicker" multiple="multiple">
<!--/*#thymesVar id="productList" type="java.util.List"*/-->
<option th:each="product : ${productList}"><a th:text="${product}"></a></option>
</select>
</label>
<button th:type="submit" class="btn btn-info">Send</button>
</form>
<form><a th:href="'orderview/'" href="#" class="btn btn-default btn-sm" role="button">Orderview only</a>
</form>
<input type="button" class="btn btn-info" value="Input Button"/>
<script>$('.btn-info').click(function(e) {
e.preventDefault();
$(this).addClass('active');
})</script>
</div>
<div th:replace="template :: footer"></div>
</body>
</html>
And here the template.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head">
<meta charset="UTF-8"/>
<!--/*#thymesVar id="title" type="String"*/-->
<title th:text="${title}">Library trader</title>
</head>
<footer th:fragment="footer">
<script th:src="#{/webjars/jquery/3.2.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
<script th:src="#{/webjars/bootstrap-select/1.12.2/js/bootstrap-select.min.js}"></script>
<link th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" rel="stylesheet"/>
<link th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap-theme.min.css}" rel="stylesheet"/>
<link th:href="#{/webjars/bootstrap-select/1.12.2/css/bootstrap-select.min.css}" rel="stylesheet"/>
</footer>
</html>
Thank you very much!
Place click event handler in the footer because you are loading jquery after loading DOM
in footer
like
<footer th:fragment="footer">
<script th:src="#{/webjars/jquery/3.2.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
<script th:src="#{/webjars/bootstrap-select/1.12.2/js/bootstrap-select.min.js}"></script>
<script>$('.btn-info').click(function(e) {
e.preventDefault();
$(this).addClass('active');
})</script>
//rest of the code
</footer>
Add the ready function to your script :
<script>
$(function(){
$('.btn-info').click(function(e) {
e.preventDefault();
$(this).addClass('active');
});
});
</script>
Hope this helps.
I think this the issue. You are finding the element with btn-info CSS Class.
Since there are two elements with the same CSS class name, it's failing to apply on-click event to each element.
So below code works as I'm iterating the $('.btn-info') so that every button with the class has on-click event.
/*$('.btn-info').click(function(e) {
e.preventDefault();
$(this).addClass('active');
})*/
$('.btn-info').each(function( index ) {
$(this).click(function(e) {
e.preventDefault();
$(this).addClass('active');
alert("class Added")
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="template :: head">
</head>
<body>
<div class="container">
<form method="post" action="specifyDetails">
<h2>Chose what you want to trade</h2>
<label>
<select th:name="Products" class="selectpicker" multiple="multiple">
<!--/*#thymesVar id="productList" type="java.util.List"*/-->
<option th:each="product : ${productList}"><a th:text="${product}"></a></option>
</select>
</label>
<button th:type="submit" class="btn btn-info">Send</button>
</form>
<form><a th:href="'orderview/'" href="#" class="btn btn-default btn-sm" role="button">Orderview only</a>
</form>
<input type="button" class="btn btn-info" value="Input Button"/>
</div>
<div th:replace="template :: footer"></div>
</body>
</html>
I hope this might help. Thank you!!

remove label and button when button clicked

I have made two labels(Label1 and Label 2 and two remove button for each labels) by using html, javascript and jquery for my learning purposes.
Now I want the label and button to be removed when the cross button is clicked.
I tried
$(".labels").closest().remove();
But it does not work. Please help
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page 2</title>
</head>
<body>
<div class="container">
<div class="form-group row">
<div class="col-md-2 labels">
<label>Label 1 </label>
</div>
<div class="col-md-1" style="padding-bottom: 5px">
<button class="btn btn-danger btn-xs removeBtn">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
</div>
</div>
<script type="text/javascript">
$(document)
.ready(
function() {
var formGroupRowDiv = $(
document.createElement('div')).attr(
"class", 'form-group row');
var labelTwoDiv = $(document.createElement('div'))
.attr("class", 'col-md-2 labels');
var removeBtnDiv = $(document.createElement('div'))
.attr("class", 'col-md-1 removeBtn');
labelTwoDiv.appendTo(formGroupRowDiv).html(
'<label>Label 2</label>');
removeBtnDiv
.appendTo(formGroupRowDiv)
.html('<button class="btn btn-danger btn-xs removeDate">'
+ '<span class="glyphicon glyphicon-remove"></span>'
+ '</button>');
$(formGroupRowDiv).appendTo('.container');
$(".removeBtn").click(function(e) {
e.preventDefault();
$(".labels").closest().remove();
});
});
</script>
</body>
</html>
Try this:
$("body").click(".removeBtn", function(e) {
$(e.target).parent().parent().siblings().find("label").remove()
});
Since you are dynamically generating the divs, you cant just bind the handler to the divs that appear on load. You need to bind it to something higher up (like body)
e.target here is the removeBtn
.parent() will return a jQuery object of the parent
.siblings() will return all of it [the parent's] siblings
.find() will filter to the passed selector
.remove() will remove it from the DOM
Basically you had 4 problems here:
You don't want to remove all the closest() elements of any .labels element that exists on the page (you want to remove a specific .labels element that is the closest to the current .removeBtn you just clicked.
The closest is not what you are looking for, but actually the prev element.
Since your structure for your HTML is different between the two .removeBtn elements you have - you will need two different selectors.
The first selector will be $(this).prev('.labels') and the second will be $(this).parent().prev('.labels').
If you also want to remove the button that was just clicked - use $(this).remove();.
This is the fist to your code:
$(".removeBtn").click(function(e) {
e.preventDefault();
if ($(this).prev('.labels').length) {
$(this).prev('.labels').remove();
} else if ($(this).parent().prev('.labels').length) {
$(this).parent().prev('.labels').remove();
}
$(this).remove();
});
Here is a working snippet:
$(document)
.ready(
function() {
var formGroupRowDiv = $(
document.createElement('div')).attr(
"class", 'form-group row');
var labelTwoDiv = $(document.createElement('div'))
.attr("class", 'col-md-2 labels');
var removeBtnDiv = $(document.createElement('div'))
.attr("class", 'col-md-1 removeBtn');
labelTwoDiv.appendTo(formGroupRowDiv).html(
'<label>Label 2</label>');
removeBtnDiv
.appendTo(formGroupRowDiv)
.html('<button class="btn btn-danger btn-xs removeDate">'
+ '<span class="glyphicon glyphicon-remove"></span>'
+ '</button>');
$(formGroupRowDiv).appendTo('.container');
$(".removeBtn").click(function(e) {
e.preventDefault();
if ($(this).prev('.labels').length) {
$(this).prev('.labels').remove();
} else if ($(this).parent().prev('.labels').length) {
$(this).parent().prev('.labels').remove();
}
$(this).remove();
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page 2</title>
</head>
<body>
<div class="container">
<div class="form-group row">
<div class="col-md-2 labels">
<label>Label 1 </label>
</div>
<div class="col-md-1" style="padding-bottom: 5px">
<button class="btn btn-danger btn-xs removeBtn">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
</div>
</div>
</body>
</html>

How to print popup window contents

I have tried the following:
<button onclick="window.print()" class="uk-button uk-float-left"><?php echo JText::_('COM_CSTUDOMUS_IMPRIMIR'); ?></button>
Also:
self.print()
window.focus();window.print()
When I click on print it shows the main window and the popup window in the page which is going to be printed. I only need the contents of the popup window.
This is an example of print popup:
<div class="contentSection">
<div class="contentToPrint">
<!-- content to be printed here -->
</div>
</div>
<div class="contentSection">
Print This
</div>
<div class="contentSection termsToPrint">
<h4>Terms & conditions</h4>
<p>Management reserves the right to withdraw, amend or suspend this print job in the event of any unforeseen circumstances outside its reasonable control, with no liability to any third party.</p>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#printOut').click(function(e){
e.preventDefault();
var w = window.open();
var printOne = $('.contentToPrint').html();
var printTwo = $('.termsToPrint').html();
w.document.write('<html><head><title>Copy Printed</title></head><body><h1>Copy Printed</h1><hr />' + printOne + '<hr />' + printTwo) + '</body></html>';
w.window.print();
w.document.close();
return false;
});
});
</script>
//popup page
<html>
<head>
<title>Your popup</title>
</head>
<body>
<h1>Pop</h1>
<p>Print me</p>
<a href="print.html" onclick="window.print();return false;">
<img src="images/printer.png" height="32px" width="32px">
</a>
</body>
</html>
//Main page
<html>
<head>
<title>main</title>
</head>
<body>
<h1>Pop & print</h1>
<button onclick="pop();">Pop</button>
<script type="text/javascript">
var POP;
function pop() {
POP = window.open('popup.html', 'thePopup', 'width=350,height=350');
}
</script>
</body>
</html>

Custom function not showing JQuery plugin

I'm a newbie in Jquery. I'm trying to print text on a document dynamically. I have a JavaScript function that is supposed to display images using the jQuery prettyphoto plugin. My function does not show the images but when I paste the code on a html file it works fine. Please help. A sample of my code is here.
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./index.css" type="text/css">
<script type="text/javascript" charset="utf-8" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="spin.min.js"></script>
<script type="text/javascript" charset="utf-8" src="custom-functions.js"></script>
<link rel="stylesheet" href="./prettyPhoto/css/prettyPhoto.css" type="text/css">
<script type="text/javascript" src="./prettyPhoto/js/jquery.prettyPhoto.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("a[rel^='prettyPhoto_related-content-images']").prettyPhoto({theme:'facebook'});
});
function showImages()
{
var stringData = '';
stringData = stringData + '<div id="related-content-images" >Related to this: <br/>'+
'<img id="not-hidden" src="images/sample-album-2.jpg" alt="" title="">'+
'<img id="related-images" src="images/sample-album-3.jpg" alt="" title="">'+
'<img id="related-images" src="images/sample-album-4.jpg" alt="" title=""></div>';
document.getElementById("content").innerHTML=''+stringData+'';
}
</script>
</head>
<body>
<div id="header"><div id="app-logo-image">
<img src="images/app-logo.png" id="app-logo"/></div>
<div id="header-form">
<input type="search" id="search-text-box" name="search-text-box" placeholder="Search">
<input type="submit" id="search-button" name="" value="Search">
</div>
</div>
<div id="container">
<div id="sub-header-menu">
<div id="music-albums">
<img src="images/music-albums-icon.png" id="music-albums-image"; onclick="fetch('music-albums');"/></div>
<div id="genres-icon">
<img src="images/genres-icon.png" id="genres-icon-image"onclick="fetch('music-genres');"/></div>
<div id="artist-icon">
<img src="images/artists-icon.png" id="artist-icon-image"onclick="fetch('music-artists');"/></div>
<div id="home-icon">
<img src="images/home-button.png" id="home-icon-image"/></div>
</div>
<div id="content" style="left:0%;">
click me
</div>
</div>
</body>
</html>
Your showImages function isn't executed until the link is clicked, however the prettyPhoto initialisation is only run once when the document finishes loading, and since showImages hasn't been run yet prettyPhotos can't find and enhance those images.
If you add this to the end of showImages everything should work:
$('#content a').prettyPhoto({theme:'facebook'});

Categories

Resources