Moving code from jquery to angularjs - javascript

I have following code block in jQuery which I need to convert it into angularjs
JS Code
command: [
{
name: "Delete",
text: "<span class='glyphicon glyphicon-trash' aria-hidden='true'></span>",
click: function (e) {
e.preventDefault();
//add a click event listener on the delete button
var tr = $(e.target).closest("tr"); //get the row for deletion
var data = this.dataItem(tr); //get the row data so it can be referred later
wnd.content(confirmationWindowTemplate(data)); //send the row data object to the template and render it
wnd.open().center();
wnd.title("Delete Prospect");
$("#yesButton").click(function (e) {
alert("hi")
})
//$("#noButton").click(function (e) {
$scope.noButton = function() {
alert("hi!");
}
},
]
HTML Code
<div class="pull-right">
<button class="btn btn-blue" id="yesButton">Yes</button>
<button class="btn btn-default" ng-click="noButton()"> No</button>
</div>
I have not posted the entire code as it would be too lengthy. I want to convert this jquery code into angularjs. As you can see I am trying to call Yes and No function with jQuery and Angularjs respectively. When I click on yes, I see an alert message "hi" but I don't get an alert message when I click on no.
I am sorry if this question provides insufficient details. I am stuck on this from past 2 days. Any help would be appreciated.

How/where your code $scope.noButton = function() { alert("hi!"); }
is placed? as per my angularjs knowledge, you required controller in your HTML code and then you can set button with ng-click inside that controller, which will finally bind function in your angular controller file code.
Ref - http://fdietz.github.io/recipes-with-angular-js/introduction/responding-to-click-events-using-controllers.html
and here your yes button code $("#yesButton").click(function (e) { alert("hi") }) is working with jQuery so its working correctly

Related

Disable load function untill button is selected in javascript?

Hi this is an odd question and i will try to ask it correctly. I have a function using javascript called load canvas.
function loadCanvas(canvas) {
relevant code here...
}
I also have a normal button called btn.
<button class="btn" type="button">Play!</button>
I am wondering can i disable the function until the play button is selected? The function is for a game using javascript. So on load there isnt anything there until i press play then it appears!
any ideas/help please?
$(document).ready(function(){
var loadCanvas= function (canvas) {
relevant code here...
}
$("#test").on('click',loadCanvas()); // using jquery
document.getElementById("test").addEventListener("click",loadCanvas()); // using javascript
<button class="btn" id="test" type="button">Play!</button>
})
If you are having issue because other method is triggering the function you can add a flag with a boolean and turn it on when you click..
Something like that:
The button don't change at all
<button class="btn" type="button">Play!</button>
The js code with this change:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
And in the on click function add this before call the function:
buttonClicked = true;
At the end your js should look like this:
var buttonClicked = false;
function loadCanvas(canvas) {
if(buttonClicked){
relevant code here...
}
}
$(".btn").click(function(){
buttonClicked = true;
var canvas = ...;
loadCanvas(canvas );
});
EDIT
If you have more buttons with the class .btn you should use an id and change the selector of the .click() with the selector of the id instead of the class selector
As you mentioned in the comments <script type="text/javascript"> loadCanvas("game"); </script> You are calling the function as soon as the page loads. So you will have to change it to:
<button class="btn play-button" type="button">Play!</button>
<script type="text/javascript">
$('.play-button').click(function(e){
loadCanvas("game");}
);
</script>
If you are not using jquery you will have to handle the click event by javascript.
You got to do following:
function loadCanvas(game) {
alert('loading canvas');
}
<button class="btn" type="button" onclick="loadCanvas('game')">Play!</button>

Changing what function to call depending on which button is pressed

Okay So I what to have 3 buttons
<div id="button1" onclick="choose1()">Button1</div>
<div id="button2" onclick="choose2()">Button2</div>
<div id="button3" onclick="choose3()">Button3</div>
And a start button
<div id="startButton" onclick="noFunction()">Start</div>
I want to make it so that pressing on of the 3 option buttons it changes what function will be called from the start button and the background image of the start button should change.
Is there a way to do this with just javascript or do I need jquery?
It also doesn't seem possible to use onclick on div tags, jquery to do that aswell?
jsFiddle
You can use onclick on <div> tags. But you shouldn't use onclick on any tags. Don't confuse your HTML layout and display with your JavaScript functionality. Bind your click handlers directly in the JS code (note that this solution is using jQuery):
HTML:
<div id="button1">Button1</div>
<div id="button2">Button2</div>
<div id="button3">Button3</div>
<div id="startButton">Start</div>
JS:
function choose1() {
// ...
}
function choose2() {
// ...
}
function choose3() {
// ...
}
$(function() {
$("#button1").click(choose1);
$("#button2").click(choose2);
$("#button3").click(choose3);
});
You can do it in javascript (anything possible with jQuery is possible with plain javascript, since jQuery is written in javascript).
Changing the click handler for the startButton from javascript is very straightforward:
document.getElementById("startButton").onclick = newFunction;
Changing the background image is also pretty simple:
document.getElementById("startButton").style.backgroundImage = "image.png";
Obviously, you should replace newFunction and "image.png" with the function and image you actually want to use respectively.
You can say
function choose1() {
document.getElementById('startButton').onclick = function() {
alert("Button one was originally press");
}
}
jQuery IS javascript. It is just a library of functions/methods that you can call.
To solve your problem, you should write a function that changes the onclick property of your start button, and add the function you write to the onclick of the other buttons.
Like so:
function chooseOne(){
document.getElementById('startButton').onclick="/\*whatever\*/";
}
A technology like what #nbrooks said in the comments that would do this very well is AngularJS
If you give each selector button a class, you can use javascript to interate them and bind a click event. Then you can store in a data property a key which you can lookup in a json object start stores the related action handler and image. Finally in your click handler you can pull these properties and apply them to the start button by setting the onClick handler and background image of the start button.
<div class="startSelector" data-startdataid="1">Button1</div>
<div class="startSelector" data-startdataid="2">Button2</div>
<div class="startSelector" data-startdataid="3">Button3</div>
<div id="startButton">Start</div>
<script>
var startData = {
"1": {
action: function() {
alert("Button 1 was selected");
},
image: "/images/button1.jpg"
},"2": {
action: function() {
alert("Button 2 was selected");
},
image: "/images/button2.jpg"
},"3": {
action: function() {
alert("Button 3 was selected");
},
image: "/images/button3.jpg"
}
}
var changeStartButton = function(e) {
var startDataIndex = e.target.dataset.startdataid
var data = startData[startDataIndex]
document.getElementById("startButton").onclick = data.action
document.getElementById("startButton").style.backgroundImage = data.image
}
items = document.getElementsByClassName("startSelector")
for (var i = 0; i < items.length; i++) {
items[i].addEventListener("click", changeStartButton);
}
</script>
Example
http://jsfiddle.net/Xk8rv/3/

Attempting to do javascript 'confirm' on a button in the code behind

I have some code on my asp.net page that looks like this:
<input type="button" onclick="if (confirm('ARE YOU SURE? This cannot be undone except by IT at great cost!')) { PurgeCourse(); }" value="Purge Course Comments" id="Button2" name="Button2" />
I'm replacing this with statements in the code behind. So far, my statements looks like this:
var Button2 = new Button();
Button2.Text = "Purge Course Comments";
Button2.OnClientClick = "javascript: PurgeCourse();";
pageButtons.Controls.Add(Button2);
This works great in the button that is added and the PurgeCourse function is called when the button is pressed.
However, I want to add a 'confirm' (as in the original page code above) so that the user must confirm their choice. Is there a way that I can add that same 'confirm' functionality to what I have above?
Just put the JS you originally had into your new buttons client click handler:
Button2.OnClientClick = "if (confirm('ARE YOU SURE? This cannot be undone except by IT at great cost!')) { PurgeCourse(); }"
Create a Javascript function in your ASPX html that has the logic from your first piece of code in the question. Then, call that function on Button2.OnClientClick.
I.E. in the page:
function foo () {
if (confirm( /*.. snip ..*/ ) { /* .. snip .. */ }
}
In the code behind:
Button2.OnclientClick = "javascript: foo()";
instead of calling directly PurgeCourse(), create an intermediary function
function confirmAndPurgeCourse() {
if (confirm('you sure'?')) PurgeCourse();
}
and invoke it in
Button2.OnClientClick = "javascript: confirmAndPurgeCourse();";
Create a new function
function purgeCourseWithConfirm() {
if (confirm('ARE YOU SURE? This cannot be undone except by IT at great cost!'))
{
PurgeCourse();
}
}
Then Button2.OnClientClick = "javascript: purgeCourseWithConfirm();";

knockout.js "with" binding and dynamic html

I want to have a modal dialog to appear with some content and buttons inside it. The dialog should be bound to some observable property or not, the dialog also must have close buttons, one inside its body, another on the top right corner. My main aim is to close this modal form with these buttons, but "Cancel" button inside dialog's body doesn't work as expected.
1) First approach:
In this example dialog is created with static dialog, on "Open dialog" button click it shows up, it gets closed if clicked on top right X link, but it doesn't close on "Close" button click, however I set my observable to null. I was pretty much sure about this approach, as it was described in this brilliant explanation.
Excerpt from my code:
HTML:
<button data-bind="click: openDialog">Open dialog</button>
<div data-bind="with: dialogOpener">
<div data-bind="dialog: { data: $data, options: { close: Close } }">
<button data-bind="click: Save">Save</button>
<button data-bind="click: Close">Cancel</button>
</div>
</div>
JS:
self.dialogOpener = ko.observable();
self.openDialog = function () {
var data = {
Save: function() {
alert('Saved');
},
Close: function() {
alert('Closed');
self.dialogOpener(null);
}
}
self.dialogOpener(data);
}
Fully working example:
http://jsfiddle.net/cQLbX/
2) Second approach shows how my dialog html is dynamically created and it has the contents and the same results as in the first example.
Excerpt from my code:
HTML:
<button data-bind="click: openDialog">Open dialog</button>
JS:
self.dialogOpener = ko.observable();
self.openDialog = function () {
var element = "";
element += '<div data-bind="with: $data">';
element += '<div data-bind="dialog: { data: $data, options: { close: Close } }">';
element += '<button data-bind="click: Save">Save</button>';
element += '<button data-bind="click: Close">Cancel</button>';
element += '</div>';
element += '</div>';
var data = {
Save: function() {
alert('Saved');
},
Close: function() {
alert('Closed');
self.dialogOpener(null);
}
}
self.dialogOpener(data);
ko.applyBindings(data, $(element)[0]);
}
Fully working example:
http://jsfiddle.net/6T3Ra/
My question is:
On both examples "Cancel" button inside body doesn't work, the dialog doesn't close, what am I doing wrong and how to solve this?
Thanks a lot!
made a bunch of changes to your fiddle, maybe not how you want to do it, but the cancel and x buttons both do the same thing now
http://jsfiddle.net/cQLbX/3/
<div data-bind="dialog: dialogOpener, dialogOptions: { autoOpen: false, close: Close, buttons: { 'Save': Save, 'Cancel': Close } }">
<div data-bind='with: dialogContent'>
<div data-bind="text: Test"></div>
</div>
</div>
i usually structure my dialogs like this, and i've had success with them.
I don't know if you use any plugins and what not, but looking at your js fiddle example no2 with the help of a great thing called debugger is that you aren't explicitly telling the element to hide. A solution to this could be the following:
//If you look at E, E would be the ViewModel and X would be the jQuery Event Click
Close: function(e, x) {
//from the event we have currentTarget which is the button that was pressed.
//parentElement would be the first element, and the next parentElement was
//the modal in your demo. When we call hide() it hides the modal from
//which the button was pressed.
$(x.currentTarget.parentElement.parentElement).hide();
//left these as is from your example
alert('Closed');
self.dialogOpener(null);
}

Why does the jQuery file upload stop working after first upload?

I'm using the jQuery File Upload plugin. I'm hiding the file input and activating it upon clicking a separate button. (See this fiddle.)
HTML:
<div>
<button class="browse">Browse</button>
<input id="upload" type="file" style="display: none;" />
</div>
JavaScript:
var element = $("#upload");
$(".browse").click(function () {
$("#upload").trigger("click");
});
element.fileupload({
add: function () {
alert("add");
}
});
Notice that if you press the button then select a file, the add method is activated and you'll get an alert. Do it again, and you'll get another alert.
Now, see this fiddle. The only difference is that I've changed the following line
$("#upload").trigger("click");
to
element.trigger("click");
Notice that now, the first time you click the button then select a file, the add method is activated and you get the alert (just like before), but if you do it again, the add method never activates.
What is causing this difference in behavior?
This can also be solved by setting replaceFileInput to false, as stated by the documentation. This is because the plugin recreates the input element after each upload, and so events bound to the original input will be lost.
It looks as though the scope of element is being lost / changed after the add function. Resetting it like below seems to work.
var element = $("#upload");
$(".browse").click(function () {
element.trigger("click");
});
element.fileupload({
add: function () {
alert("add");
element = $(this);
}
});
Fiddle
Try this one: http://jsfiddle.net/xSAQN/6/
var input = $("#upload");
$(".browse").click(function () {
input.trigger("click", uploadit(input));
});
function uploadit(input){
$(input).fileupload({
add: function () {
alert("add");
}
});
}
Although there is one more way:
just change to this:
var element = $("#upload");
$(".browse").click(function () {
$("#upload").click(); // <----trigger the click this way
});
element.fileupload({
add: function () {
alert("add");
}
});

Categories

Resources