jQuery onclick event not works - javascript

I have a lot of buttons with specific class like this:
All of these buttons has stored JSON in data attribute. I've created function, where I detect clicked button, and do some stuff with this JSON like this:
$(".btn-load-road").on("click", function () {
console.log($(this).data("route"));
});
Click event is not fired. Can you tell me what is wrong with this?

You can use:
prop
method to get the value of data-route (JSON value)
Here's a quick solution. Hope it helps!
$(".btn-load-road").on("click", function () {
console.log($(this).prop("data-route"));
});

I see a problem in the quotation of the "data-route" value. You are trying to double-quot a string that is already doublequotted...
Instead of
data-route=""coordinates":[[18.159425,49.835919],...],"type":"LineString"}"
You could try single-quot the quoted strings inside your main string
data-route="{'coordinates':[[18.159425,49.835919],...],'type':'linestring'}"
See this working Fiddle

Related

can't get value from onclick function javascript

I have a function where I am trying to get a value from an onclick event.
Here is the element attribute that gives the function to the element:
listcontainer.setAttribute('onmousedown',"knowbe4campaignspecific(this)")
Here is the function code:
function knowbe4campaignspecific(ele){
console.log(ele.value)}
However it will say undefined in the developer console.
If I just print the element by itself it will show the value inside so I must be missing something basic.
function knowbe4campaignspecific(ele){
console.log(ele)}
##RESULTS##
<ul value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>
Let me know if anything else is needed and I will update this post. Thanks!
As mentioned, value isn't a valid attribute of <ul>. You can still use it and access it through element.getAttribute but using datasets is more extendable and the correct implementation - you can access those through element.dataset
document.querySelector('.ms-List').setAttribute('onmousedown',"knowbe4campaignspecific(this)")
function knowbe4campaignspecific(ele){
console.log(ele.getAttribute('value'))
console.log(ele.dataset.value)
}
<ul value="183085" data-value="This is the better way" class="ms-List"><li> something</li></ul>
On elements that are not inputs you want to use the data attribute.
I believe this should work
<ul data-value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>
And then
function knowbe4campaignspecific(ele){
console.log(ele.dataset.value)}

passing values to a function does not work when inside for loop

I'm mapping currencies from a json file and i render the mapped currencies to a component. I have a .php file like this
<div class="currency-switch-container" id="currency_container">
<span style="font-size:12px;font-weight:bold">All currencies</span>
<div id="currency-map" style="margin-top:15px"></div>
</div>
I refer the div in the above component in my js file as follows
let currencyMap = jQuery("#currency-map");
And when my jQuery document is ready i'm doing the following
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`<span onclick="onCurrencyClick(${data[c].abbreviation})"
class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</span>`)
}
});
}
and my function is like this
function onCurrencyClick(val){
console.log("val",val);
setCookie("booking_currency", val, 14);
}
Here the function does not work. But if i do not pass anything to the function it seems to work as i can see the log in the terminal.
Hi your expression ${data[c].abbreviation} will put the value into function string without string quotes i.e. the resultant would be onCurrencyClick(abbreviation) while it should be onCurrencyClick('abbreviation').
please use onclick="onCurrencyClick('${data[c].abbreviation}')" instead.
Instead of using the inline onclick, use event delegation. This means that you have a single event listener that handles all the events from the children and grandchildren. The modification is a very minor one seeing the example here below.
A reason for doing this is that you keep your JavaScript inside your JS file. Like now, you encounter a JS error and have to look for it in your HTML. That can get very confusing. Also however inline onclick listeners are valid, they are outdated and should be avoided unless there is absolutely no other way. Compare it with using !important in CSS, same goes for that.
function onCurrencyClick(event){
var val = $(this).val();
setCookie("booking_currency", val, 14);
}
currencyMap.on('click', '.currency-item', onCurrencyClick);
This example takes the val that you try to insert from the value attribute from the clicked .current-item. <span> elements don't have such an attribute, but a <button> does and is a much more suitable element for it expects to be interacted with. It is generally a good practice to use clickable elements for purposes such as clicking.
In the example below you see the button being used and the abbreviation value being output in the value attribute of the <button> element and can be read from the onCurrencyClick function.
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`
<button value="${data[c].abbreviation}" class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</button>
`)
}
});
onclick will not work for a dynamically added div tag
Yo should follow jQuery on event
Refer: jQuery on
Stackoverflow Refer: Dynamic HTML Elements

How to pass value in a jQuery function without the help of onclick attribute?

I am facing a problem in which I need to pass either one or multiple parameter to a javascript function. For example
<a href="#" OnClick="Delete(1,'q');" > X </a>
<a href="#" OnClick="Delete(2,'u');" > X </a>
But I am trying to avoid this onclick attribute from the html end. So I have used this way
</span>Delete1
</span>Delete2
</span>Delete3
And written the jQuery function like this to capture my click function from the link
$("#actRemove").each(function() {
$(this).on("click", function () {
alert($(this).data("action"));
});
});
But alas!! I am undone. This link works only for the first anchor Delete1 none of the anchors are working. Here is my jsFiddle link. I have gone through these answers Q1, Q2, Q3, Q4, Q5, Q6. Each of those question have the solution in the first way using onclick and passed the parameter to the function.I am thinking differently. Moreover my another question is, is there any way to pass parameter to a jQuery function without writing onclick in the html attribute? I know that jQuery function is capable to receive the parameter, but how can I send it to the function from the html end?
Instead of id use class selector:-
HTML:-
</span>Delete1
</span>Delete2
</span>Delete3
jQuery:-
$(".actRemove").on("click", function () {
alert($(this).data("action"));
});
Working demo:-
$(".actRemove").on("click", function () {
alert($(this).data("action"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</span>Delete1
</span>Delete2
</span>Delete3
Note:-
id used as unique-selector in jQuery,while class used as a group-selector
You can use this way
</span>Delete1
</span>Delete2
</span>Delete3
$("a[id^='actRemove_']").on("click", function () {
alert($(this).data("action"));
})
You can get the value of an HTML object directly in javascript without passing it with onclick using:
var object_id = document.getElementById('object_id').value;

Passing parameter to javascript onclick without using HTML

I can't figure this out. I'm trying to create an onclick handler purely in Javascript.
What I plan to do here is inside this DIV, have a collection of items that I can click on. For now, these items will be numbers from 0 to 9 inclusive. When a number is clicked on, a system message consisting solely of that number should pop-up on the screen. I narrowed my problem down to just the onclick handler definition.
If I use this format:
item[n].onclick=function(n){
handler(n);
}
The handler will fire only when click a number which is correct, but the message that appears is something about mouse event.
If I use this format:
item[n].onclick=function(){
handler(n);
}
The handler will pass a value of -1 which in turn is printed as a message. I think it means "false".
How do I modify this:
item[n].onclick=function(){
handler(n);
}
so that 'n' being used as the handler parameter is the same as the number I click on the screen?
My code is the following:
<div ID="Itemset"></div>
function handler(n){
alert(n);
}
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
collections.appendChild(item[n]);
item[n].onclick=function(n){
handler(n);
}
}
What I'm effectively trying to do if you want to understand it HTML wise is this:
<div ID="Itemset">
<div onclick="handler(0);">0</div>
<div onclick="handler(1);">1</div>
<div onclick="handler(2);">2</div>
<div onclick="handler(3);">3</div>
<div onclick="handler(4);">4</div>
<div onclick="handler(5);">5</div>
<div onclick="handler(6);">6</div>
<div onclick="handler(7);">7</div>
<div onclick="handler(8);">8</div>
<div onclick="handler(9);">9</div>
</div>
Except that I don't want to write out onclick="handler(n);" a million times.
Any advice? and feel free to point to another resource that has the answer I need if there is one.
UPDATE
I'm looking for something compatible with older browsers as well. I'm going to have to not go for the bind function because according to mozilla docs, it works for IE 9+. I'm looking for something that works for IE 7+ as well as other browsers. I might have to go for event listeners if there is no other alternative.
You have a closure issue here (see JavaScript closure inside loops – simple practical example), a simple solution is to use bind to use the current value of n to be a parameter of the handler function
item[n].onclick=handler.bind(item[n],n);
U can use addEventListener and ID for find clicked element...
document.getElementById("Itemset").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
var value_data = parseInt(e.target.textContent);
if(e.target && value_data > -1) {
alert("Malai test:: "+value_data);
//handler(value_data);
}
});
https://jsfiddle.net/malai/tydfx0az/
I found my answer here: https://bytes.com/topic/javascript/answers/652914-how-pass-parameter-using-dom-onclick-function-event
Instead of:
item[n].onclick=function(n){
handler(n);
}
I have to do:
item[n].onclick=new Function('handler('+n+')');
Funny thing is, the word function needs to be capitalized when making a new instance. It's awkward I have to go this route but it works in IE 7+
One alternative is :
function handler(){
alert(this.id);
}
function myFunction() {
var item=[];
collections=document.getElementById('Itemset');
for(n=0;n<10;n++){
item[n]=document.createElement('DIV');
item[n].innerHTML=n;
item[n].setAttribute("id","itemset"+n);
collections.appendChild(item[n]);
item[n].onclick=handler;
}
}
Insert dynamic ids to the elements and when you click on any element retrieve its id using this.id and do whatever you want to do with that value.
That's all.
Hope this helps.

Put string in href="javascript" in append

I want to put a string into a href="javascript:" when i append a li but i doesn't work at all....
ajoutEnf("myString");
function ajoutEnf(enf){
$('#laliste').append('<li>Enfant</li>');
$('#enf').popup('close');
$('#laliste').listview('refresh');
}
That code will produce:
javascript:propEnfant(myString)
Thus clicking the link, the script will look for a variable named myString. You probably want to use '<li><a href="javascript:popEnfant(\''+enf+'\')" ...
Another thing to be aware of: if popEnfant is defined inside your DOMReady event listener (which I don't know if it is) it will not be globally accesible, which is a requirement for javascript:... to work.
Demo
You can bind the click event using jQuery.fn.on:
ajoutEnf("myString");
function ajoutEnf(enf){
$('<a herf="#" data-icon="edit" data-rel="popup">Enfant</a>').on('click', function(event) {
event.preventDefault(); // Stop the hash from changing to "" (page.html#)
popEnfant(enf);
}).wrap('<li/>').parent().appendTo('#laliste');
$('#enf').popup('close');
$('#laliste').listview('refresh');
}
This way you dont have to string whatever enf and make sure that objects/arrays are passed on correctly.
Do some little changes: add slashes with single quotes.
$('#laliste').append('<li>Enfant</li>');

Categories

Resources