JavaScript: Basic function to go back/forward - javascript

So, I made a JavaScript function which helps me to define several parts that are hidden at first but can be shown when clicking a link (I suck at explaining, sry... you'll see what I mean when having a look at the code snippet)
The idea that I had then was to make a function that would show the next 'page' (make the id 1 higher) and another function that would go one 'page' back (reduce the id by 1, so to speak).
Here's the JS and HTML code:
function change_page (id) {
var content_raw = document.getElementById(id);
var content = content_raw.innerHTML;
var display = document.getElementById('replace');
display.innerHTML = content;
}
function page_back () {
//function to go one page back
}
function page_forward () {
//function to go one page forward
}
<div id='replace'>
This is page 1 (shown by default)
</div>
<div style='display:none;'>
<p id="1">This is page 1</p>
<p id="2">This is page 2</p>
<p id="3">This is page 3</p>
<p id="4">This is page 4</p>
<p id="5">This is page 5</p>
</div>
<p style="text-align:center; width:100%;">
Back
Page 1 |
Page 2 |
Page 3 |
Page 4 |
Page 5
Forward
</p>
I really hope that you guys can help me because although I can programm quite well in PHP, I hardly can with JS.

Create a helper variable
var currentPage = 1;
Then, in the change_page function you would always update this value
function change_page (id) {
currentPage = id;
...
And the page_back/page_forward would be calling change_page function with either increased or decreased value of currentPage. So page_back could look like this
function page_back() {
change_page(currentPage - 1);
}
Lastly, you need to make sure that the page_back and page_forward will never result in trying to load a page below 1/above the actual number of pages. To secure that, in the change_page function, you could check whether id is not less than 1 and at the same time it is smaller than max number of pages. The check could look like
function change_page (id) {
if (id < 1 || id > 5)
return;
currentPage = id;
...

Just make a global variable to store the current page you're in.
function change_page (id) {
_currentPage = id;
var content_raw = document.getElementById(_currentPage);
var content = content_raw.innerHTML;
var display = document.getElementById('replace');
display.innerHTML = content;
}
function page_back () {
change_page(_currentPage-1);
}
function page_forward () {
change_page(_currentPage+1);
}
// global variable
var _currentPage;
<div id='replace'>
This is page 1 (shown by default)
</div>
<div style='display:none;'>
<p id="1">This is page 1</p>
<p id="2">This is page 2</p>
<p id="3">This is page 3</p>
<p id="4">This is page 4</p>
<p id="5">This is page 5</p>
</div>
<p style="text-align:center; width:100%;">
Back
Page 1 |
Page 2 |
Page 3 |
Page 4 |
Page 5
Forward
</p>

Try This Code
Working JSFIDDLE Here
var curPage = 0;
function change_page (id) {
var content_raw = document.getElementById(id);
curPage = parseInt(id);
var content = content_raw.innerHTML;
var display = document.getElementById('replace');
display.innerHTML = content;
}
function page_back () {
//function to go one page back
if(curPage==1)
return;
var content_raw = document.getElementById(curPage-1);
curPage = curPage-1;
var content = content_raw.innerHTML;
var display = document.getElementById('replace');
display.innerHTML = content;
}
function page_forward () {
if(curPage==5)
return;
var content_raw = document.getElementById(curPage+1);
curPage = curPage+1;
var content = content_raw.innerHTML;
var display = document.getElementById('replace');
display.innerHTML = content;
}
<div id='replace'>
This is page 1 (shown by default)
</div>
<div style='display:none;'>
<p id="1">This is pagse 1</p>
<p id="2">This is paage 2</p>
<p id="3">This is page 3</p>
<p id="4">This is page 4</p>
<p id="5">This is page 5</p>
</div>
<p style="text-align:center; width:100%;">
Back
Page 1 |
Page 2 |
Page 3 |
Page 4 |
Page 5
Forward
</p>
Working Demo Here

Related

how to capture p elements value when click event happened using JavaScript

Here is my code. I want to capture Nebula and Price 1.44 when I click on button. Can anyone help me please.
Html code
<div class="item__top">
<p> Nebula</p>
<p>
Price<span class="big-price">1</span>.44
<span class="text-large">/mo</span>
</p>
<p>$2.88</p>
<button class="calculate-hosting">Get Started</button>
<p>You pay $17.28 — Renews at $33.88/year</p>
</div>
JS code
var calHosting = document.querySelectorAll('.calculate-hosting');
[...calHosting].forEach(cal=>{
cal.addEventListener('click',function(event){
document.getElementById('cal-container').style.display='block';
});
});
Note: I am dealing with mutiple buttons so thats why I sued querySelectorAll.
You can use this to refer to the button that was clicked, .parentElement to climb up, and then select paragraphs and their inner text. The text can be parsed however you like from there.
var calHosting = document.querySelectorAll('.calculate-hosting');
[...calHosting].forEach(cal => {
cal.addEventListener('click', function (event) {
var paragraphs = this.parentElement.querySelectorAll("p");
var p1 = paragraphs[0].innerText;
var p2 = paragraphs[1].innerText;
var price = Number(p2.match(/\d+\.\d+/)[0]);
console.log(p1); // Nebula
console.log(p2); // Price1.44 /mo
console.log(price); // 1.44
// document.getElementById('cal-container').style.display = 'block';
});
});
<div class="item__top">
<p> Nebula</p>
<p>
Price<span class="big-price">1</span>.44
<span class="text-large">/mo</span>
</p>
<p>$2.88</p>
<button class="calculate-hosting">Get Started</button>
<p>You pay $17.28 — Renews at $33.88/year</p>
</div>

How to validate data into paragraph's text using javascript?

I want to check if time and day is same when I click to add these paragraphs into the array, If time and day is same then also prevent adding items into an array. Can Anyone help me please.Thanks
window.addEventListener("load", function() {
var test = [];
[...document.querySelectorAll(".container p")].forEach(function(para) {
para.addEventListener("click", function(e) {
var text = e.currentTarget.textContent;
if (test.indexOf(text) === -1)
{
test.push(text);
}
console.log(test)
})
})
})
<div class="container">
<p>
<b>Group:N</b>Code:1234<br/>
<b>Session Type:</b>CS<br/>
<b>Location:</b>Main Hall<br/>
<b>Time:</b>11:00<br/>
<b>Day:</b>Tuesday<br/>
<b>Duration:</b>1hour<br/>
</p>
</div>
<div class="container">
<p>
<b>Group:M</b>Code:98743<br/>
<b>Session Type:</b>NP<br/>
<b>Location:</b>Main Hall2<br/>
<b>Time:</b>11:00<br/>
<b>Day:</b>Tuesday<br/>
<b>Duration:</b>1hour<br/>
</p>
</div>

jQuery Search Function

Hi i'm building a project which has a page navigation and search bar in jQuery.
I can't get my search function to work correctly and I'm not certain if it's a problem with the ID element or the each function. I'm getting the ("Sorry, no student's found!") message for anything that is or isn't a match. So i think there could be a problem with the if statement looking for a match in search function--but not sure.
I'm dynamically adding a search box to my html like this:
function appendSearchBox(){
var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
$(".students").after(search);
// Add click event handler
$("button").click(function() {
searchList();
});
}
this is what my html looks like for a list of students:
<div class="page">
<div class="page-header cf">
<h2 class="students">Students</h2>
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
And then here is the actual search function:
var listStudents = $(".student-list li");
var numStudents = listStudents.length;
function searchList() {
var matched = [];
// Obtain the value of the search input
input = $("#search").val()
// remove the previous page link section
$('.pagination').hide();
// Loop over the student list, and for each student…
listStudents.each(function(){
// ...obtain the student’s name…
var name = $(this).find("h3").val();
// ...and the student’s email…
var email = $(this).find(".email").val();
// ...if the search value is found inside either email or name…
if (name.includes(input) || email.includes(input)) {
// ...add this student to list of “matched” student
matched.push($(this).parent());
}
});
// If there’s no “matched” students…
if (matched.length === 0){
// ...display a “no student’s found” message
var message = ("Sorry, no student's found!");
$(".student-list").hide();
$(".student-list").after(message);
if (matched.length > 10) {
// ...call appendPageLinks with the matched students
appendPageLinks(matched);
}
// Call showPage to show first ten students of matched list
showPage(1, matched);
}
}
adding functions which actually show the students and add navigation
function showPage(pageNum, listStudents) {
// first hide all students on the page
pageNum = parseInt(pageNum);
listStudents.hide();
// Then loop through all students in our student list argument
listStudents.each(function(index){
// if student should be on this page number
if ((index >= ((pageNum*10)-9)) && (index <= (pageNum*10))) {
// show the student
$(this).show();
}
});
}
function getNumPages(numStudents){
numPages = Math.ceil(numStudents/10);
return numPages;
}
function appendPageLinks(numStudents) {
// determine how many pages for this student list
pages = getNumPages(numStudents);
// create a page link section
var nav = "<div class='pagination'><ul>"
for (i=1; i<pages+1; i+=1){
nav += ("<li>" + "" + i + "" + "</li>");
};
nav += ("</ul></div>");
$(".student-list").after(nav);
// define what happens when you click a link
var active = $('.pagination a').click(function(){
// Use the showPage function to display the page for the link clicked
var id = $(this).attr('id');
showPage(id,listStudents);
// mark that link as “active”
active.removeClass('active');
$(this).addClass("active");
});
}
here is how i am calling the functions:
appendSearchBox();
showPage(1, listStudents);
appendPageLinks(numStudents);
UPDATE -- I have changed the code to remove the val and put in to grab the text.
Not sure what issue is but it appears if i have a correct match--it is working (since pagination disappears) but the students do not change on the page. If there is no match then I get the error message, but the error console is saying
Uncaught TypeError: listStudents.hide is not a function
at showPage (main.js:8)
I'm not sure if this is somehow related to how I am passing the 'matched' list?
h3 and span tags have no value, but text content, so replace:
var name = $(this).find("h3").val();
// ...and the student’s email…
var email = $(this).find(".email").val();
with:
var name = $(this).find("h3").text();
// ...and the student’s email…
var email = $(this).find(".email").text();
You are using val() method to read inner text of h3 and span (email). It should be text(). Also you are appending message after the student list every time you couldn't find a student. You could have used one span tag and hide/show based on the search results.
function appendSearchBox() {
var search = "<div class='student-search'><input id='search' placeholder='Search for students...'><button>Search</button></div>"
$(".students").after(search);
// Add click event handler
$("button").click(function () {
searchList();
});
}
$(document).ready(function () {
appendSearchBox();
});
function searchList() {
var listStudents = $(".student-list li");
var numStudents = listStudents.length;
$(".student-list").show();
$("#message").hide();
var matched = [];
// Obtain the value of the search input
input = $("#search").val()
// remove the previous page link section
$('.pagination').hide();
// Loop over the student list, and for each student…
listStudents.each(function () {
// ...obtain the student’s name…
var name = $(this).find("h3").text();
// ...and the student’s email…
var email = $(this).find(".email").text();
// ...if the search value is found inside either email or name…
if (name.includes(input) || email.includes(input)) {
// ...add this student to list of “matched” student
matched.push($(this).parent());
}
});
// If there’s no “matched” students…
if (matched.length === 0) {
// ...display a “no student’s found” message
var message = ("Sorry, no student's found!");
$(".student-list").hide();
$("#message").show();
if (matched.length > 10) {
// ...call appendPageLinks with the matched students
appendPageLinks(matched);
}
// Call showPage to show first ten students of matched list
showPage(1, matched);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="page">
<div class="page-header cf">
<h2 class="students">Students</h2>
</div>
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/67.jpg">
<h3>iboya vat</h3>
<span class="email">iboya.vat#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 07/15/15</span>
</div>
</li>
</ul>
<span id="message" style="display:none;"><br/>Sorry, no student's found!</span>
</div>

Issue with disappearing images on click event (javascript)

I am supposed to build a store for a a javascript assignment. The store has three items and a counter which tallies the total of the items. Each item is updated through a click event which changes the value based on a data attribute defined in the html. It then saves this to cookies and allows us to use what was stored when we get to a checkout page. The cookies store and the totals update, but unfortunately, each time the click event occurs, the image disappears. I have been scouring the code and I cannot see why this is happening. Can anyone help?
$(document).ready(function() {
$("#jeans-line").text(Cookies.get("jeans") || 0)
$("#jeanJacket-line").text(Cookies.get("jeanJacket") || 0)
$("#belt-line").text(Cookies.get("belt") || 0)
$("#total").text(Cookies.get("total") || 0)
//The DOM will be changed to the key value of each cookie or 0
$('.item').click(function() {
itemTotal = parseInt($(this).text())
oneMore = itemTotal + ($(this).data('cost'))
$(this).text(oneMore)
Cookies.set($(this).data('name'), oneMore)
setTotal()
});
// //updating the total cost of the pseudo-items in shopping
function setTotal() {
var jeans = parseInt(Cookies.get("jeans"))
var jeanJacket = parseInt(Cookies.get("jeanJacket"))
var belt = parseInt(Cookies.get("belt"))
Cookies.set("total", (jeans + jeanJacket + belt) || 0)
$("#total").text(Cookies.get("total") || 0)
};
//Enter data and close the modal
var modal = $("#modal-box")
var email_input;
$(".email-submit").click(function(e) {
e.preventDefault();
email_input = $("#email-val").val()
console.log(email_input)
var checkEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (checkEmail.test(email_input)) {
alert("This is a good email!")
Cookies.set("email", email_input)
modal.css("display", "none")
} else {
alert("This is not a valid email address!")
}
});
//closes the model with close click event
$(".close").click(function() {
modal.css("display", "none");
});
}) //closes document.ready
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<div class="item" data-cost="200" data-name="jeans">
<img id="jeansIMG" src="images/jeans.jpg">
<h2 class="item" id="jeans-line"></h2>
</div>
</div>
<div class="col-md-4">
<div class="item" data-cost="300" data-name="jeanJacket">
<img id="jeanJacketIMG" src="images/jean_jacket.jpg">
<h2 class="item" id="jeanJacket-line"></h2>
</div>
</div>
<div class="col-md-4">
<div class="item" data-cost="50" data-name="belt">
<img id="beltIMG" src="images/belt.jpg">
<h2 class="item" id="belt-line"></h2>
</div>
</div>
</div>
<!-- closes the bootstrap row -->
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
<img class="shoppingCart" src="images/shopping_cart.jpg">
<h2 class="totalTitle">The total for these pseudo-products is:</h2>
<h2 id="total"></h2>
</div>
<div class="col-md-4">
</div>
</div>
The reason why images are getting remove is because of this code:
$('.item').click(function () {
itemTotal = parseInt($(this).text())
oneMore = itemTotal + ($(this).data('cost'))
$(this).text(oneMore) // <-- this overrides everything inside div.item
Cookies.set($(this).data('name'), oneMore)
setTotal()
});
Seeing your overall code, I'd suggest to change inner item class to something else (eg. item-total) so it won't be conflicting with the outer item class. After that adjust the javascript code:
$('.item').click(function() {
itemTotal = parseInt($(this).text())
oneMore = itemTotal + ($(this).data('cost'))
$('.item-total', this).text(oneMore) // <!-- change text in item-total
Cookies.set($(this).data('name'), oneMore)
setTotal()
});
You may also want to modify the setTotal to add default value || 0 so that it will calculate the total properly even if there is one or more items left unclicked:
function setTotal() {
var jeans = parseInt(Cookies.get("jeans") || 0)
var jeanJacket = parseInt(Cookies.get("jeanJacket") || 0)
var belt = parseInt(Cookies.get("belt") || 0)
Cookies.set("total", (jeans + jeanJacket + belt) || 0)
$("#total").text(Cookies.get("total") || 0)
};
You can check the simplified demo in https://jsfiddle.net/nm5dL9h1/

Javascript Elements with class / variable ID

There's a page with some HTML as follows:
<dd id="fc-gtag-VARIABLENAMEONE" class="fc-content-panel fc-friend">
Then further down the page, the code will repeat with, for example:
<dd id="fc-gtag-VARIABLENAMETWO" class="fc-content-panel fc-friend">
How do I access these elements using an external script?
I can't seem to use document.getElementByID correctly in this instance. Basically, I want to search the whole page using oIE (InternetExplorer.Application Object) created with VBScript and pull through every line (specifically VARIABLENAME(one/two/etc)) that looks like the above two into an array.
I've researched the Javascript and through trial and error haven't gotten anywhere with this specific page, mainly because there's no tag name, and the tag ID always changes at the end. Can someone help? :)
EDIT: I've attempted to use the Javascript provided as an answer to get results, however nothing seems to happen when applied to my page. I think the tag is ALSO in a tag so it's getting complicated - here's a major part of the code from the webpage I will be scanning.
<dd id="fc-gtag-INDIAN701" class="fc-content-panel fc-friend">
<div class="fc-pic">
<img src="http://image.xboxlive.com/global/t.58570942/tile/0/20400" alt="INDIAN701"/>
</div>
<div class="fc-stats">
<div class="fc-gtag">
<a class="fc-gtag-link" href='/en-US/MyXbox/Profile?gamertag=INDIAN701'>INDIAN701</a>
<div class="fc-gscore-icon">3690</div>
</div>
<div class="fc-presence-text">Last seen 9 hours ago playing Halo 3</div>
</div>
<div class="fc-actions">
<div class="fc-icon-actions">
<div class="fc-block">
<span class="fc-buttonlabel">Block User</span>
</div>
</div>
<div class="fc-text-actions">
<div class="fc-action"> </div>
<span class="fc-action">
View Profile
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Compare Games
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Message
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Friend Request
</span>
</div>
</div>
</dd>
This then REPEATS, with a different username (the above username is INDIAN701).
I tried the following but clicking the button doesn't yield any results:
<script language="vbscript">
Sub window_onLoad
Set oIE = CreateObject("InternetExplorer.Application")
oIE.visible = True
oIE.navigate "http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=12"
End Sub
</script>
<script type="text/javascript">
var getem = function () {
var nodes = oIE.document.getElementsByTagName('dd'),
a = [];
for (i in nodes) {
(nodes[i].id) && (nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
}
</script>
<body>
<input type="BUTTON" value="Try" onClick="getem()">
</body>
Basically I'm trying to get a list of usernames from the recent players list (I was hoping I wouldn't have to explain this though :) ).
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
alert(a[0]);
};
please try it by clicking here!
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
};
try it out on jsbin
<body>
<script type="text/javascript">
window.onload = function () {
var outputSpan = document.getElementById('outputSpan'),
iFrame = frames['subjectIFrame'];
iFrame.document.location.href = 'http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=1';
(function () {
var nodes = iFrame.document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
for (var j in a) if (a.hasOwnProperty(j)) {
outputSpan.innerHTML += (a[j] + '<br />');
}
})();
};
</script>
<span id="outputSpan"></span>
<iframe id="subjectIFrame" frameborder="0" height="100" width="100" />
</body>
What does "I can't seem to use document.getElementsByID correctly in this instance" mean? Are you referring to the fact that you are misspelling getElementByID?
So...something like this (jQuery)?
var els = [];
$('.fc-content-panel.fc-friend').each(function() {
els.push(this));
});
Now you have an array of all the elements that have both of those classes.

Categories