Send variables to javascript(jquery) function - javascript

I wont to be able to send a variable to a JavaScript function when I click on a link but for some reason I cant find anywhere on how to do it on the internet.
Here is the function at the top of my page:
<script>
$(document).ready(function(){
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h= &v= ");
});
});
</script>
As you can see I need the variable to be placed after the "h=" and "v=" parts.
Here is the link to activate the function in my page:
<img src="images/map/invisible.png" border="0" />

Variables from where? It's easy enough:
var h = 20;
var v = 40;
$(function() {
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
});
});
Just make sure you escape them with encodeURIComponent().
You can of course get them from anywhere like:
<input type="text" id="txth">
<input type="text" id="txth">
and then:
var h = $("#txth").val();
var v = $("#txtv").val();
Edit: Ok, from your comments I gather you want to send the information from the server back to the client so the client can send it back. The first is to do your click handler in a non-jquery kind of way:
Click me
with:
function handle_click(h, v) {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
}
That's probably the easiest solution. If you want to stick with jquery click handlers you can always embed this information in an attribute or a hidden element. For example:
<div class="special-h">12</div><div class="special-v">34</div>Click me
with CSS:
a.special div { display: none; }
and:
$(function() {
$("a.special").click(function() {
var h = $(this).children("special-h").text();
var v = $(this).children("special-v").text();
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" +
encodeURIComponent(h) + "&v=" + enocdeURICompoennt(v));
});
});
There are many variations on this theme.
Lastly, I'll point out that I would advise you not to do attribute lookup selectors where you can possibly avoid it. Give the anchor a class and/or ID and use one of those to assign the event handler. Also use a selector like "a.special" over ".special" too (for performance reasons).

Do you mean appending them into the URL string?
<script>
$(document).ready(function(){
$('[name=updateInterface]').click(function() {
$("#interfaceScreen").load("modules/interface/interfaceScreen.php?h=" + h + "&v=" + v);
});
});
</script>
This assumes you have the variables h and v defined elsewhere in your script.

Related

Passing json object in href function - JavaScript

I need to pass a json object to function, which is as mentioned below in a href, but this JS code is not getting evaluated. So can anyone suggest a workaroud or a solution for this?
function function_test(option,jsonObj){
displayMessage(str);
}
function function_prepare_div(){
var str ="";
var jsonResposneObj = getJson();//function to get jsonResponseObj
for(i=0;i<jsonResponseObj.length;i++){
str += "<a href='function_test( " + i + "," + jsonResposneObj.dataObj[i] +")'>1. " + jsonResposneObj.dataObj[i].objName + "</a></br>";
}
return str;
}
P.S. I cannot return the jsonResponse after function call.
Instead of using inlined JS, append the element using proper DOM methods, and then attach an event listener.
Eg something like
const a = container.appendChild(document.createElement('a'));
a.href = function_test(1, jsonResponse);
a.textContent = '1. ' + function_test(1, jsonResponse);
(make sure function_test returns a URL)
Functions (or any JavaScript for that matter) don't belong in an <a href=""> in the first place.
Hyperlinks are for navigation, not JavaScript hooks. Using them just to trigger some JavaScript is an incorrect use of the <a> tag. It was commonplace 20+ years ago (before we had web standards), but is woefully outdated and downright incorrect today. Using a hyperlink to trigger JavaScript is semantically incorrect and can cause issues for people who rely on assistive technologies (like screen readers) to navigate a page.
Just about any element that is valid in the body of a web page supports a click event and most are better suited to what you want to do.
What you need to do is register your function as the callback to the click event of some element, like this:
// An example of a JSON response
var jsonResponse = '{"key1":10,"key2":true,"key3":"foo"}';
// Get reference to any element that supports a click event that
// can be safely used as a JavaScript trigger
var span = document.getElementById("fakeLink");
// Set up an event handling callback function for the click event of the element
span.addEventListener("click", function(){
// Call the function and pass it any arguments needed
processJSON(1, jsonResponse, this);
});
// Do whatever you need to do in this function:
function processJSON(val, json, el){
console.log(val, json);
el.textContent = val + json;
}
/* Make element look & feel like a hyperlink */
#fakeLink { cursor:pointer; text-decoration:underline; }
#fakeLink:active { color:red; }
<span id="fakeLink">Click Me</span>
var json = {
foo: 'bar'
};
var func = function(data) {
alert(data.foo);
}
$('body').append("<button onclick='func(" + JSON.stringify(json) + ")'>BUTTON</button>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Call to window.print firing before documents style is applied

I have a form with a print function. Inside the function I open a window, build the document, add the head with style sheets, add the form HTML and make the call to print the last part of the body. The problem is the initial print preview/print doesn't reflect the style. If I cancel the print and attempt to print manually, the style shows up.
I've tried quite a few ways of doing this with no luck. It seems like a timing issue. Any ideas?
Browser is Chrome. Below is the JS function. (This is injected with a faces context).
function printForm(windowTitle, path){
var printWindow = window.open();
var printDocument = printWindow.document;
var headHtml = "<link href='" + path + "/css/style.css' rel='stylesheet' type='text/css'/>";
printDocument.getElementsByTagName('head')[0].innerHTML = headHtml;
var printDiv = printDocument.createElement("DIV");
var formDiv = document.getElementById("formDiv");
printDiv.innerHTML = formDiv.innerHTML // Styling here is the issue
printDocument.body.appendChild(printDiv);
var scriptTag = printDocument.createElement("script");
var script = printDocument.createTextNode("print();");
scriptTag.appendChild(script);
printDocument.body.appendChild(scriptTag);
}
I think you need a setTimeout to delay printing for a second or two so the style can be applied. You'll need to tinker to find the right length.
Instead of trying to guessing with a timer, it might be more precise to use the load event on the <link ...> to know exactly when it has completed loading.
Below is a function I use which illustrates this technique. It uses an off-screen <iframe> to print a portion of a page. It's jQuery based, but the principles are the same in vanilla JS. Note the setting of the <link>'s onload function with an anonymous function which invokes print() on the <iframe>'s window object.
/*
* expects:
* <tag id="whatever">...goop...</tag>
* <input type="button" class="printit" data-target="whatever" value="Print">
*/
$(function() {
$( '.printit' ).click(function() {
var goop = $( '#' + this.dataset.target ).prop('outerHTML');
var ifr = $('<iframe>');
var bas = $('<base href="' + document.baseURI + '">');
var lnk = $('<link rel="stylesheet" href="/css/print.css">');
lnk.on('load', function() { /* CSS is ready! */
ifr[0].contentWindow.print();
});
ifr.css( { position: 'absolute', top: '-10000px' } )
.appendTo('body')
.contents().find('body').append(goop);
ifr.contents().find('head').append(bas).append(lnk);
return false;
});
});

Onclick URL extender

My problem resides within the syntax of the onclick funtion.
My URL for the page I'm working on(Simplified for obvious reasons):
www.mytestsite.com/tier-1/tier-2.html
My code right now:
<div onclick="location.href='tier-3.html';">
When clicked, it attempts to bring me to a page with a URL of:
www.mytestsite.com/tier-1/tier-3.html
I'd like it to extend the current URL dynamically so it'll bring me to:
www.mytestsite.com/tier-1/tier-2/tier-3.html
Does anyone know if this is possible to do within the onclick function? This is going to be dynamic, so I'm reluctant to do the simple fix of:
<div onclick="location.href='tier-2/tier-3.html';">
I really appreciate any help anyone offers me!
You should not use inline javascript, it's hard to debug to debug and keep things scoped. Just create an event listeners for each div.
You can set a topdir variable, that you change to suit your needs.
//pure javascript way:
var topdir = "tear2/";
document.getElementById('mydiv').addEventListener("click", function(){
window.location = topdir + "tier-3.html";
});
document.getElementById('mydiv2').addEventListener("click", function(){
window.location = topdir + "someotherurl.html";
});
//jquery way:
var topdir = "tear2/";
$('#mydiv').on('click', function(){
window.location = topdir + "tier-3.html";
})
$('#mydiv2').on('click', function(){
window.location = topdir + "someotherurl.html";
})
Try this:
document.getElementById("yourdiv").setAttribute("onclick", "location.href='tier-2/tier-3.html';");
EDIT
Use global js variables if you wanna increase your "tier" value and extend your url.
Your html:
<div onclick="url_update();"></div>
Then create your global var and your function:
var global_url = "tier-1";
var global_count = 1;
function url_update(){
global_count++; // increase "tier" value
global_url = global_url + "/tier-" + global_count;
// your new global_url will be = "tier-1/tier-2";
location.href = global_url + ".html";
}
I hope it was what you were looking for!

Class of ID Change based on URL - URL Based Image Swap -

What I'm trying to achieve:
Based on URL (ie., foo.com/item1), the div element "logoswap" receives a different class.
The following is the code I put together but it seems completely wrong. I'm not a JS pro by any means, XHTML/CSS is more my speed (some PHP)... I cannot use PHP, even if it is possible in PHP (and I know it is because I have a PHP version of what I need done already, but I can't call the PHP properly.
I'm really just trying to get a different logo to show up based on the directory/url... It doesn't have to be a background element called in by the CSS class necessarily, I just need a different image to load based on the aforementioned url variable...
$(function() {
var url = location.pathname;
if(url.indexOf('item1') > -1) {
document.getElementById("logoswap").className += " class1";
}
elseif(url.indexOf('item2') > -1) {
document.getElementById("logoswap").className += "class2";
}
elseif(url.indexOf('item3') > -1) {
document.getElementById("logoswap").className += "class3";
}
elseif(url.indexOf('item4') > -1) {
document.getElementById("logoswap").className += "class4";
}
elseif(url.indexOf('item5') > -1) {
document.getElementById("logoswap").className += "class5";
}
else {
document.getElementById("logoswap").className += "class1";
}
});
That's what I have... Ugly I'm sure.
That's why I'm here though, I definitely need some help.
Assigning CSS Class By URL Pathname
A jsfiddle has been setup for
this solution.
Here is a case for using numeric expressions if they are available. This does not apply to the above question.
$(function() {
var rgx = /item(\d+)$/,
url = location.pathname,
id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
$("#logoswap").addClass("class" + id);
});
UPDATE:
In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.
$(function(){
// my favorite way to make string arrays.
var matches = "brand1 brand2 brand3".split(" "),
url = location.pathname.match(/\w+$/)[0], // get the last item
id = matches.indexOf(url),
className = matches[(id > -1) ? id : 0];
$("#logoswap").addClass(className);
});
To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.
CSS Setup
#logoswap {
height : 200px;
width : 200px;
}
.class1 {
background-image : url(/path/to/default.jpg);
}
.class2 {
background-image : url(/path/to/second.jpg);
}
.brand1 {
background-image : url(/path/to/brand/1/logo.jpg);
}
...
Without jQuery
if you do not have jQuery in your code you may need to use window.onload.
(function(){
var old = window.onload;
window.onload = function(){
old();
var r = /item(\d+)$/,
url = location.pathname,
id = (r.test(url)) ? url.match(r)[1] : '1';
document.getElementById('logoswap').className += "class" + id;
};
})()
I just want to take a moment here to
encourage anyone who is doing this
type of code to get used to Regular
Expressions and learn them. They are
far and away the most frequently used
cross language part of my development
arsenal.
There's nothing that wrong with what you have. You could tidy it up with something like below.
$(function() {
var url = location.pathname;
var logo = document.getElementById("logoswap");
var i = 6;
logo.className = "class1";
while(i--)
{
if(url.indexOf("item" + i) > -1) {
logo.className = "class" + i;
}
}
});
Hope this helps.
Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:
<body id="item1">
Then in your CSS, create a selector:
#item1 #logoswap {
// class1 CSS
}

How can I change the href of an anchor after it has been clicked?

I have a page that pulls in data via AJAX. As well as this I have a link to download said data as a CSV file.
The problem I have is that upon I need to pass some parameters along with the click event so that the server can return the correct CSV file.
Without any processing the link looks like this:
Download Target Reports
This then fires off an ASP.NET MVC Controller action that returns the CSV. What I want to do though is pass two parameters along in the query string. Initially I thought that I could intercept the click event and add data to the query string like so:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
It would seem that changing the href at this stage will not update the link in time and the URL will be as it was when it hits the server?
Is it possible to change a URL after it has been clicked or do I need to look at another method?
Thanks
You could redirect the window yourself, like this:
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
window.location.href = this.href + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
return false; //prevent default going-to-href behavior
Or, whatever is updating those hidden fields, update the link then instead of when it's clicked, for example:
$("#someField").change(function() {
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
$("a.black").attr("href", function() {
return "/manager/TargetResults.csv" + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
});
});
The main difference is this still allows normal click behavior to work, ctrl+click, etc.
Just rounding out your options, you could put a span inside the link:
<span>Download Target Reports</span>
...and then hook the click event on the span, which will happen before the click on the link.
you can make javascript redirect here:-
var holder = $('.hidden-information').first();
var newOutlets = $('input[name="newoutlets"]', holder).val();
var queryDate = $('input[name="enddate"]', holder).val();
var anchor = $(this);
var link = anchor.attr('href');
link = link + "?endDate=" + queryDate + "&newOutlets=" + newOutlets;
anchor.attr('href', link);
location.href=link;
ya someone can disable js but your code is completely based on js.
Thanks
Without having a href, the click will reload the current page, so you need something like this:
jhhghj
Or prevent the scroll like this:
jhhghj
Or return false in your f1 function and:
jhhghj
....or, the unobtrusive way:
jhg
jhhghj
<script type="text/javascript">
document.getElementById("myLink").onclick = function() {
document.getElementById("abc").href="xyz.php"; `enter code here`
return false;
};
</script>

Categories

Resources