I want to store a value to the cache using javascript when clicking an a href link. I'm setting up following code dynamicall
<a align="left" href="projectoverview.html">Test Manager</a>
So I want to save the text Test Manager to the cache, but I don't know how to catch this text when it's clicked. The code below is how that piece of code is setup. Do I need to add an onclick or something or is there a better way?
var text = '<a align=\"left\" href=\"projectoverview.html\">' + project['title']
+ '</a><p align=\"right\">';
If you want to pass data from page to page using javascript/jquery you can do so with sessionStorage. Below is just an example of how you would do it using jQuery.
$('a').each(function() {
$(this).on('click', function() {
var linkText = $(this).text();
// Save data to sessionStorage
sessionStorage.setItem('clickedLink', linkText);
});
});
Then on the next page you can call it by using the .getItem function like so.
$(function() {
var data = sessionStorage.getItem('clickedLink');
alert(data);
});
If implemented correctly the alert box will say "Test Manager".
You can read more about sessionStorage here.
EDIT:
I would add a special class to those links though because the code above will execute on any link you have on the page which may give you unwanted issues.
Related
For a web based project, I am using jQuery. In one part of the code, there is data that gets dynamically added to the screen on the client side based on the activity of other users connected to the server. I want to write a code that will allow me to execute a function when a client clicks on the data.
To elaborate a little bit, there is a list which shows which members are online. When a new client connects, his name is added to the list and all other users can see on their screen that he is online. When another user clicks on his name, he sends a message request.
This is the relevant jQuery code:
$('#inc').append("<br><i onclick='accept()'>"+data.plr+"<i><br>")
And the accept function is defined under this block which is within another function, so like
function a(){
$('#inc')....
}
function accept(){
//...
}
However, when the code runs I get an error which says accept() is not defined
How do I solve this problem?
Maybe you can do it in that way...
$('#inc').append("<br><i>"+data.plr+"<i><br>")
$('#inc i:last-child').click(accept);
I did a small CodePen to let you see the code in action
https://codesandbox.io/embed/frosty-jang-fvk3j
I've always done it this way. I find this easier.
$('#inc').append("<br><i class="child">"+data.plr+"<i><br>")
$('.child').on("click",function(){
//your code here
});
You can do it with this way as well :
jQuery(function(){
click_link = $('<a class="" href="#">Click here</a>');
click_link .bind("click", function(){
alert('DO something');
});
$('.your_dom').append(click_link );
});
Write it using jQuery methods:
var $i = $('<i>').text(data.plr).click(function(event) {
//handle here onClick event
}); //or if you have the function already declared just write .click(accept);
$('#inc').append('<br />', $i, '<br />');
https://api.jquery.com/click/
So, a little context: I'm trying to do an ajax call to a webpage in the same domain to get a telephone number to show up as soon as I specify the client on the first page. I do get the data but it seems like not the whole page is loaded in.
I need this:
<div id="1">
<div id="2">
<a id="ineedthis"></a>
</div>
</div>
but instead it's giving me this:
<div id="1">
</div>
This is a website that I'm writing a script for, since I can't edit the source code. This is managed from our ERP program and is pretty limited in customizability.
My best guess is that the target webpage is also still loading in the information from the database, but my ajax call returns the webpage before that happens.
Here is my js code:
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
console.log(href);
if(href !== "https://52134.afasinsite.nlundefined"){
$.ajax({
url:href,
type:'GET',
success: function(data){
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
}
});
}
}
setInterval(updateClasses, 1000);
I'm running this once per second to check for a change in the input field on the first page, I don't know if there is a better way for this?
Firstly, you could try running the script/function once a change has been detected.
Something along the lines of :
$('input[name="{inputFieldName}"]').on('change',function(){
updateClasses();
});
//You can also use "keyup" instead of "change", depending on the type of action that you are looking for.
For the Ajax, you could try using Promises. Basically, set up the ajax call and then set a ".done" case for the ajax call has been completed and received some result. A ".fail" can also be used to catch non-code related issues.
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
var getPhonePromise = $.ajax({
url: href
});
getPhonePromise.done(function(data) {
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
});
getPhonePromise.fail(function(errRes) { console.log(errRes);});
}
I'm currently building a website for a school project that loads json data into the page dynamically as the user navigates. Here's the code I'm working with right now:
$(function () {
var $divs = $(".divs > div"),
N = $divs.length,
C = 0; // Current
$divs.hide().eq(C).show();
$("#next, #prev").click(function () {
$divs.stop().fadeOut().eq((this.id == 'next' ? ++C : --C) %N).fadeIn();
}); // close click function
}); // close main function
var content = jSONtexts.texts;
$(document).ready(function () {
$("#content0").html(content[0].content);
$("#content1").html(content[1].content);
$("#content2").html(content[2].content);
$("#content3").html(content[3].content);
$("#content4").html(content[4].content);
$("#content5").html(content[5].content);
$("#content6").html(content[6].content);
$("#content7").html(content[7].content);
$("#content8").html(content[8].content);
});
In my html I have divs set up as containers for the particular json data that I want to be presented. It's rudimentary right now, but the user clicks 'next' or 'previous' and a different section of the json loads into the visible div.
What I need is to be able to save what div is showing (maybe using the 'C' variable?) - into a cookie, and load that div when the user returns. I've tried using js.cookie.js, and it's quite possible that I'm using it wrong, Here's what I'm trying:
$( window ).unload(function() {
Cookies.set('pageState', 'C');
}); //close cookie function
But that doesn't seem to be working. It breaks my json loading when I try to put it anywhere in the .js file that would be relevant to the C variable.
I'm stumped. I've looked everywhere on google, and everything that people are saying to try breaks my json function. Help please!
If someone has any ideas I would be eternally grateful!
Thanks
Sam
Cookie is not a best practice to save these data, as cookies will be send with all requests.
Use need to use HTML5 localStorage to save data at client side.
http://www.w3schools.com/html/html5_webstorage.asp
Made demo for the same
document.getElementById("textInput").value = localStorage.getItem("pageState");
window.addEventListener("unload", function() {
localStorage.setItem("pageState", document.getElementById("textInput").value);
});
<input id="textInput" type="text" />
Demo : http://jsfiddle.net/kishoresahas/vvkdge2q/
as #KishoreSahas already suggested in the comments, I would suggest you to use localStorage instead of cookies.
You could store what you need like this
localStorage.setItem("veryimportantdata", "INeedThisLater");
and get it back later like this
var data = localStorage.getItem("veryimportantdata");
console.log(data); // prints out "INeedThisLater"
I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);
I need to pass a couple bits of info through the URL just by clicking a link, rather than by using action="GET" with a form and input button. Is this possible? This is client-side only, there is no server, so suggestions regarding PHP etc. will not be useful in this circumstance.
In your anchor, change the href to include a querystring at the end.
e.g.
<a href="http://www.example.com/test.html?parameter=2">
Assuming you have access to the variables on the client, you can do something like this:
<script type="text/javascript">
navigateToPage = function(val){
window.location.href = "/somefolder/somefile.htm?id=" + val;
}
</script>
<input type="button" value="Navigate" onclick="navigateToPage(5);" />
You're gonna need to use JavaScript to get all the values, and then combine them into a URL.
Here's an example (using the jQuery library):
Click
<script>
$(function(){
// The data, from the page
var id = 1, name = 'test';
// Add event to link
$('#paramLink').click(function(e){
e.preventDefault(); // Stop the browser from following the link
location.href = $(this).attr('href')+'?id='+id+'&name='+name; // Build the URL
});
});
</script>
put your bit of info in anchor and post along with it
click!
how to get these values on redirected page; and in case you using PHP.
$id=intval($_REQUEST['id']);
$action=$_REQUEST['action'];