How to pass parameters to function using buttons - javascript

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.

Related

alert value of button by onClick

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>

Angular JS - ng-repeat repeating old values

I am new to Angular JS. I have created a code in angular using app and controller. What I am tyring to do is to add name dynamically to a array when a button is clicked.
By default my array has two value passed. When i give an input and click the add button,it adds the string for the first time.
But when i give another input and click add again, the old string is replaced by the new string and the new string is added again.
Here is the piece of code on JSFiddle: http://jsfiddle.net/5DMjt/3680/
var demo= angular.module("demo",[]);
var simplecontroller = function($scope){
$scope.members = [{id:1,name:'prateek'},{id:2,name:'Ruchi'}];
$scope.addmember = function(newmember){
newmember.id = $scope.members.length+1;
$scope.members.push(newmeber);
demo.controller(simplecontroller);
}
}
and here is the HTML Code:
<div ng-app="demo">
<div ng-controller="simplecontroller">
<ul>
<li ng-repeat="member in members">{{member.id}}-{{member.name}}</li>
</ul>
Name<input type="Text" ng-model="inputmember.name">
</br><h2>
{{inputmember}}
</h2>
<input type="button" value="Add" ng-click="addmember(inputmember)">
</div>
</div>
Please Help !
What i analyzed is that push function is passing the address that is why binding still exists.What u can do is pass the value instead like i did below-:
$scope.addmember = function(newmember){
newmember.id = $scope.members.length+1;
$scope.members.push({id:newmember.id,name:newmember.name});
demo.controller(simplecontroller);
}
Hope this solves your problem.Happy learning :)
You have two options.
Either you can reinitialize it every time what I would not recommend.
And the other one is to, pass the parameters with values.
$scope.members.push({id:newmember.id,name:newmember.name});
:)
See this updated fiddle: http://jsfiddle.net/5DMjt/3689/
Name<input type="Text" ng-model="newname">
This gives you a scope variable newname.
<input type="button" value="Add" ng-click="addmember()">
And addmember function uses this newname to create a new object and add it to the list:
$scope.addmember = function(){
var newmember = {};
newmember.id = $scope.members.length+1;
newmember.name = $scope.newname;
$scope.members.push(newmember);
}
You have a syntax error. See console error for more info.
Your variable inputmember is not defined anywhere.
Also you need to push to array new reference of the object, so the old one in array does not change each time you type value.
Here is a working version.
http://jsfiddle.net/a9zvgm8k/
$scope.addmember = function(newMember){
newMember.id = $scope.members.length+1;
$scope.members.push(angular.extend({}, newMember));
demo.controller(simplecontroller);
}
$scope.members = $scope.members.concat({id: newmember.id, name: newmember.name});
Solved : http://jsfiddle.net/5DMjt/3693/
Before pushing to $scope.members you need to create a new object and populate it with id and name from the input.

Form with JQuery Steps using aui:form tag in Liferay submits no data

I built a portlet and added a entity named Idea. There are two JSPs, one is the view and one the edit.
In the view there is only a button to create a new Idea and a table showing all ideas. Clicking on the button shows the edit jsp.
There is a form with two fieldsets and input stuff.
The "problem" is i cannot use the <aui:form ... stuff because it won't work with JQuery steps (or better, i cannot get it working). So i am using normal tag and also JQuery steps is providing the submit button which is only a <a href="#finish" ...>. So that wont bring the form to submit and the data being in the database.
So I tried to do it within the javascript code of the definition of jquery steps like here:
$(document).ready(function(){
var form = $("#wizard").show();
form.steps(
{
headerTag : "h3",
bodyTag : "fieldset",
transitionEffect : "slideLeft",
onFinishing: function (event, currentIndex) {
alert("Submitted!");
var data = jQuery("#wizard").serialize();
alert(data);
jQuery("#wizard").submit();
form.submit();[/b]
},
onFinished: function (event, currentIndex) {
//I tried also here..
},
});
});
But even if i declare the data explicitely it wont put it in the db.
So my idea was that the "controller" class which calls the "addIdea" function is never called.
How am I solving the problem?
Here is also my jsp code for the form part:
<aui:form id="wizard" class="wizard" action="<%= editIdeaURL %>" method="POST" name="fm">
<h3>Idea</h3>
<aui:fieldset>
<aui:input name="redirect" type="hidden" value="<%= redirect %>" />
<aui:input name="ideaId" type="hidden" value='<%= idea == null ? "" : idea.getIdeaId() %>'/>
<aui:input name="ideaName" />
</aui:fieldset>
<h3>Idea desc</h3>
<aui:fieldset>
<aui:input name="ideaDescription" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button onClick="<%= viewIdeaURL %>" type="cancel" />
</aui:button-row>
</aui:form>
Is there a way to "teach" JQuery Steps the <aui:*** tags? I tried it already while initializing the form but it won't work. To get it working using the aui tags would be great. Because otherwise the Liferay portal wont get the data or it would get it only with hacks right?
€dit: What I forgot, when I submit the form using javascript submit, it creates a new dataentry in the db but no actual data in it.
€dit2:
The editIdeaURL is referenced a bit over the form here:
<portlet:actionURL name='<%=idea == null ? "addIdea" : "updateIdea"%>'
var="editIdeaURL" windowState="normal" />
and the addIdea code looks as follows:
In the IdeaCreation class first this:
public void addIdea(ActionRequest request, ActionResponse response)
throws Exception {
_updateIdea(request);
sendRedirect(request, response);
}
Where _updateIdea() is:
private Idea _updateIdea(ActionRequest request)
throws PortalException, SystemException {
long ideaId = (ParamUtil.getLong(request, "ideaId"));
String ideaName = (ParamUtil.getString(request, "ideaName"));
String ideaDescription = (ParamUtil.getString(request, "ideaDescription"));
ServiceContext serviceContext = ServiceContextFactory.getInstance(
Idea.class.getName(), request);
Idea idea = null;
if (ideaId <= 0) {
idea = IdeaLocalServiceUtil.addIdea(
serviceContext.getUserId(),
serviceContext.getScopeGroupId(), ideaName, ideaDescription,
serviceContext);
} else {
idea = IdeaLocalServiceUtil.getIdea(ideaId);
idea = IdeaLocalServiceUtil.updateIdea(
serviceContext.getUserId(), ideaId, ideaName, ideaDescription,
serviceContext);
}
return idea;
}
And to finally put the data using IdeaLocalServiceImpl:
public Idea addIdea(
long userId, long groupId, String ideaName, String ideaDescription,
ServiceContext serviceContext)
throws PortalException, SystemException {
User user = userPersistence.findByPrimaryKey(userId);
Date now = new Date();
long ideaId =
counterLocalService.increment(Idea.class.getName());
Idea idea = ideaPersistence.create(ideaId);
idea.setIdeaName(ideaName);
idea.setIdeaDescription(ideaDescription);
idea.setGroupId(groupId);
idea.setCompanyId(user.getCompanyId());
idea.setUserId(user.getUserId());
idea.setCreateDate(serviceContext.getCreateDate(now));
idea.setModifiedDate(serviceContext.getModifiedDate(now));
super.addIdea(idea);
return idea;
}
Any ideas?

How to submit data from new page to older page

I got a Button on HTML form (let's call it Form_A) which when clicked, opens a new window (let's call it Form_B).
When user fill in some information in Form_B form and hit submit (or just a button), I need to send some processed information back to 'Form_A' and close 'Form_B.'
How can I accomplish it?
This is best illustrated with an example. In the code of Form_A:
<div id="target"></div> <button onclick="window.open('form_b.html'); return false">Open Form B</button>
function receive_data (value)
{
$("#target").text(value);
}
In the code of Form_B:
<input type="button" onclick="window.opener.receive_data('hello'); window.close();">
You can do it using localStorage, like:
<!--FormB-->
<input type="submit" onclick="processInfo();" />
and in your javascript code:
function processInfo(){
//process your information then
//let's day you have 2 variables as a result of your process
var info1 = "My Information 1";
var info2 = "My Information 2";
localStorage.setItem("info1", info1);
localStorage.setItem("info2", info2);
}
then in your code on the next page get your variables whenever you wanted like:
function getInfo1(){
return localStorage.getItem("info1");
}
function getInfo2(){
return localStorage.getItem("info2");
}
and the other solution for ancient browsers is using window.opener, you can use it in your close function like this:
<!--FormB-->
<input type="button" onclick="closeWindow();" />
javascript code:
function closeWindow(){
//process your information then
//let's day you have 2 variables as a result of your process
var info1 = "My Information 1";
var info2 = "My Information 2";
window.opener._info1 = info1;
window.opener._info2 = info2;
window.close();
}
then you can get them in the main page like:
function getInfo1(){
return window._info1;
}
function getInfo2(){
return window._info2;
}
BTW, we usually use _ when we want to simulate private variable, whereas they are not really private.

Javascript to get the id of the hyperlink clicked

I would like to know how i can set the current hyperlink id to a hidden field on clicking the corresponding links. The html control code is as follows:
<a href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent" class="thickbox" id="ExpressionsLink"
title="Create expression column" onclick="keepID()">Add Expressions Model</a>
<a href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent" class="thickbox" id="AggregateMethodLink"
title="Create aggregate column">Add Aggregate Methods</a><input id="HiddenIdHolder"
type="hidden" />
I need the id of the link clicked on the hidden field 'HiddenIdHolder'.
Javascript
function keepID() {
var hiddenInput = document.getElementById("HiddenIdHolder");
hiddeninput.value= ? // What can i do here to get the id?
}
this refers to the element itself. Example on jsFiddle
onclick="keepID(this)"
Then
function keepID(element)
{
var hiddenInput = document.getElementById("HiddenIdHolder");
hiddeninput.value = element.getAttribute("id");
}
Use jQuery:
$('a').click(function() {
$('#HiddenIdHolder').val($(this).attr('id'))
})
You should modify your HTML to provide argument for KeepID function:
ooxx
note that you should provide a this argument when invoke KeepID function, then in KeepID function, you can access this element from argument:
function KeepID(src) {
document.getElementById("HiddenIdHolder").value = src.id;
}

Categories