Show button after function - javascript

I have a search function and a button. I only want the button to appear after the search successfully returns a result, how can I do so?
HTML:
<input type="text" class="searchFeature" ng-model="selected" ng-keyup="$event.keyCode == 13 && searchFunction()" uib-typeahead="value for value in themename | filter:$viewValue | limitTo:7" placeholder="Start your search here.">
<button>DL</button>
JavaScript:
$scope.searchFunction = function() {
// searchLayer.clearLayers();
for ( var i = 0; i < $scope.allTheme.length; i++) {
if ($scope.selected == $scope.allTheme[i].THEMENAME)
{
$scope.selectedTheme = $scope.allTheme[i].QUERYNAME;
apiURL = 'url';
$http.get(apiURL).then(function(response) {
$scope.apiResult = response.data.SrchResults;
$scope.apiResult.splice(0,1);
for (var i= 0; i < $scope.apiResult.length; i++) {
if ($scope.apiResult[i].Type == "Point"){
$scope.dataLatLng.push($scope.apiResult[i].LatLng)
$scope.Lat.push($scope.dataLatLng[i].split(',')[0]);
$scope.Lng.push($scope.dataLatLng[i].split(',')[1]);
L.marker([$scope.Lat[i], $scope.Lng[i]], {icon: greenIcon}).bindPopup($scope.apiResult[i].NAME).addTo(searchLayer);
}
}
})
}
}
}
What I tried doing:
<a ng-href="" ng-click="" ng-if="selectedTheme ==''" download>SHP</a>

you can add some flag in your angular controller and set this flag into your search function if successful and then you can use
<button ng-if="flagOn">DL</button>

This can be done by using ng-show directive
<button ng-show="showButton">DL</button>
In the search fuction after getting executed set $scope.showButton variable to true.

<button ng-if="trunOn">Search</button>
Or
<button ng-show="trunOn">Search</button>
Add ng-if in html button element and
Add condition in that function after the search successfully returns a result.
Example: $scope.trunOn = true;

Related

How I can trigger a function with a button click which is already set to be triggered with "Enter" Key press in AngularJS?

So I was trying to make it possible to add a product to the cart by a button click beside the ENTER key press(which is now the only way to add a product to the cart), I have tried many times but unfortunately all ways does not work at all.
This is a POS system project built with AngularJS (which my experience in it, is very weak) And I need to make it badly
here is the HTML part:
<tr>
<td colspan="6" class="text-center">
<input autofocus autocomplete="off" list="product-list"
id="product-entry" type="text" class="form-control"
name="product-reference" required/><br/>
<button id="myButton" ng-click="" >Add Product to Sale</button>
<datalist id="product-list">
<option ng-repeat="item in inventory" value="{{ item.name }}">
</option>
</datalist>
</td>
</tr>
I need to make it when someone click "myButton" ,I imagine that I need to add some function in ng-click directive,But Any other ways are welcomed
And Here is the JS part :
// POS Section
pos.controller('posController', function ($scope, $routeParams, Inventory, Transactions) {
$scope.barcode = '';
function barcodeHandler (e) {
$scope.barcodeNotFoundError = false;
$scope.barcode = $('#product-entry').val();
var regex=/^[0-9]+$/;
// if enter is pressed
if (e.which === 13) {
if(!$scope.barcode.match(regex)){
for(var i = 0; i < $scope.inventory.length; i++) {
if($scope.inventory[i].name === $scope.barcode) {
$scope.barcode = $scope.inventory[i].barcode;
break;
}
}
}
if ($scope.isValidProduct($scope.barcode)) {
$scope.addProductToCart($scope.barcode);
$scope.barcode = '';
$scope.productsList = '';
$scope.$digest();
$('#product-entry').val($scope.barcode);
}
else {
window.alert('product not found: ' + $scope.barcode);
console.log('invalid product: ' + $scope.barcode);
// $scope.barcodeNotFoundError = true;
}
}
}
$('#product-entry').off('keypress').on('keypress', barcodeHandler);
What you're doing is listening for a keyup event on the field, and if that key matches the return key, it continues with your logic.
If you move the logic into its own function (before barcodeHandler), you can access it elsewhere:
$scope.doSomething = function() {
$scope.barcodeNotFoundError = false;
$scope.barcode = $('#product-entry').val();
var regex=/^[0-9]+$/;
if(!$scope.barcode.match(regex)){
for(var i = 0; i < $scope.inventory.length; i++) {
if($scope.inventory[i].name === $scope.barcode) {
$scope.barcode = $scope.inventory[i].barcode;
break;
}
}
}
if ($scope.isValidProduct($scope.barcode)) {
$scope.addProductToCart($scope.barcode);
$scope.barcode = '';
$scope.productsList = '';
$('#product-entry').val($scope.barcode);
}
else {
window.alert('product not found: ' + $scope.barcode);
console.log('invalid product: ' + $scope.barcode);
// $scope.barcodeNotFoundError = true;
}
};
Then inside barcodeHandler, use:
if (e.which === 13) {
$scope.doSomething();
}
Now in your markup, You can do:
<button id="myButton" ng-click="doSomething()">Add Product to Sale</button>
Adding something to the $scope of the controller is a way of making it available in the view.

Validate checkbox with AngularJs

Again i'm having trouble with checkboxes. I'm getting info from an API and showing like checkbox. The problem comes when i'm triying to add a validation. This is a part of my code:
(function() {
'use strict';
var fact = {
templateUrl: './app/components/fact.components.html',
controller: factCtrl
};
angular.module('fApp').component('odcFacturas', fact);
factCtrl.$inject = ["$scope", "couponApi"];
function factCtrl($scope, couponApi) {
var vm = this;
vm.clientOrder = null;
vm.all = false;
vm.sendData = function() {
vm.apiData = couponApi.get({
idOrder: vm.idOrder
}).$promise.then(function(data) {
for (var i = 0; i < data.Response.length; i++) {
data.Response[i].Select = vm.all;
}
vm.coupons = data.Response;
vm.combo = data.Response.length > 0;
});
}
Here i call the info, and the next part of my code check all the checkboxes:
vm.selectAll = function() {
for (var i = 0; i < vm.coupons.length; i++) {
vm.coupons[i].Select = vm.all;
}
if (vm.all == 0) {
alert("Select at least one coupon");
}
}
How can I trigger three validations with a submit button? I mean: what I want to do is validate three cases:
if the checkbox "select all checkboxes" is checked, submit
if there's no selected checkboxes, show the alert message
if there's at least one checkbox (or 'n' checkboxes) selected,
submit
On the HTML view i have this:
<div class ="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="cbx input-group">
<div class="checkbox" name="imtesting" ng-show="$ctrl.coupons.length > 0">
<label><input type="checkbox"
ng-show="$ctrl.coupons.length > 0"
name="allCoupons"
ng-model="$ctrl.all"
ng-click="$ctrl.selectAll()"/>Select all coupons</label>
<ul>
<li ng-repeat="c in $ctrl.coupons">
<input type="checkbox"
name="couponBox"
ng-model="c.Select"
ng-click="$ctrl.result()"
required/>{{c.CodeCoupon}}
<br>
</li>
</ul>
<label class="label label-danger" ng-show="submitted == true && !ctrl.newTest()">Select at least one coupon</label>
</div>
</div>
</div>
</div>
Hope you can help me.
Thanx in advance.
You can use the Select property from each coupon object like
vm.canSubmit = function() {
for(var i = 0; i< vm.coupons.length; i++)
{
if (vm.coupons[i].Select) {
return true;
}
}
return false;
}
Redo the way you are handling your selectsAll function. When you are using angular there is a thing called scope.$apply that is actually running which tells the dom to update if the object or properties have changed. Sometimes if you use for loops the way you are using them it wont register a change.
Try this and it should work:
vm.selectAll = function()
{
vm.all = !vm.all;
vm.coupons.forEach(function(o){
o.Select = vm.all;
})
}
vm.submit = function(){
var checked = 0;
vm.coupons.forEach(function(o){
if(o.Select === true)
checked +=1;
})
if(vm.all || checked > 0){
//submit here
}
else if(checked === 0){
//error
}
}
This will work both ways. If checked it will check all and if unchecked it will uncheck all. That validation will work for all three scenarios.

Disable CheckBox Dynamically using JQuery

I have a collection of checkboxes within a form. I am looping through the collection to check and/or disable the checkboxes. The checking works fine; however, I am having an issue with checking if the checkbox is disabled or not. It always return false even when the checkbox is enabled. I looked at the code over and over, and I could not see a anything that could cause this to happen.
Partial HTML File
<label class="col-lg-3"><div style="padding-left:5px;">View Department</div></label>
<div class="col-lg-1"><input id="Accounting" name="Accounting" type="checkbox" /> </div>
<label class="col-lg-3"> Finance</label>
<div class="col-lg-1"><input id="Finance" name="Finance" type="checkbox" /></div>
<label class="col-lg-3"> Marketing</label>
<div class="col-lg-1"><input id="Marketing" name="Marketing" type="checkbox" /></div>
<div class="col-lg-12">
<hr style="width:100%;" />
</div>
//This is how I disable the checkbox
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
if (typeof (e) !== 'undefined') {
if (e) {
switch (e) {
case 'Education':
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id == 'Accounting') || (collection[i].id == 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
break;
}
}
}
//The rendering HTML
<input checked="checked" id="Accounting" name="Accounting" type="checkbox" disabled>
//checking if the field is disabled or not
var isAccountingDisabled = $('#Accounting').is(':disabled');
//The above code always return false. Why is that?
I added a screen shot of the checkbox property showing that the checkbox is automatically checked and disabled. Even though the checkbox is rendering as disabled, the property does not show it as being disabled.
You can't have multiple elements with the same id. In your looping structure you can add the index of the loop also to the id, so that it will be unique. (Accounting1, Accounting2...)
Change your code to something like this
var checkBoxesCollection = $("#yourparentelement").find("input:checkbox[name='Accounting']");
$.each(checkBoxesCollection, function(){
if (this.disabled) {
};
});
http://jsfiddle.net/eanamztz/
Use === instead of ==
for (var i = 0; i < collection.length ; i++) {
if ((collection[i].id === 'Accounting') || (collection[i].id === 'Finance')) {
collection[i].disabled = true
} else {
collection[i].disabled = false
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
I was not able to read the property using $('#Accounting').is(':checked'); however, I was able to read them using the syntax below.
var collection = document.getElementById('DepartmentClassModal').getElementsByTagName('input');
$.each(collection, function (index, item) {
ListDepartments[item.name + "Disabled"] = item.disabled;
})

Submitting a 'input type="submit"' button using JavaScript with a Value and without ID or Name

I want to submit a button using JavaScript that looks like this:
<input type="submit" value=" somevalue ">
I was told that the web page is using jQuery but I have no clue.
Any suggestion ?
You can check for the inputs in the DOM that have type="submit" and then fire click() for it.
var elms = document.getElementsByTagName('input');
for(var i = 0; i < elms.length; i++) {
if(elms[i].type == "submit") {
elms[i].click();
break;
}
}
It would be easier to start from the parents though, like the form containing this input.
EDIT:
Alright, since there are many input type="submit" in the page and apparently we know nothing about the one we want to fire but its value is different from the other submits we can add the value check to the code as well:
var elms = document.getElementsByTagName('input');
for(var i = 0; i < elms.length; i++) {
var sb = elms[i];
if(sb.type == "submit" && sb.value == "YOUR_VALUE" ) {
sb.click();
break;
}
}

JQuery Validated Form Not Submitting

I have a form that I am using on my site and it is validated with some simple JQuery validation. Problem is it's not submitting or doing anything really when I change the values. Here is my code:
<form id="radForm" method="post" action="events.php?type=rad">
<div class="searchBoxLeft searchBoxRad"></div>
<div class="searchBoxMiddle">
<input id="radSearch" type="text" class="searchBoxInput searchBoxShort" value="<?php echo $yourradius; ?>" />
<label class="searchBoxLabel">Mile Radius of Your Address</label>
</div>
<div id="radButton" class="searchBoxRight"></div>
<div class="clearLeft"></div>
</form>
<script>
$(document).ready(function()
{
var radsearchok = 0;
//Rad search
$('#radSearch').blur(function()
{
var radsearch=$("#radSearch").val();
if(radsearch < 2){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else if(radsearch > 50){
$('#radSearch').addClass("searchError");
radsearchok = 0;
}
else{
$('#radSearch').addClass("searchSuccess");
radsearchok = 1;
}
});
// Submit button action
$('#radButton').click(function()
{
if(radsearchok == 1)
{
$("#radForm").submit();
}
else
{
$('#radSearch').addClass("searchError");
}
return false;
});
//End
});
</script>
Can anyone see what is wrong with this?
You need to go back and set the .val() property again of your form, otherwise it will take the original value of .val() not radsearch;
Not sure if you actually want to update .val() though or just attach a property. Some options:
Right before the closing brace of .blur --> }); add"
$("#radSearch").val(radsearch);
Or:
Add a hidden input to your form with a new ID like:
<input type='hidden' name='radsearchHidden' />
and then do the same before the end of .blur:
$("#radsearchHidden").val(radsearch);
I made some changes to your code (http://jsfiddle.net/zdeZ2/2/) which I'll describe below:
<div id="radButton" class="searchBoxRight"></div> I assume you have something in there=> <input id="radButton" class="searchBoxRight" type="button" value="rad button">
I rewrote your validator with blur as follows. As suggested it coroses the radSearch value to an integer before comparisions The changes remove the searchError and searchSuccess classes before validating. I also made some optimizations for you.
//Rad search
$('#radSearch').blur(function () {
//remove classes from previous validating
var $this = $(this).removeClass("searchError").removeClass("searchSuccess");
var radsearch = $this.val() | 0; //radsearch is an integer
if (radsearch < 2 || radsearch > 50) {
$this.addClass("searchError");
radsearchok = 0;
} else {
$this.addClass("searchSuccess");
radsearchok = 1;
}
});
Can be equivalently written as:
//Rad search
$('#radSearch').blur(function () {
var $this = $(this);
var radsearch = $("#radSearch").val() | 0; //radsearch is an integer
var valid = radsearch < 2 || radsearch > 50;
$this.toggleClass("searchError", !valid)
.toggleClass("searchSuccess", valid);
radsearchchok = valid ? 1 : 0;
});

Categories

Resources