ng-click no longer calls function after different dom element removed - javascript

Whenever I remove a dom element that precedes an element that has a ng-click attribute specified, it will no longer call the function that the ng-click references.
Here is an example of it not working. Note: if you change if(true) to if(false) and click save it will properly call the function.
function MainCtrl($scope) {
$scope.submit = function() {
alert('submitted');
}
function load() {
if(true){
$('#resetPassword').remove();
}
}
load();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app>
<div ng-controller="MainCtrl">
<div class="btn-group m-b-20 pull-right" role="group">
<button type="button" id="resetPassword" class="btn btn-success">Reset Password</button>
<button type="button" class="btn btn-success" ng-click="submit();">Save</button>
</div>
</div>
</div>

I don't know why this is happening, but you should not use jQuery. Use ng-if to add or remove the button on condition. That's the way to go with Angular. jQuery's remove here looks dirty. ng-show just show or hides, but ng-if adds or removes the element from the DOM. It's what you want, and by far the simplest solution.

You should try to accomplish this with a custom directive. E.g:
JS
app.directive("removeClick", function() {
return {
link:function(scope,element,attrs)
{
element.bind("click",function() {
element.remove();
});
}
}
});
HTML
<div ng-app>
<div ng-controller="MainCtrl">
<div class="btn-group m-b-20 pull-right" role="group">
<button type="button" id="resetPassword"class="btn btn-success">Reset Password</button>
<button remove-click type="button" class="btn btn-success" ng-click="submit();">Save</button>
</div>
</div>
</div>
You are free to use getElementbyId at this point, although you should probably try to pass the correct element to your directive. This will probably give you a basic understanding of angular directives.
https://docs.angularjs.org/guide/directive

Related

Why I can apply JS/Jquery function to a button specific ID, but can't link to his class?

I'm trying to apply a function when a button is pressed, but sometimes the button is appended, so I tried to apply the function to his class. The problem is that I can only make the function work when I link it to the button ID, when I link the class nothing happens. This happens to the button that is appended and to the normal button as well.
$(document).on('click', '.createCustomLayer', function () {
alert("Alert");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-light form-control" id="createCustomLayer" class="createCustomLayer" style="margin-top: 32px;">Create a custom layer</button>
If I change the .createCustomLayer for #createCustomLayer, all works fine.
You can't have multiple class="" move createCustomLayer into class="btn btn-light form-control", so it looks like class="btn btn-light form-control createCustomLayer"
Demo
$(document).on('click', '.createCustomLayer', function () {
alert("Alert");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-light form-control createCustomLayer" id="createCustomLayer" style="margin-top: 32px;">Create a custom layer</button>
This is because you have more than one class attribute in the element. If you have multiple class attribute in the same element then except the first one all are simply ignored:
$(document).on('click', '.createCustomLayer', function () {
alert("Alert");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-light form-control createCustomLayer" id="createCustomLayer" style="margin-top: 32px;">Create a custom layer</button>

Why the values of a function are not reflecting their values during function call in angularjs?(new to angularjs)

I need to display a div of comment box section on ng-click of the button invoking the function from controller as defined in the below HTML...picking up the index values from the table and validating the ng-if condition as shown in the code
<button class="btn btn-outlined" ng-click="vm.showCommentBox1($parent.$index, $index)">Save All</button>
<div class="comment-box custom saveAll" ng-if="tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented">
<div class="panel panel-default">
<div class="panel-heading">
<button type="button" class="close" aria-label="Close" ng-click="baseline.toBeSaved = false" title="Close comment box"><span aria-hidden="true">×</span>
</button>
<h3 class="panel-title blue-30">Comment</h3>
</div>
<div class="panel-body">
<form>
<div class="form-group">
<textarea class="form-control bg-white" ng-model="tableData.template.selectedTowers[$parent.$parent.$parent.$parent.$index].baselines[$index].comment"
placeholder="Add your description"></textarea>
</div>
<button ng-click="saveAllRows(tableData.dealName, tower.towerName, baseline, $parent.$parent.$parent.$parent.$index, $index, tower.towerGeo, tableData.template.selectedTowers[$parent.$parent.$parent.$parent.$index].baselines[$index].comment)"
class="btn btn-filled btn-xs pull-right">Submit</button>
</form>
</div>
</div>
</div>
The function with the arguments are going undefined while the same arguments in different function possess some values
vm.showCommentBox1 = function (towerIndex, baselineIndex) {
$scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented = true;
$scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeSaved = true;
$scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].showPreviousComments = false;
}
in the above code towerIndex and baselineIndex are going undefined while the same has some values intended when different functions are invoked
Example:the below function possess the values for both the arguments
vm.enableSaveButton = function (towerIndex, baselineIndex) {
// console.log("Changed", baseline);
$scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented = true;
}
By,this situation im stuck and im not able pass the ng-if condition true in my HTML so that i can display the comment box.
please,help on this
Thank you
As it was a button outside the table i can't pass the parameters as ($parent.$index,$index) from controllers because only table possess the $index values...it was my bad i didn't notice that at beginning.

How to get prev textarea element

I want to get a text from a textarea after clicking on button that is next to the textarea.
The problem is that I will have many textareas and every button must returns the text of the textarea that corresponds to it.
This is my code
function btnmodif(){
var mod = $(this).prev().val();
alert(mod);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif()">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif()">get text</button>
</div>
You have to pass object clicked to btnmodif function.
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
JS
function btnmodif(button){
var mod = $(button).prev().val();
alert(mod);
};
Also, you should use .prev function.
Read more about .prev() function, here.
function btnmodif(button){
var mod = $(button).prev().val();
alert(mod);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
Firstly, you need to pass the clicked element as context to the function:
onClick="btnmodif(this)"
...
function btnmodif(button){
Second, if the HTML structure will remain the same (i.e. the textarea is always going to be the element immediately before the button), then you can use prev()
var mod = $(button).prev('textarea').val();
https://api.jquery.com/prev/
If that structure isn't guaranteed to be maintained, then .siblings() gives you a bit more flexibility, as it searches through all the elements at the same hierarchical level in the DOM to find what you want:
var mod = $(button).siblings('textarea').val();
https://api.jquery.com/siblings/
Here is what are you looking for.
Add this as parameter to your button.onclick
Thanks to jQuery:
Using $(element).parent(), you get your div element.
Using $(element).parent().find('.list_input'), you get your textarea element.
Using $(element).parent().find('.list_input').text() gives you the value of the textarea "related to" the clicked button.
function btnmodif(element){
var result = $(element).parent().find('.list_input').text();
alert(result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="list-item-edit">
<textarea class="list_input">eggs</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
<div class="list-item-edit">
<textarea class="list_input">water</textarea>
<button class="btn btn-modify-item" onClick="btnmodif(this)">get text</button>
</div>
You're missing the this from the inline handler specification:
https://jsfiddle.net/3mvod6ux/
Use siblings with a selector to get the textarea's value that belong to the same block of the button clicked.
function btnmodif(button){
var mod = $(button).siblings("textarea").val();
alert(mod);
};
Another way to do this task .
Instead to use HTML event attribute this is better approach.
var btnModifyItem = $('.btn-modify-item');
btnModifyItem.click(function(){
var mod = $(this).prev().val();
alert(mod);
})
This way you can get the parent of button (and textarea) and then can get the text from child textarea:
$('button').on('click', function () {
console.log(($(this).parent().find("textarea").text()));
});

Trying to make a button in JavaScript but it's not working

I'm new in JavaScript and I took an app here to learn how to use the language.
So, In my index.html I have this code here:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
and this as footer:
`<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>`
What I'm basically trying to do is just reset the score to zero. But It's not working...
I tried to put some alert() inside reset() function but didn't work also.
Does someone has a clue why this is happening?
Thanks for helping!
Use onclick property:
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore" onclick="reset()">Reset</button>
<script type="text/javascript">
function reset() {
localStorage.setItem('total_win', 0);
localStorage.setItem('total_lose', 0);
}
</script>
</div>
You are declaring the function but not calling it anywhere. So you need to call the function at onclick event of button.
You should add an event listener for the click event.
Because of your comment, you can change the DOM by changing the inner HTML, see below snippet and code:
document.getElementById('resetscore').addEventListener('click',function() {
//localStorage.setItem('total_win', 0);
//localStorage.setItem('total_lose', 0);
document.getElementById('total_win').innerHTML = 0;
document.getElementById('total_lose').innerHTML = 0;
});
document.getElementById('win').addEventListener('click',function(){
var a = parseFloat(document.getElementById('total_win').innerHTML);
document.getElementById('total_win').innerHTML = (a+1).toFixed(0);
});
document.getElementById('loss').addEventListener('click',function(){
var b = parseFloat(document.getElementById('total_lose').innerHTML);
document.getElementById('total_lose').innerHTML = (b+1).toFixed(0);
});
<div data-role="collapsible">
<h3>Reset Score</h3>
<button type="button" id="resetscore">Reset</button>
<button type="button" id="win">+1 Win</button>
<button type="button" id="loss">+1 Loss</button>
</div>
<div id="scores" class="ui-grid-b">
<div class="ui-block-a">Tries left:<span id="tries_left">4</span></div>
<div class="ui-block-b">Total win:<span id="total_win">0</span></div>
<div class="ui-block-c">Total lost:<span id="total_lose">0</span></div>
</div>
your script tag can't be inside a div. You need to move all your javascript to the end of your body, right before its closing tag, after all the html
Just add this:
<button type="button" onclick="reset()" id="resetscore">
You need to tell which one of your functions to use, notice the onclick, it does just that, so reset executes on click
Your button needs to call reset
<button type="button" id="resetscore" onclick="reset()">Reset</button>

Fire button click event when there are multiple classes on an element

How would I fire a button click event when a particular button is pressed (in this case the accept button).
I've tried the following but with little success:
Javascript
$('.notification-expand .Request .active-item > .accept-button').click(function () {
alert("hello");
});
HTML
<div class="notification-expand Request active-item" style="display: block;">
<div class="notification-body"></div>
<br>
<p>
<button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
</p>
<div class="row">
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
</div>
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
</div>
</div>
</div>
Fiddle here
You have error in your selector , it should look like this:
$('.notification-expand.Request.active-item .accept-button').click(function () {
alert("hello");
});
You need to concatenate all classes without spaces to catch your target button
$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
alert("hello");
});
See the updated snippet
Notice the syntax of ".className1.className2" instead of ".className1 .className2"
should be something like:
$('button.accept-button').click(function(){ ... });
there is really no need to go down the whole list if this is the whole code
----edit----
so when there are more items but only 1 active(i guess) then just target the active-item class:
$('div.active-item button.accept-button').click(function(){ ... });
try
$('.accept-button', $('.notification-expand.active-item')).click(function () {
alert("hello");
});
or
$('.notification-expand.active-item')).find('.accept-button').click(function () {
alert("hello");
});
Just give the button an id and reference back to that.
HTML
<button id="btnSubmitData"> Ok Button </button>
JQuery Code
$('#btnSubmitData').click(function(){ ... });
You can also have multiple button Ids bind to the same event:
$('#btnAccept, #btnReject, #btnWarning').click(function () {
alert("hello");
});
Take a look at the updated Working Fiddle.

Categories