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>
Related
When the user clicks on <a> tag it calls a function like the following:
<a href="#" onclick="func1(this)">;
This function generates HTML for a modal that needs to reference the first button.
func1(elem) {
html='<div class="modaldiv">' +
'<a href="#" onclick="func2(e.srcElement)">'+
'</div>';
}
When the link inside the modal is clicked, func2() should save text into a data attribute inside the first link, but this is not working, returning:
"Uncaught SyntaxError: Unexpected identifier "
First, don't use inline HTML event handling attributes (onclick, onmouseover, etc.), here's why.
But, your actual problem is that you are not properly declaring your function.
This: func1(elem)
Needs to be this: function func1(elem)
Next, you <a> elements must have some content for someone to see and click on and they must then be closed, which you didn't have.
function func1(elem) {
html='<div class="modaldiv">' + 'click me too'+ '</div>';
document.body.innerHTML += html;
}
click me
If you rework your answer to use modern standards, the proper modern way to do this would be:
// Get references to DOM elements
var a1 = document.getElementById("firstAnchor");
a1.addEventListener("click", func1);
// Callback for first link:
function func1(e) {
// Store original source element
var src = e.srcElement;
// Formally create new elements and configure them
var d = document.createElement("div");
d.classList.add("modaldiv");
var a = document.createElement("a");
a.href = "#";
a.textContent = "Click me too!";
// By hooking up to a wrapper function, we can have that function
// pass arguments to the actual callback function:
a.addEventListener("click", function(){
func2(src);
});
// Add new elements to the document
d.appendChild(a);
document.body.appendChild(d);
}
function func2(firstSrc){
console.log("func2 invoked and e.srcElement from first link is: ", firstSrc);
}
click me
I'm trying to make two upload buttons. One is for an account logo.
.col-sm-6
.wrapper
Account Logo
#account_logo
= image_tag #account.logo.url, :class => 'account_logo'
= file_field_tag 'account[logo]', :accept => 'image/png,image/jpeg'
%a.btn.btn-default{:href => '#'} Choose file
%span.notice
Only PNG or JPG please.
The other is for an email logo.
.col-sm-6
.wrapper
Email Logo
#email_logo
= image_tag #account.email_logo.url, :class => 'email_logo'
= file_field_tag 'account[email_logo]', :accept => 'image/png,image/jpeg'
%a.btn.btn-default{:href => '#'} Choose file
%span.notice
Only PNG or JPG please.
I've added javascript so it works for both. However, there is something very wrong going on. I've added alerts to try and debug and they tell me that it's all going into #email_logo even when I click on the #account_logo button. Can some javascript wizard please help me?
:javascript
var logo = ["#account_logo", "#email_logo"];
for (var i = 0; i < logo.length; i++) {
var on_change = (logo[i] + ' input[type=file]');
var on_click = (logo[i] + ' a.btn');
var logo_img = (logo[i] + ' img');
$(document).on('click', on_click , function() {
alert("it is now " + on_click);
$(on_change).click();
alert("it is now " + on_change);
});
$(document).on('change', on_change, function() {
alert("it is now " + on_change);
var filelist = $(this).get(0).files;
var reader = new FileReader();
reader.onload = function (e) {
var url = e.target.result;
alert("it is now " + logo_img);
$(logo_img).attr('src', url);
}
reader.readAsDataURL(filelist[0]);
});
}
It might be because you are using a for(var i = ...) {} loop construct instead of logo.forEach(function(element) { ... }).
The reason this might be happening is because JavaScript does not have block scoping but function scoping, which means your loop variable i is available in the entire function, and your .on('change', ...) handlers will refer to this i as a variable, not as whatever value that variable had when you registered the handler.
Try using a logo.forEach(function(element) { ... } construct, and instead of setting var on_change = (logo[i] + 'input[type=file]');, do var on_change = (element + 'input[type=file]');.
Edit:
Ah ha, #Frost found the problem - variable scope. I would have used an iterator myself, and missed here the effect scope would have on event binding.
Given you're already using jQuery, and are probably after much better browser compatibility than forEach provides, I would highly recommend using the jQuery.each function. You may as well also inline the logos array, and pass the click event directly too, giving:
$(["#account_logo", "#email_logo"]).each(function(logo) {
$(logo + " input[type=file]").on("click", $(logo + " a.btn").click);
// etc.
});
Original response:
This seems like a lot of code for not much problem description. Are you saying that the event handlers are both applied to #email_logo, or that both buttons do the action desired of #email_logo? I haven't done file upload before, but from a quick review, the logic looks fine.
It would be easier to see the issue if you used console.log rather than alert, and pasted the results here, along with a description of how the log was produced.
I would prefer to comment this, but I don't have enough reputation.
I am sorry for this very basic question. I am very new to javascript and learning it.
I am stuck with one easy problem-
This is what i am trying to do-
I have a header that has some innertext
<h1 id="bd" onmouseover="fun1()" onmouseout="fun2()"> sample</h1>
I am chaging innerHTML of this header on mouseover like this-
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
well on mouseout i do the same but for getting original innerHTML for this header tag.
function fun2()
{
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
}
But onmouseout function shows me changed innerHTML, that is a in this case.
How do i get original innerHTML sample again onmouseout?
I want this to be done in javascript.
I tried another way more
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
function fun3()
{
var ds=document.getElementById("bd").innerHTML;
alert(ds);
}
function fun2()
{
document.getElementById("bd").innerHTML=fun3();
}
but it is not working also.
A very generic version would be the following:
First change your markup a bit:
<h1 id="bd" onmouseover="fun1(this)" onmouseout="fun2(this)"> sample</h1>
This way you don't need to look up your element again in your callback function. This works then for more than one element you mouse over. Then you go:
function fun1(elm) {
if (!fun1.cache) fun1.cache = {}; // extend your function with a cache
fun1.cache[elm.id] = elm.innerHTML; // write into cache -> fun1.cache.bd
elm.innerHTML = 'a';
}
function fun2(elm) {
if (fun1.cache && fun1.cache[elm.id]) { // see if cache exists and...
elm.innerHTML = fun1.cache[elm.id]; // read from it
}
}
This way you build a caching system that doesn't need an extra global variable but stays closer to your function.
The next step would be to use only one function and send the new value as a parameter. Create something like a toggle function:
<h1 id="bd" onmouseover="fun(this, 'a')" onmouseout="fun(this)"> sample</h1>
and then your function:
function fun(elm, newValue) {
if (!fun.cache) fun.cache = {};
var value = newValue || fun.cache[elm.id]; // no newValue means recover old value
fun.cache[elm.id] = elm.innerHTML; // alway save the old value
elm.innerHTML = value;
}
If you need more explanations about this and creating Objects just leave a comment to this answer and I'll come back with more details...
Good luck!!
Store the first innerHtml in a global variable ,and use this variable to backup the first innerHtml.
var oldInner = '';
function fun1()
{
oldInner = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=oldInner;
}
You'll need to store the original value somehow:
var originalInnerHTML = "";
function fun1()
{
originalInnerHTML = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=originalInnerHTML
}
Currently you just get the existing innerHTML and set it as the new innerHTML - it's always going to be the same. So this line never changes anything:
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
once you have changed the innerhtml of an element, old data is gone
In order to get the old data you first need to have it store in some other place.
For ex : on mouseover you can first copy the original html to a hidden div, and upon mouseout you can again copy from the hidden div to the main div.
hope this helps.
A very easy implementation will be to have the two text you want to display in the div. so you have:
<h1 id="bd">
<span id='sample1'>sample1</span>
<span id='sample2' style='display: none'>a</span>
</h1>
var el = document.getElementById("bd");
el.onmouseover = function() {
document.getElementById("sample1").setAttribute("style", "display: none");
document.getElementById("sample2").setAttribute("style", "");
}
el.onmouseout = function() {
document.getElementById("sample2").setAttribute("style", "display: none");
document.getElementById("sample1").setAttribute("style", "");
}
Hilariously, I'm having incredible difficulty finding any half-good way to determine whether or not an HTML element is inside another one or not -- which seems like it should be a basic core feature of traversing and analyzing the HTML DOM. I was immensely surprised and disappointed that the "hasDescendant" (or likewise) method is missing.
I'm trying to do this:
var frog = $('#frog');
var walrus = $('#walrus');
if (frog.hasDescendant(walrus)) console.log("Frog is within walrus.");
else console.log("Frog is outside walrus.");
I've tried to reproduce what I'm looking for with many jQuery combinations.
walrus.is(frog.parents());
walrus.has(frog);
walrus.find(' *').has(frog);
frog.is(walrus.find(' *'));
I haven't found a working solution yet.
[edit]
Solution: walrus.has(frog)
Alternate: if (walrus.has(frog)) { doStuff(); }
Alternate: var booleanResult = walrus.has(frog).length>0;
//Chase.
jQuery has just the function for this: jQuery.contains: "Check to see if a DOM element is within another DOM element."
Demo (live copy):
HTML:
<p id="frog">Frog <span id="walrus">walrus</span></p>
JavaScript:
jQuery(function($) {
var frog = $("#frog"),
walrus = $("#walrus");
display("frog contains walrus? " + $.contains(frog[0], walrus[0]));
display("walrus contains frog? " + $.contains(walrus[0], frog[0]));
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Use
if (walrus.has(frog).length) {
// frog is contained in walrus..
}
Demo at http://jsfiddle.net/gaby/pZfLm/
An alternative
if ( $('#frog').closest('#walrus').length ){
// frog is contained in walrus..
}
demo at http://jsfiddle.net/gaby/pZfLm/1/
If you wanted to write your own function you could do it without jQuery, perhaps something like this:
function isAncestor(ancestor, descendent) {
while ((descendent = descendent.parentNode) != null)
if (descendent == ancestor)
return true;
return false;
}
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.