Put string in href="javascript" in append - javascript

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>');

Related

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

Regex in javascript replace function

Am newbie to regex am trying to do some regex replace function in java script here is my content and code
jQuery("td[headers='name_head']").each(function (index, value) {
var text = jQuery(this).html();
if( text.indexOf('<a href=') >= 0){
jQuery(this).text(text.replace(/<a href=.*\"$/, ""));
}
});
Html content will be look like this
Calculate Points
i just want to remove only the value inside href ""
Please throw some light on this
Regards
Sathish
The text() method just retrieves the text contents which doesn't include any HTML tags. You can use html() method with a callback function where you can get the old HTML content as the second argument to the callback and based on the old value generate updated HTML.
The better way is to update the href attribute value of a tag to empty by directly selecting them, there is no need to loop over them since all values need to be empty.
jQuery("td[headers='name_head'] a").attr('href', '');
UPDATE 1 : In case you want to iterate and do some operation based on condition then do something like this.
jQuery("td[headers='name_head'] a").each(function(){
if(//your ondition){
$(this).attr('href', '');
}
});
or
jQuery("td[headers='name_head']").each(function(){
if(//your ondition){
$('a', this).attr('href', '');
}
});
UPDATE 2 : If you want to remove the entire attribute then use removeAttr('href') method which removes the entire attribute itself.
jQuery("td[headers='name_head'] a").removeAttr('href');
Why would you reinvent the wheel?
You don't need regex to achieve this, you can simply do it this way:
jQuery("td[headers='name_head'] a").attr('href', '');
It will set href to "" for all <a> elements inside td[headers='name_head'] so it will always respect your condition.
I haven't tested this code; but something like this should help, don't think you need to use regex for this;
$('a.DisableItemLink[href!=''][href]').each(function(){
var href = $(this).attr('href');
// do something with href
})
This piece of code selects all elements which have the class DisableItemLink with a location set and sets it to blank.
I am curious as to what you are trying to do in the larger scheme of things though, sounds like there might be better ways to go about it.
Reference: some good selector combinations for links

jQuery onclick event not works

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

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.

Proper Syntax to Pass Vars in a href JavaScript

Basic question so I feel dumb but..., Whats the proper syntax below in the href?
The href:
<html>
</html>
The Function:
function navClickListener(appendE, target, gotoURL) {
//doing stuff
};
When you really have to use inline JavaScript, use different quotes, eg ' or ".
Currently, the HTML attributes are marked by double quotes, as well as the JavaScript code.
Is effectively truncated to:
^ Because of this.
In this case, since you're using a JavaScript-URI, you can also use %22 instead of double quotes.
Demo: http://jsfiddle.net/pu3CM/
You'd be better off avoiding JavaScript in your "href" attributes.
<a href='#' onclick='navClickListener("navContent", "bodyContent", "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content"); return false;'>Click Me</a>
Using javascript:void(0); as the HREF value will prevent jumping or other undesired behavior from happening when the user clicks on the anchor. Use single quotes since you have double quotes in your JavaScript.
<a href="javascript:void(0);" onclick='javascript:navClickListener("navContent", "bodyContent" "http://192.168.1.34/wiki/index.php/Airworthiness_Directive #content");'></a>
Alternatively, you can do the entire thing in your JavaScript by binding a click handler. This would allow you to set a normal HREF value, which would be better for screen readers, and still allow the same functionality.
$(document).ready( function() {
$('.someclass').click( function(event) {
event.preventDefault();//Does the same thing as javascript:void(0); in the HREF value
var pageURL = $(this).attr('href');
navClickListener("navContent", "bodyContent", pageURL );
} );
} );

Categories

Resources