This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript not being called in inline event handler
Trying to build a javascript based like/dislike system using AJAX to perform the actions. The like and dislike functions are named "likeit" and "dislikeit".
HTML:
<a class="btn" data-toggle="tooltip" title="I like this." id="like" onclick="likeit('abc123');"><i class="icon-thumbs-up"></i></a>
<a class="btn" data-toggle="tooltip" title="I didn't like this." id="dislike" onclick="dislikeit('abc123');"><i class="icon-thumbs-down"></i></a>
JS:
$(document).ready(function() {
"use strict";
(function likeit(id) {
$.post("likeDislike.php", {likeID:id}, function(data) {
alert(data);
// Nothing to be displayed.
});
});
(function dislikeit(id) {
});
});
The error I'm getting in Google Chrome's Inspect Element is:
Uncaught ReferenceError: likeit is not defined
Uncaught ReferenceError: dislikeit is not defined
Yet, they are defined right there.
Your onclick=".." stuff (which you shouldn't use anyway) can only access the global scope. Your functions are defined in the scope of the document.ready callback function.
The proper solution is registering your handlers using JavaScript instead of inline events.
$(document).ready(function() {
"use strict";
function likeit(id) { ... }
function dislikeit(id) { ... }
var funcMap = {
'like': likeit,
'dislike': dislikeit
};
$('.btn').on('click', function(e) {
e.preventDefault();
var action = $(this).data('action');
var id = $(this).data('id');
var func = funcMap[action];
if(func) {
func.call(this, id);
}
})
});
Your HTML also needs some modifications:
<a class="btn" data-toggle="tooltip" title="I like this." id="like" data-id="abc123" data-action="like"><i class="icon-thumbs-up"></i></a>
<a class="btn" data-toggle="tooltip" title="I didn't like this." id="dislike" data-id="abc123" data-action="dislike"><i class="icon-thumbs-down"></i></a>
try this
//make sure jquery library loaded here
<a class="btn" data-toggle="tooltip" title="I like this." id="like" onclick="likeit('abc123');"><i class="icon-thumbs-up"></i></a>
<a class="btn" data-toggle="tooltip" title="I didn't like this." id="dislike" onclick="dislikeit('abc123');"><i class="icon-thumbs-down"></i></a>
<script type="text/javascript">
function likeit(id){
$.post("likeDislike.php", {likeID:id}, function(data) {
alert(data);
// Nothing to be displayed.
});
}
function dislikeit(id) {
}
</script>
Related
I have a page with a lots of buttons from PHP output with each buttons having different values:
<button class='add' value=".$row['cat_no']." onClick='addItem(value)'>Add To Cart</button>
$row['cat_no'] is data from mysql.
I want to check the button's value when I click it, so I use native JS below:
<script>
function addItem(value) {
alert("this.value");}
</script>
It is not working...it just return this.value. In this case I don't think it is suitable to assign Id to getElementbyId, Pls help to check my mistake or suggest solution. Thanks.
Pls: I dont want to use JQUERY, just native JS.
Use alert(elmt.value); like below. you should pass this to the function
<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>
<script>
function addItem(elmt) {
alert(elmt.value);
}
</script>
the code below helps you retrieve the value of the element that triggered the event:
<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>
<script>
function addItem(sender) {
alert(sender.value);
}
</script>
However, this is filled with code smells.
I would suggest doing the code below
<button id='add-to-cart' class='add' value="test value">Add To Cart</button>
On a separate JS file:
(function() {
function _onLoad() {
var addToCartButton = document.getElementById("add-to-cart");
addToCartButton.addEventListener("click", _onAddToCartClicked);
}
function _onAddToCartClicked() {
var sender = this;
alert(sender.value);
}
document.addEventListener("DOMContentLoaded", _onLoad, false);
})();
This approach ensures that:
Concerns are separated between HTML and JS
External JavaScript file would be cached which results to faster page load time.
UI would render faster since there are no inline scripts
Global namespace won't be polluted
You don't really need this in your function, just use value. And also remove double quotes, because you need to alert function's parameter, not string, like this:
function addItem(value) {
alert(value);
}
Here is the working example:
function addItem(value) {
alert(value);
}
<button class='add' value="yourValue" onClick='addItem(value)'>Add To Cart</button>
Or you can pass the element to function using this, and then get the needed attribute value from addItem method:
function addItem(item) {
alert(item.value);
}
<button class='add' value="yourValue" onClick='addItem(this)'>Add To Cart</button>
currently I am working on modification Remote Modal (show href in modal).
<a id="btnAdd" class="btn btn-sm btn-primary" role="button" data-toggle="modal" data-target="#DetailModal" data-tot="60" href="http://urlmodal">
on javascript I have
$('#DetailModal').on("loaded.bs.modal", function (e) {
alert($(e.relatedTarget).data('tot'));
});
I wanna to catch variable "data-tot" in link (button), but it result undefined. either $(e.relatedTarget).data('tot') or $(e).data('tot') result undefined.
Found it, I need to iterate show then loaded to catch then put in remote modal
$('#DetailModal').on("show.bs.modal", function (e) {
var dtot = $(e.relatedTarget).data('tot');
$('#DetailModal').on("loaded.bs.modal", function (e) {
$(e.target).find('#infoTot').html(dtot);
});
});
I'm doing a web game with javaScript and KnockoutJs library.
In my html file I have a array foreach, and the number that this array saves, is the same number of buttons that a I have to draw on the page. Like this:
<strong data-bind = "foreach: cena1.opcoes">
<button data-bind="click: $parent.teste">Opcão</button>
<font color="red"><strong data-bind="text: conteudo"> </strong></font><br>
What I want to know is, how will I know which button the player selected?
I put data like a parameter on my button function, but I don't know how this works. like this:
object.teste = function(data) {
}
You can call the function this way:
<button data-bind="click: function() { $parent.teste($data); }">Opcão</button>
or
<button data-bind="click: function() { $parent.teste($data/* here can be any arguments available in the current binding context */); }">Opcão</button>
Update
By default the first parameter is being passed to the click handler function is the current view model - $data in the current binding context.
For more details and advanced scenarios you can check the Knockout JS documentation.
The click binding passes the current item to the bound function.
var vm = {
items: [1, 2, 3],
click: function(data) {
alert('You clicked: ' + data);
}
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach:items">
<button data-bind="click:$parent.click">Click</button>
</div>
I have a call to a service using ajax, i would like if everything goes well on the ajax call to enable or display an input (maybe in a div?) on my page that when clicked it will close the current window. What is the best way to do this using javascript?
Here is my function of a javascript class:
MyFunction.prototype.init = function(param1, param2) {
this.MyParams = new Hash();
this.MyParams.set("param1", param1);
this.MyParams.set("param2", param2);
new Ajax.Request('MyService.asmx/MyServiceFunction', {
method: 'post',
onSuccess: //how can i do what i mentioned here?,
onFailure: failureFunc,
onException: ajaxError,
parameters: this.MyParams
});
}
Any help would be much appreciated
On the onSuccess part you have to put something like this:
OnSuccess: function() {
$('div_to_show').show();
}
In the HTML part you will have this:
<div id="div_to_show">
<input type="button" name="close" id="close" value="close" onclick="javascript:window.close();" />
</div>
Of course you have to hide the div on document loading.
in .gsp file i have javaScript function
<script type="text/javascript">
function getCurrentItemNumber(){
return document.getElementById('item_itemNumber').innerHTML.substr(6);
}
</script>
and in g:remoteLink I like to pass param using that function
something like following ...
<g:remoteLink id="remove_item_button" action="removeItem" update="itemBox"
params="[itemNumber:getCurrentItemNumber()]">- Remove Item</g:remoteLink>
How can I achieve that?
AS workaround I can suggest following
change g:remoteLink to simple link
"<"a id="remove_item_button" class="btn small primary" onclick="removeItem();">- Remove Item "<"/a>
Add javaScript function which will submit data via AJAX
function removeItem() {
$.ajax({type:'POST',
data:{'itemNumber':getCurrentItemNumber()},
url:'${createLink(action: 'removeItem')}',
success:function (data, textStatus) {
jQuery('#itemBox').html(data);
}});
}