Concatenate variable and function name [duplicate] - javascript

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 3 years ago.
We want to concatenate the function name and variable name. This should occur on click of a <a> tag.
How can we concatenate the function and variable name?
Issue:
we are getting error message fn_dataId() is not defined
Desired output:
fn_dataId() should be fn_some123();
What we tried
$(function() {
$('.link').on('click', function() {
console.log('clicked');
var dataId = $(this).attr('data-id');
console.log('data id - ' + dataId);
// What we tried, but didn't work.
fn_dataId();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-id="some123" class="link">
Click here
</a>

You can concatenate strings, and use the result as a function using window["function_name"](args);:
function fn_some123() {
console.log('i have been called!');
}
$(function() {
$('.link').on('click', function() {
var dataId = $(this).attr('data-id');
window['fn_' + dataId]();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-id="some123" class="link">
Click here
</a>

I'm not sure the use case of this it sounds like the dataId might be better off as an argument to a more generic function, but you can possibly solve it using the following:
eval("fn_" + dataId + "()")
Be wary of eval though - executing anything you take as input from a user is a big security risk

Related

Pass var using onClick with function name of JS

I'm trying to pass 2 variable using onClick inside of <a> tag
Here's my code:
<a onClick="pbDiv(id=1);">Enter</a>
<script>
function pbDiv(id){
alert(id);
}
</script>
This works perfectly as it should be.
But the problem is I need to pass 2 variable
Example of variable
id=1
name=myname
inside of onClick
Is that even possible?
tried this one onClick="pbDiv(id=1,name=name);"
seems not working to me.
In javascript, you define the name as an argument, and never pass in the name of the argument as a parameter. TypeScript (a version of javascript) does this, however.
function pbDiv(id, name){
alert("id: " + id + ", name: " + name);
}
<a onclick="pbDiv(1, 'foo');" href="#">Enter</a>
Pass object instead
<a onClick="pbDiv(options={id:1, name: 'deepak'});">Enter</a>
<script>
function pbDiv(options) {
alert(options.id + options.name);
}
</script>

Get document title in Javascript (getElementsByTagName) returns undefined [duplicate]

This question already has answers here:
How to get the title of HTML page with JavaScript?
(4 answers)
Closed 3 years ago.
I´m trying to get the current html title of a page in Javascript. I'm using the getElementsByTagName("title") function but it just returns me undefined.
I´m looking to output the title and substring 23 chars.
I hope someone can help me.
code:
function printName(){
document.onLoad()
var strng = document.getElementsByTagName("title")[0];
var resfin = strng.substring(0, strng.length - 23);
document.write(resfin)
}
UPDATE: I tried this:
<button onclick="printName(-23)">Try it</button>
<br>
<script>
function printName(sub) {
var str = document.title.substring(0, document.title.length + sub);
document.write(str)
}
printName(-23);
</script>
and now its printing out nothing.
I'd simply use document.title
function pageTitle(sub){
return document.title.substring(0, document.title.length + sub)
}
console.log( pageTitle(-23) )
https://developer.mozilla.org/en-US/docs/Web/API/Document/title
You can use
document.title
I would advise you to review this:
https://developer.mozilla.org/en-US/docs/Web/API/Document/title

jQuery: how to read the name attribute? [duplicate]

This question already has an answer here:
Jquery get Name value of hidden field
(1 answer)
Closed 6 years ago.
I have little of an issue writing my script.
$(function(){
$(".wolny").click(function() {
var godzina = this.id;
var minuta = this.name;
alert(godzina + ":" + minuta);
});
Alert should give me output looking like so hour:minute. Instead of that I am getting this: hour:undefined. I really dont know what to do :x
Here's HTML code (php generated)
<div class="col-sm-3 kafelek wolny" name="15" id="9"></div>
Thank's for any help.
A div element doesn't technically have a name attribute. If you want to store a piece of data, store it as a data-* attribute. Something like this:
<div class="col-sm-3 kafelek wolny" data-name="15" id="9"></div>
Then retrieve it as such:
var minuta = $(this).data('name');
Try using .attr() function instead like so:
var minuta = $(this).attr('name');
This works because name in your case is a attribute and not a property. This will work with any random attribute like foo that you may add.
A better way is to add a data attribute like data-name="something" and read it with $(this).data(name).
Working Example:
$(function(){
$(".wolny").click(function() {
var godzina = this.id;
var minuta = $(this).attr('name');
alert(godzina + ":" + minuta);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3 kafelek wolny" name="15" id="9"> Click me! </div>
Try this instead:
$(function(){
$(".wolny").click(function() {
var godzina = $(this).attr('id');
var minuta = $(this).attr('name');
alert(godzina + ":" + minuta);
});
});
However, if possible, I would recommend using data attributes for your values. Here's an example:
<div class="col-sm-3 kafelek wolny" data-hour="9" data-minute="15"></div>
Then, in the JavaScript, you use "data-hour" and "data-minute" for the attributes instead of "id" and "name" like it is now.

Using document.getElementById() inside a function

I have this code:
<div id="com_22">
<a onclick="delete(22);">delete entry</a>
</div>
and the javascript code:
function delete(url){
var tupu = document.getElementById("#com_"+url+"");
alert(tupu);
}
the problem is I'm having a null alert
I want to get the id
document.getElementById("#com_22");
How I can solve it
update
this is my code:
function confirmDel(url){
$(document).ready(function(){
$.ajax({
type: 'POST',
url: '/files/assets/php/ajax/blog-stream.php?act=del',
data: 'url=' + url ,
success: function(h){
var status = h.status
if (status == "si" ) {
$("#com_"+url+"").fadeOut("slow");
}
}
});
});
}
the code excecutes so well except for the id didnt fade out
$("#com_"+url+"").fadeOut("slow"); <--- no working
See :: getElementById(), that should have been:
function delete_something(url){
var tupu = document.getElementById("com_"+url);
alert(tupu);
}
btw, try avoiding use of js pre-defined names as function name see:: delete
Don't include the hash when you're selecting by id. You're not using jQuery or querySelector.
var tupu = document.getElementById("com_"+url);
There is also no need to concatenate the empty string there at the end so I removed it.
Remove the '#' from within the bracket.
The function getElementById gets the element ID as a string, not a CSS-style selector. Change to:
var tupu = document.getElementById("com_"+url);
As can be extracted by javascript levels:
[{"file": ". m3u8" in this page: http: //ivm.antenaplay.ro/js/embed_aplay_fullshow.js? id = 6eI6sLVBfOL

Running a function by typing in URL - Javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Running a function by typing in URL
On my website I have several functions that when a hyperlink is clicked on example.php page, the main content changes accordingly. Now I want to direct people from a single URL to that example.php page with the function already called. Example - www.example.com/example.php?AC ( which will call a function named AC and the content changes before the page loads)
I had already asked the same question, but forgot to tag javascript and tagged php.
Thanks in advanced.
You can use JavaScript to get the querystring, and call the functions accordingly.
How to get querystring in JavaScript: JavaScript query string
What I would do is read the query string by using something like this to figure out if the key is there
function doesKeyExist(key) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
return qs != null;
}
Then
if(doesKeyExist(AC)) {
// run my code
}
You could do:
var query = document.location.search;
var func = window[query];
if (func && typeof(func) == "function")
func();
<script language="javascript">
var k = document.location.toString().split('?');
if(k.length > 1)
{
if(k[1] == "AC")
AC();
}
</script>
You can add a window.onload handler, check the query string of the page and act accordingly.
For example:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>
You run a JS funciton like this.
<script type="text/javascript">
function test()
{
alert('test');
}
</script>
Now if you type javascript:test() in the url it will execute test function.

Categories