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>
Related
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
I have a button thats value is set based on a mysql query in php like so:
echo "<td><button class='jsontable' onclick='Copythat(this.value)' value='" . $row['json'] . "'> " . $row['name'] . "</button></td>";
the text of the button is the name row, which works currently.
and a function that i have basically in place to try and grab the string and send it to the load function. the load function needs to receive only text of that mysql row json
function Copythat(el.val) {
var jsontoload = $(el.val).html();
load(jsontoload);
}
If you pass this to your function, you get the context of the element where the event occurred. Once you've got that, you can pass it to jQuery and you can get the "value" attribute using the .val() shortcut method.
Note that function Copythat(el.val) { needs to be something simply like function Copythat(val) { - function parameters must be standalone variables, they cannot be written like object properties.
function Copythat(input) {
var attrValue = $(input).val();
alert(attrValue);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
You could also convert the whole thing to jQuery and ditch the inline event handler:
$(function() {
$(".jsontable").click(function(event) {
var attrValue = $(this).val();
alert(attrValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' value='Something'>A button</button>
Or it should also be noted that for something as simple as this you don't really need jQuery at all:
function Copythat(input) {
alert(input.value);
}
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
Another further simplification if you literally only need the value to go into your function:
function Copythat(input) {
alert(input);
}
<button class='jsontable' onclick='Copythat(this.value)' value='Something'>A button</button>
I have used a function to capture the Query String value of "name" - i.e. imagine a party invite site;
https://cometomyparty.com?name=phil
The function used is;
<script type="text/javascript">
function getQuerystring(){
var q=document.location.toString();
q=q.split("?");
q=q[1].split("&");
var str=""
for(i=0;i<q.length;i++){
tmp=q[i].split("=")
str+=" "+tmp[1]+"<br />"
}
document.getElementById("name").innerHTML=str
}
onload=function(){
getQuerystring()
}
</script>
Then I can call the value of 'name' using id="name" where I want to use this on my page, i.e. in the heading, I could say, Phil, looking forward to having you at the party...
How can I dynamically append my 'name' value (var str) within a html link placement i.e.
Link Text
Which would return, in the example above;
http://example.com?name=phil
You can access the href attribute of the <a> tag directly or by using .setAttribute:
// Using .href:
document.getElementById("name").href=str;
// Using . setAttribute:
document.getElementById("name").setAttribute ("href", str);
Be aware that you should have that <br/> tag in the src of the link.
Try this:
<a href="#" onclick='goToPage(event)'>Link Text</a>
<script>
function goToPage(event) {
event.preventDefault();
window.location='http://example.com?name='+str;
}
</script>
Ideally you would want to use jquery where you could use:
$('#link').click(function(event) {
event.preventDefault();
var link = $(this).attr('src');
window.location=link+str
});
You would of course want to remove "str" from the href
I want to pass a field of a domain object to a javascript function in my view.gsp (grails) , but I am getting a syntax error.
Here is my gsp and javascript - please let me know if you see the syntax error. Thanks!
/*HTML*/
<td>${fieldValue(bean: studentInstance, field: "active")}</td>
/*JS*/
<script type="text/javascript">
var id = 0;
function setID(userId){
console.log("userId: " + userId);
id = userId;
}
</script>
The issue is you have function in your onclick. You don't need it there. Remove it so your onclick looks like this:
onclick="setID( ${studentInstance.id})"
In my form, I want to offer the ability to add another location. It was working when I had only one text box appear,(address) and could get multiple address text boxes to appear. but now I am trying to add the "city" text-box and it is not working. I used one function before, now I split up my functions to reuse code better. So now my id's (id_) should be id_1,id_2,ect. but I am getting the object instead. I think the addLoc() should be on its own, vs function city() inside function addLoc(), but that wasnt working either.
HTML
<div class="one">
<button onclick="addLoc()">Add Location</button>
</div>
<div class="three">
<h2>Locations</h2>
<form action="#" id="mainform" method="get" name="mainform">
<div id="myForm"></div>
<input type="submit" value="Submit">
</form>
</div>
javaScript
var i = 0;
function increment(){
i += 1;
}
function addLoc(){
var d = document.createElement("DIV");
var l = document.createElement("LABEL");
var i = document.createElement("INPUT");
address();
city();
function address() {
i.setAttribute("type","text");
i.setAttribute("placeholder","Address");
build();
}
function build() {
var g = document.createElement("IMG");
g.setAttribute("src", "delete.png");
increment();
i.setAttribute("Name","textelement_" + i);
d.appendChild(l);
l.setAttribute("for","textelement_" + i);
g.setAttribute("onclick", "removeElement('myForm','id_" + i + "')");
d.appendChild(g);
d.setAttribute("id","id_" + i);
document.getElementById("myForm").appendChild(d);
}
function city() {
i.setAttribute("type","text");
i.setAttribute("placeholder","City");
build();
}
}//end of addLoc()
Here is the jsFiddle (some changes)
was working fine with just the address text box. I broke something trying to split up the functions. I can do it all as one BIG function, but prefer not to.
Any help Much appreciated!
var i = document.createElement("INPUT"); d.setAttribute("id","id_" + i); This is why your id is what it is. To fix it, use a different variable name for your input element.
Looks like you redeclare the variable "i" in your function addLoc() as an input element. Therefore it's not using the "i" you declared at the top of your code outside the function scope (var i = 0;) on line 0. So it's actually trying to append the object to the string which turns out as you see it in your html.
Try not to overload variable names, especially when declaring them outside function scope. If you're going to use global variables, preface them with a marker like g_variableName so they don't get mixed up with function scope variables.
Also, try to use meaningful names for your function variables instead of d,l,i. I would change your input variable them to something like "divElement", "labelElement", "inputElement".
Changing the variable name of 'i' that you declare in the function addLoc() and carrying it through that function should help!