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>
`
Related
This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 2 years ago.
In my javascript on load in my index.html, I am getting the data from my backend (Flask app) and putting in a javascript variable. The reason why i am doing this is that while I can directly inject from flask end using {% data %} and do a for loop, I want to do filtering on my data dynamically. For this instead of me fetching from my server always, this is why i load it into a javascript object.
Index.html
<script type="text/javascript">
window.onload = function() {
var productdata = JSON.parse('{{ data | tojson | safe}}');
console.log(productdata)
var output = "";
for (var i in productdata) {
output += "<div class='item' data-product style='float: left; width: 200px;'>"
+ "<article class='product'>"
+ "<a href='/getproduct?priceid=" +productdata[i].priceid+ "'data-url'>"
+ "<img src="+ productdata[i].images+" class='img-fluid' data-img></a>"
+ "<div class='price-group'>"
+ "<div class='price'><span class='currency' data-product-currency>$</span> <span data-product-price>"+productdata[i].price+"</span></div>"
+ "</div>"
+ "<h3><a>"+productdata[i].name+"</a></h3>"
+ "<div class='btngroup'>"
+ "<a type='button' onclick=specialcart() class='add-to-cart btn btn-sm btn-secondary' title='Add to Cart' data-id=" + productdata[i].id + " data-name="+productdata[i].name+" data-price="+productdata[i].price+"></i> Add to cart</a>"
+ "</div>"
+ "</article>"
+ "</div>"
}
document.getElementById('products').innerHTML=output;
}
</script>
I have a jquery function
$('.add-to-cart').click(function (event) {
event.preventDefault();
var name = $(this).data('name');
console.log(name);
var price = Number($(this).data('price'));
console.log(price);
shoppingCart.addItemToCart(name, price, 1);
displayCart();
$('.toast').toast('show');
});
By right, when i call this jquery event, my data will be added into a js array. I have tested it using a static button and it works. However, i notice my button in my js code above in the index.html which is calling my jquery event is not working (nothing is happening).
So my question is how do we call jquery event within my document.getElementById('products').innerHTML=output?
I think it's because .click won't work on dynamically added elements.
Try using .on('click',...) instead.
$('.add-to-cart').on('click', function (event) {
event.preventDefault();
var name = $(this).data('name');
console.log(name);
var price = Number($(this).data('price'));
console.log(price);
shoppingCart.addItemToCart(name, price, 1);
displayCart();
$('.toast').toast('show');
});
I think you have to target your click listener through the document like so
$(document).on('click', '.add-to-cart', function (event) {
event.preventDefault();
var name = $(this).data('name');
console.log(name);
var price = Number($(this).data('price'));
console.log(price);
shoppingCart.addItemToCart(name, price, 1);
displayCart();
$('.toast').toast('show');
});
I was trying to pass a string to a JavaScript function.
As it's mentioned here - Pass a string parameter in an onclick function
I'm using this simple code-
<!DOCTYPE html>
<html>
<body>
<script>
name = "Mathew";
document.write("<button id='button' type='button' onclick='myfunction(\''" + name + "'\')'>click</button>")
function myfunction(name)
{
alert(name);
}
</script>
</body>
</html>
But in the console it's giving an error like Uncaught SyntaxError: Unexpected token }.
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
Rename your variable name to myname, bacause name is a generic property of window and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
onclick='myfunction(myname)'
Working example:
var myname = "Mathew";
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');
function myfunction(name) {
alert(name);
}
The question has been answered, but for your future coding reference you might like to consider this.
In your HTML, add the name as an attribute to the button and remove the onclick reference.
<button id="button" data-name="Mathew" type="button">click</button>
In your JavaScript, grab the button using its ID, assign the function to the button's click event, and use the function to display the button's data-name attribute.
var button = document.getElementById('button');
button.onclick = myfunction;
function myfunction() {
var name = this.getAttribute('data-name');
alert(name);
}
DEMO
document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
Better to use `` than "". This is a more dynamic answer.
You can pass string parameters to JavaScript functions like 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);
}
Use this:
document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')
Try this ...
onclick="myfunction('name')";
How to call the Method in Jquery's Append Method ?
I have the HTML code in which I use the append method() on click of a button.
I want to append the HTML with viewbag data using loop.
here is my code , is that right ?
<html>
<body>
<div class="row-fluid" id="MyCode">
</div>
<button name="AddCode"></button>
</body>
</html>
<script type="text/javascript">
$(document).ready(function ()
{
$('#AddCode').click(function () {
$('#MyCode').append("<di ><div class='span2'>" +
//I want to call the function here...
AddDivs()
);
});
function AddDivs()
{
var ht="";
#foreach (var item in ViewBag.LocationList)
{
ht += "<div id='"+item.Id+"_"+item.Name+"'></div>";
}
}
});
</script>
Its showing undefined.
Change foreach loop with following:
#foreach (var item in ViewBag.LocationList)
{
// these lines are client codes that is in server codes
<text>ht += "<div id='" + #item.Id + "_" + #item.Name + "'></div>";</text>
}
if you dont write your js codes in <text>, razor assume that ht is an server variable.
script tag must be inside of body tag
<script type="text/javascript">
...
</script>
</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);
So I have the following link:
<div class="upload-copy" id="<?php echo $row['RandomName'] . '-html'; ?>" onclick="javascript:getID(this)">Copy To Clipboard</div>
That when clicked it should copy an input using the code below:
<script type="text/javascript">
function getID(theLink){
var clickid = '#' + theLink.id;
var inputid = clickid + '-input';
$(clickid).zclip({
path:'js/vendor/ZeroClipboard.swf',
copy:function(){return $(inputid).val();},
afterCopy:function(){
$(clickid).html('Copied');
}
});
}
</script>
Now this works but only when you click the link twice. How can I make it so it fires on the first click?
I think you can just use the jQuery click function.
Just use the class you have for the click then get the ID attribute and do your other bits and pieces.
$(".upload-copy").click(function() {
var linkid = $(this).attr("id");
// your other code
});
Hope that makes sense.