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>
Related
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 several buttons that use the same implementation but need to pass a different parameter to the function. This if for an mp3 player for context. My idea should be easy to follow, but I cannot get the syntax to work. Hope someone can help.
The button in HTML:
<input id="songToPlay" type="button" value="Click To Play!"/>
Then the javascript onclick call:
document.getElementById('songToPlay').onclick = playSongByThisBand;
The method playSongByThatBand():
function playSongByThisBand() {
playSongByAnyBand(theIntegerThatRepresentsThisBand);
}
The method playSongByAnyBand(parameter):
function playSongByAnyBand(anIntegerThatRepresentsABand) {
currentSongIndex=anIntegerThatRepresentsABand;
//other implementation ect...
}
An alternative approach I tried is:
function playSongByAnyBand(anIntegerThatRepresentsABand) {
currentSongIndex=anIntegerThatRepresentsABand;
someObject = function() {other implementation ect...}
}
var functionIWantToExecutre = new playSongByAnyBand(anIntegerThatRepresentsABand)
functionIWantToExecute.someObject();
I cannot get playSongByAnyBand to execute. I could implement each button separately but that is even more redundant that my approach already. Can anyone help me with the syntax to implement multiple buttons this way?
By Javascript
<input type="button" value="Play" onclick="playSong('param1')" />
function playSong(param) {
// do something
}
With jQuery
<input type="button" value="Play" id="btnPlay" data-param="param1" />
$("#btnPlay").click(function() {
var param = $(this).data("param");
// do something
});
In your button specify the band as a data attribute :
<input id="songToPlay"
type="button"
value="Click To Play!"
data-band="bandName" />
The in your event handler yoiu can fetch it thus :
function playSong (ev) {
var song = this.id;
var band = this.getAttribute ('data-band');
// .. put your play code for band/song rght here
}
Another way of accessing the data-band attribute is using the dataset a relatively new HTML feature now available on most current browsers.
function playSong (ev) {
var song = this.id;
var band = this.dataset.band; // Fetches attribute 'data-band'
// .. put your play code for band/song rght here
}
You can add as many data-xxx attributes as you like for different infos. Each is a string value.
I would like to know how to pass Angular ng-repeat variable to my Javascript onclick event
My angular repeater
<div class="data" data-ng-repeat="sub in subs" >
<button onclick="ConfirmDialog(sub.SubID)">Cancel</button>
{{ sub.someOtherProperty}}
{{ sub.someOtherProperty}}
{{ sub.someOtherProperty}}
</div>
My script function
<script type='text/javascript'>
function ConfirmDialog(subID) {
console.log('Succesfully submitted id: ', subID);
});
</script>
The error : sub is not defined (in the onclick() call from the button element) all other properties show as expected.
You are running straight javascript onclick instead of ng-click.
move confirmDialog into your controller and ng-click can attach to it.
<div class="data" data-ng-repeat="sub in subs" >
<button ng-click="ConfirmDialog(sub.SubID)">Cancel</button>
</div>
$scope.ConfirmDialog = function (subID) {
console.log('Succesfully submitted id: ', subID);
});
If you don't want to use ng-click, you still have a chance! Try the following
<tr ng-repeat="supplier in suppliers" id="{{supplier.id}}">
<button onclick="readVariable(this);">
</tr>
<script>
function readVariable(elem){
id = elem.parentNode.id;
console.log(id); //it works!
}
</script>
You should use ng-click instead in order to access the ng-repeat variable
<button ng-click="ConfirmDialog(sub.SubID)">Cancel</button>
I want to display the data from a ViewBag in my View with Javascript. Here is my code.
View
<span id='test'></span>
Javascript
function myFunction()
{
$('#test').text('#ViewBag.Test');
}
When myFunction() is called I get the text #ViewBag.Test but not his value. How can I fix this ?
You need to place your JavaScript which takes the #ViewBag.Test value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.
If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
// in the view:
var testText = '#ViewBag.Test';
// in external js
function myFunction() {
$('#test').text(window.testText);
}
Alternatively, you can use a data-* attribute:
<span id='test' data-text="#ViewBag.Test"></span>
// in external js
function myFunction() {
$('#test').text(function() {
return $(this).data('text');
});
}
What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.
Your GET action method
public ActionResult View(int id)
{
var vm=new CustomerViewModel();
vm.LastName="Scott"; // You may read this from any where(DAL/Session etc)
return View(vm);
}
and in your view which is strongly typed to your view model.
#model CustomerViewModel
<div>
Some Html content goes here
</div>
<script type="text/javascript">
var lastName="#Model.LastName";
//Now you can use lastName variable
</script>
EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.
#model CustomerViewModel
<div>
<span id="content"></span>
#Html.HiddenFor(s=>s.LastName)
<input type="button" id="btnShow" value="Show content" />
</div>
<script type="text/javascript">
$(function(){
$("btnShow").click(function(e){
$("#content").html($("#LastName").val());
});
});
</script>
Firstly make sure your ViewBag.Test does got a value, then use a div tag instead of a span and add the following code:
<script type="text/javascript">
$(document).ready(function () {
StartRead();
});
function StartRead() {
document.getElementById("test").innerHTML = '#ViewBag.Test';
}
</script>
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);
}});
}