I am working on jquery with php,Right now i have button inside loop and i want to pass "data attribute" and want to get value,Right now i am getting "undefined",So how can i do this ?
Here is my current code
echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap();'><img src='assets/viewmap.png'></a>"."</td>";
<script>
function viewmap()
{
var ids = $(this).attr('data-id');
alert('id is ' + ids);
}
</script>
change your onclick to this
onclick='viewmap(this)'
and get data with jquery like this
function viewmap(elm){
var id = $(elm).data('id');
alert('id is ' + id);
}
Pass this in onclick function and get in viewmap function and access
You can try below code ..
PHP
<?php
echo "<td>"."<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'><img src='assets/viewmap.png'></a>"."</td>";
?>
Script
<script>
function viewmap(m)
{
var ids = m.attr('data-id');
alert('id is ' + ids);
}
</script>
The problem is that you are using this inside your function viewmap but you are not sending it as a parameter from the HTML code, Change your onclick by: onclick='viewmap(this); than change the js function like bellow:
function viewmap(e)
{
var ids = $(e).attr('data-id');
alert('id is ' + ids);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='map-pop' data-id='1254' data-toggle='modal' data-target='#mapModal' onclick='viewmap(this);'>
click here
</a>
Remove onclick attribute and change the viemap() function like this
$(".map-pop").click(function(e) {
e.preventDefault();
let ids = $(this).data('id');
alert(`id is ${ids}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class='map-pop' data-id='".$employee_time['id']."' data-toggle='modal' data-target='#mapModal'><img src='assets/viewmap.png'></a>
`
I am trying to pass an object, totalArray into an input element, id=fullReport so that I will be able to use the variable totalArray within a function: printFullReport.
The input element is concatenated in a string so that it can be eventually created into a table.
I am unable to pass totalArrays into onclick="printFullReport('+ totalArray+ ')"> possibly due the string concatenation, in my console I recieve:
"Uncaught SyntaxError: Unexpected identifier" which implies a missing ; or '
but it appears to fine to me.
So this is my initial attempt:
<script type="text/javascript">
console.log(totalArray); //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
var str = "";
str += '<td>
<input id ="fullReport"
class="button"
type="button"
value="Full Report"
onclick="printFullReport('+ totalArray+ ')">
TOTAL (GBP):</td>';
</script>
this is my second attempt after reading and following the top answer:
Inline onclick JavaScript variable
<script type="text/javascript">
var str = "";
console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
function init(){
document.getElementById('fullReport').onclick=function(){
printFullReport(totalArray);
};
}
window.onload=init;
str += '<td><input id ="fullReport" class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>
but now this is returning: Uncaught ReferenceError: init is not defined.
I am possibly not understanding scope when having html elements in javascript strings.
For second attempt, you are missing the closing double-quote "
<script type="text/javascript">
And you need to assign the onclick from where the totalArray is accessible. (now that you clarified in comments that totalArray is not globally scoped.)
Demo
<script type="text/javascript">
var str = "";
totalArray ={ "1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
//console.log(totalArray) //{"1":0,"2":0,"3":54700.33,"4":54700.33,"5":0,"6":0,"7":-54700.33,"8":0,"9":0,"10":0};
function init(){
document.getElementById('fullReport').onclick=function(){
printFullReport(totalArray);
};
}
window.onload=init;
str += '<td><input id ="fullReport" class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):</td>';
</script>
<input id ="fullReport" class="button" type="button" value="Full Report" onclick="init();">TOTAL (GBP):
There's plenty of questions on how to get the value onKeyUp, but I want to pass the id of the form onKeyUp as well.. I tried something like this, but it's telling me getId is not defined.
function getId(x){
$('.not').append(x);
}
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"' onkeyup='getId("+word+")'></form> ");
http://jsfiddle.net/evs3A/
Also is putting something like "+variable+" bad practice, because I'm using it quite a lot ;)? Thank u.
Use jQuery to hook up the event and avoid the problem altogether. Try this:
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='" + word + "'
name='" + word + "'></form> ");
$('.questions input').on('keyup', function(e) {
$('.not').append(this.id);
});
Example fiddle
you can change it into this:
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"'></form> ");
and in jquery:
$(document).ready(function(){
var word = 'HELP';
$(document).on('keyup', '#' + word, function(){
$('.not').append(word); //or $(this).attr('id'); if the id is the argument that you want to pass
});
});
if you want to change a variable to pass you can use data value like this:
<input type='text' id='"+word+"' name='"+word+"' data-something="new_value">
and take it in this mode:
$(document).on('keyup', '#' + word, function(){
$('.not').append(word);
var value = $(this).data('something');
});
Here's a sample without any jQuery.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('myFormId').addEventListener('keyup', onFormKeyUp, false);
byId('myFormId2').addEventListener('keyup', onFormKeyUp, false);
}
// this function was attached to the form in the mInit function.
// as a consequence, 'this' reffers to the form itself.
// this.id should give us the id of the form
function onFormKeyUp(e)
{
alert("Keyup detected in the form with the id: '" + this.id + "'");
}
</script>
<style>
</style>
</head>
<body>
<form id='myFormId'>
<input id='textField1'/>
<br>
<button>Some button</button>
</form>
<form id='myFormId2'>
<input id='textField2'/>
<br>
<button>Some button</button>
</form>
</body>
</html>
I am using javascript to create html page , but not able to call some function on button click .
var alernative = "plot1";
var buttonvalue= "mybutton";
function callme()
{alert("hello");}
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' + callme() + '";></div>');
In above code , creating a button and giving its value and calling function onclick of button , but when the page loads it shows alert (that should not happen) and it is not alerting on button click .
Hoping for Suggestion or some help .
You need to pass the function name as a part of the string:
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');
It is a bad practice to write HTML with strings, DOM exists for one reason!
var input = $('<input/>', {
type: "button",
style: "float: right",
value: buttonValue
}),
element = $('<div/>').append(input);
input.click(function () {
callme();
});
$('#test').html(element);
I would like to pass a parameter (i.e. a string) to an Onclick function.
For the moment, I do this:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
with result.name for example equal to string "Add".
When I click on this button, I have an error that says that "Add is not defined". Since this function call works perfectly with a numeric parameter, I assume that it has something to do with the symbols "" in the string.
How can I fix this problem?
It looks like you're building DOM elements from strings. You just need to add some quotes around result.name:
'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
You should really be doing this with proper DOM methods though.
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
document.body.appendChild(inputElement);
Just be aware that if this is a loop or something, result will change before the event fires and you'd need to create an additional scope bubble to shadow the changing variable.
A couple of concerns for me with respect to using string escape in onClick and as the number of arguments grow, it will become cumbersome to maintain.
The following approach will have a one hop - On click - take the control to a handler method and handler method, based on the event object, can deduct the click event and corresponding object.
It also provides a cleaner way to add more arguments and have more flexibility.
<button type="button"
className="btn btn-default"
onClick="invoke"
name='gotoNode'
data-arg1='1234'>GotoNode</button>
In the JavaScript layer:
invoke = (event) => {
let nameOfFunction = this[event.target.name];
let arg1 = event.target.getAttribute('data-arg1');
// We can add more arguments as needed...
window[nameOfFunction](arg1)
// Hope the function is in the window.
// Else the respective object need to be used
})
}
The advantage here is that we can have as many arguments (in above example, data-arg1, data-arg2, etc.) as needed.
I suggest not even using HTML onclick handlers, and use something more common such as document.getElementById.
HTML:
<input type="button" id="nodeGoto" />
JavaScript:
document.getElementById("nodeGoto").addEventListener("click", function() {
gotoNode(result.name);
}, false);
This is a nice and neat way to send a value or object.
<!DOCTYPE html>
<html>
<body>
<h1 onclick="test('wow',this)">Click on this text!</h1>
<script>
var test = function(value,object) {
object.innerHTML= value;
};
</script>
</body>
</html>
I am guessing, you are creating a button using JavaScript itself. So, the error in your code is that, it will render in this form
<input type="button" onClick="gotoNode(add)" />'
At this current state, add will be considered as an identifier like variables or function calls. You should escape the value like this
'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
Try this...
HTML:
<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button>
JavaScript:
<script language="javascript" type="text/javascript">
function a1_onclick(id) {
document.getElementById(id).style.backgroundColor = "#F00";
}
</script>
Note: be sure of sending arguments between ' ' signs like ('a1') in HTML code
If your button is generated dynamically:
You can pass string parameters to JavaScript functions like the below code:
I passed three parameters where the third one is a string parameter.
var btn ="<input type='button' onclick='RoomIsReadyFunc("+ID+","+RefId+",\""+YourString+"\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
Also you can use the grave accent symbol ( ` ) in a string
Try:
`<input type="button" onClick="gotoNode('${result.name}')" />`
For more information, visit MDN and Stack Overflow.
By Chrome, Edge, Firefox (Gecko), Opera, Safari support, but it does not support Internet Explorer.
If the requirement is to reference the global object (JavaScript) in your HTML code, you can try this. [Don't use any quotes (' or ") around the variable]
Fiddle reference.
JavaScript:
var result = {name: 'hello'};
function gotoNode(name) {
alert(name);
}
HTML:
<input value="Hello" type="button" onClick="gotoNode(result.name)" />
Multiple parameters:
bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
'<b>' + response[i].driver_name + '</b><br>' +
'<b>' + moment(response[i].updated_at).fromNow() + '</b>
<button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);
If you need to pass a variable along with the 'this' keyword, the below code works:
var status = 'Active';
var anchorHTML = '' + data+ '';
You can pass a reference or string value. Just put the function inside the double commas "" as per the below snapshot:
If to use for generation of a set of buttons with different parameters of handlers.
JavaScript Closures
let some_button = document.createElement( "button" );
some_button.type = "button";
some_button.onclick = doWithParam( some_param );
function doWithParam( param ){
return function(){
alert( param ); // <-- Your code here
}
}
If we do:
some_button.onclick = foo( some_param );
function foo( param ){
alert( param );
}
then function foo starts after every updating page.
If we do:
for( let i = 0; i < 10; ++i ){
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
document.body.appendChild(inputElement);
}
then for all buttons created in the loop, the last value of the parameter is "result.name".
Here is a jQuery solution that I'm using.
jQuery
$("#slideshow button").click(function(){
var val = $(this).val();
console.log(val);
});
HTML
<div id="slideshow">
<img src="image1.jpg">
<button class="left" value="back">❮</button>
<button class="right" value="next">❯</button>
</div>
<!---- script ---->
<script>
function myFunction(x) {
document.getElementById("demo").style.backgroundColor = x;
}
</script>
<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>
<!---- buttons & function call ---->
<a onClick="myFunction('red')" />RED</a>
<a onClick="myFunction('blue')" />BLUE</a>
<a onClick="myFunction('black')" />BLACK</a>
This is work for me:
$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');
Just add \ slash in ()
※Multiple parameters example
"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"
let task = {....}
<button onclick="myFunction('${task}')">Continue task</button></li>
In Razor, you can pass parameters dynamically:
<a href='javascript:void(0);' onclick='showtotextbox(#Model.UnitNameVMs[i].UnitNameID, "#Model.UnitNameVMs[i].FarName","#Model.UnitNameVMs[i].EngName","#Model.UnitNameVMs[i].Symbol" );'>#Model.UnitNameVMs[i].UnitNameID</a>
If you are using ASP.NET you can use JavaScript:
HTML
<input type='button' value='test' onclick='javascript: EditSelectedOptionName(x,y)' />"
JavaScript
function EditSelectedOptionName(id, name) {
console.log(id);
console.log(name);
}
For passing multiple parameters you can cast the string by concatenating it with the ASCII value. Like, for single quotes we can use ':
var str = "'" + str + "'";
The same parameter you can pass to the onclick() event. In most of the cases it works with every browser.
<style type="text/css">
#userprofile{
display: inline-block;
padding: 15px 25px;
font-size: 24px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #FFF;
background-color: #4CAF50; // #C32836
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
width: 200px;
margin-bottom: 15px;
}
#userprofile:hover {
background-color: #3E8E41
}
#userprofile:active {
background-color: #3E8E41;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
#array {
border-radius: 15px 50px;
background: #4A21AD;
padding: 20px;
width: 200px;
height: 900px;
overflow-y: auto;
}
</style>
if (data[i].socketid != "") {
$("#array").append("<button type='button' id='userprofile' class='green_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username + "</button></br>");
}
else {
console.log('null socketid >>', $("#userprofile").css('background-color'));
//$("#userprofile").css('background-color', '#C32836 ! important');
$("#array").append("<button type='button' id='userprofile' class='red_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username+"</button></br>");
$(".red_button").css('background-color','#C32836');
}
If you are adding buttons or link dynamically and facing the issue then this may be help. I solved it by this way:
var link= $(contentData1[i]).find("td:first font b a").attr("href",'javascript:onClick=openWin(\'' + tdText + '\')');
I am new to HTML, jQuery and JavaScript. So maybe my code will not be optimized or syntax, but it was working for me.
Not escaping double quotes is the cause of OP's problem. A readable approach to escape double quotes is using backticks (MDN). Here is a sample solution:
my_btn.setAttribute('onclick', `my_func("${onclick_var1}", "${onclick_var2}")`);
You can use this:
'<input id="test" type="button" value="' + result.name + '" />'
$(document).on('click', "#test", function () {
alert($(this).val());
});
It worked for me.
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
function displayAlert(msg){
alert(msg);
}
</script>
The following works for me very well,
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<form>
<input type="button" value="ON" onclick="msg('ON')">
<input type="button" value="OFF" onclick="msg('OFF')">
</form>
<script>
function msg(x){
alert(x);
}
</script>
</body>
</html>
You can use this code in your button onclick method:
<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>