ionic 5 alert buttons with JavaScript - ionic-framework

Without using any Javascript framework or Class, I am working with pure Javascript and Ionic 5 .
I am trying to display the alert notification when the user hit the Add button
If the User does not fill the fields and then press the ADD Button, an alert pops out to notify the user to fill the fields
Note: Add button its function also is to Add two fields
The issue is when Hit the Add button, No notification pops out
here is the code
HTML section
<ion-alert-controller></ion-alert-controller>
In app.js file
const btnConfirm = document.querySelector('#btn-confirm');
const alertCtrl = document.querySelector('ion-alert-contrller');
btnConfirm.addEventListener('click' ,() => {
const enterReason = reasonInput.value;
const enterInput = parseFloat(amountInput.value).toFixed(2);
if(enterReason.trim().length <=0 || enterInput <= 0 || enterInput.trim().length <=0
) {
async function handleButtonClick() {
const alert = await alertController.create({
message: 'Please enter valid reason and amount!',
header: 'Invalid Inputs',
buttons: ['Okay']
});
await alert.present();
}
return; // if values are Invalid - stop execution

You should do somethign like:
const btnConfirm = document.querySelector('#btn-confirm');
btnConfirm.addEventListener('click' ,() => {
const enterReason = reasonInput.value;
const enterInput = parseFloat(amountInput.value).toFixed(2);
if(enterReason.trim().length <=0 || enterInput <= 0 || enterInput.trim().length <=0) {
presentAlert(); // call your alert function when input is invalid
return;
}else{
// continue execution
}
})
// keep your alert as a function. and call it when ever you want.
async function presentAlert() {
const alert = document.createElement('ion-alert');
alert.cssClass = 'my-custom-class';
alert.header = 'Alert';
alert.subHeader = 'Subtitle';
alert.message = 'This is an alert message.';
alert.buttons = ['OK'];
document.body.appendChild(alert);
await alert.present();
const { role } = await alert.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
}

Related

Event listener is not running if/else statement?

I believe my if/else statements are not running and end up not making the changes to the elements I target. When I run it, I believe the parent element is not being called correctly for the first function. For the second function, it is stating that it's not a node?
Function expandArticleBody()
Find the article in which the button that was clicked belongs.
If the text on the button that was clicked is a V, then set the display property of the article's body to none. Also set the text on the button to >.
If the text on the button that was clicked is not a V, then set the display property of the article's body to block. Also set the text on the button to V.
function highlightArticle()
Find the article in which the button that was clicked belongs.
If the text on the button is +, then add the .highlight class to the article and set the text on the button to -.
If the text on the button is not +, then remove the .highlight class from the article and set the text on the button to +.
function expandArticleBody() {
const allBtns = document.querySelectorAll(".expand_button");
allBtns.forEach((btn) => {
btn.addEventListener("click", (event) => {
let parent = event.target.parentElement;
let text = event.target.innerHTML;
if(text !== "V"){
parent.style.display = "block";
event.target.innerHTML = "V";
} else if(text == "V"){
parent.style.display = "none";
event.target.innerHTML = ">";
}
});
});
}
function highlightArticle() {
const highlight = document.querySelectorAll(".highlightBtn");
highlight.forEach((btn) => {
btn.addEventListener("click", (event) => {
let text = event.target.innerHTML;
if(text == "+"){
event.target.classList.add(".highlight");
event.target.innerHTML = "-";
} else if(text !== "+"){
event.target.classList.remove(".highlight");
event.target.innerHTML = "+";
}
});
});
}

Draft.js insert image at dropped position

I'm trying to drop image from outside of draft-js editor but it's always inserted at last position of the cursor/selection in editor (or at end if cursor/selection not set).
This is my wrap around draft-js-drag-n-drop-plugin
const droppableBlockDndPlugin = {
...blockDndPlugin,
handleDrop: (
selection,
dataTransfer,
isInternal,
{getEditorState, setEditorState}
) => {
const editorState = getEditorState();
const raw = dataTransfer.data.getData('text');
const data = raw ? raw.split(IMAGE_BLOCK_TYPE_SEPARATOR) : [];
if (data.length > 1 && data[0] === IMAGE_BLOCK_TYPE_PURE) {
const url = data[1];
if (url) {
const newState = imagePlugin.addImage(editorState, url);
setEditorState(newState);
}
}
return blockDndPlugin.handleDrop(selection, dataTransfer, isInternal, {
getEditorState,
setEditorState
});
}
};
Basically I'm just doing extra logic before base handleDrop occurs where I insert image using imagePlugin.addImage. Is there way to drop image to dragged position?
Actually it was quite obvious solution - you should just use passed selection and create new state with it and then add image to that new state:
const newState = imagePlugin.addImage(EditorState.forceSelection(editorState, selection), url);
setEditorState(newState);

Ionic switch between tabs with parameters

I have an app with tabs, where the first tab I show the latest post and an input search where a user can filter the results.
When user makes a search, I want to switch to the second tab, which will manage the search and display the results. I want to keep the first tab showing the latest post.
The code for switching to the second tab is:
$scope.search_posts = function() {
if ( !angular.isUndefined($scope.searchText) && $scope.searchText.length > 2 ) {
$scope.searchText = '';
$scope.show_search_box = false;
$ionicTabsDelegate.select($ionicTabsDelegate.selectedIndex() + 1);
} else {
$ionicLoading.show({ template: 'You must write at least 3 characters long.', noBackdrop: false, duration: 2000 });
}
}
...but I do not know how to send the 'searchText' as a parameter when switching.
How can I accomplish this?
you could use $rootScope to store shared data:
$scope.search_posts = function() {
if ( !angular.isUndefined($scope.searchText) && $scope.searchText.length > 2 ) {
$rootScope.searchTextFromTabOne = $scope.searchText;
$scope.searchText = '';
$scope.show_search_box = false;
$ionicTabsDelegate.select($ionicTabsDelegate.selectedIndex() + 1);
} else {
$ionicLoading.show({ template: 'You must write at least 3 characters long.', noBackdrop: false, duration: 2000 });
}
}
//in tab two's controller
$scope.searchText = $rootScope.searchTextFromTabOne;

Enforcing password policy in AEM

How to do I override the weak password policy in AEM6 SP2 and enforce a custom strict password policy for admin as well as non admin editors ?
Sreekanth wrote this in an blog Article "AEM 61 - Touch UI Add Simple Password Policy"
you can find it here:
http://experience-aem.blogspot.de/2015/09/aem-61-touch-ui-add-simple-password-policy.html
(function ($, $document) {
var ADMIN_PASSWORD_DIV = "#admin_password",
FIELD_CHANGE_PASSWORD = ".change-user-password", // change password form
FIELD_NEW_USER_PASSWORD = ".user-password-fields", //new user form
BUTTON_OK = ".user-admin-change-password", // change password form
BUTTON_SAVE = ".user-admin-save-user", //new user form
RE_TYPE_PASSWORD_FIELD = "[name='rep:re-password']";
var $policyText = $("<div/>").css('padding-bottom', '10px')
.css('font-style', 'italic')
.css('text-align', 'center')
.html('New Password must contain a number');
$(ADMIN_PASSWORD_DIV).find(".coral-Modal-body")
.prepend($policyText);
$(ADMIN_PASSWORD_DIV).find(RE_TYPE_PASSWORD_FIELD).focusout(focusHandler);
$(FIELD_NEW_USER_PASSWORD).find(RE_TYPE_PASSWORD_FIELD).focusout(focusHandler);
//change password form
$document.on("keyup", FIELD_CHANGE_PASSWORD, function(){
keyHandler($(FIELD_CHANGE_PASSWORD));
});
//new user form
$document.on("keyup.user-admin change.user-admin selected.user-admin", ".save-button-enabler", function(){
keyHandler( $(FIELD_NEW_USER_PASSWORD).find("[type=password]"));
});
function keyHandler($fields){
if(!$fields || $fields.length != 2){
return;
}
var one = $($fields[0]).val(), two = $($fields[1]).val();
if(isValidPassword(one) && isValidPassword(two) && (one == two)){
return;
}
$(BUTTON_OK).attr("disabled", "disabled"); // change password form
$(BUTTON_SAVE).attr("disabled", "disabled"); //new user form
}
function focusHandler(event){
clearErrors();
var val = $(event.currentTarget).val();
if(isValidPassword(val)){
return;
}
var message = "Password must contain a number";
showErrorAlert(message);
}
function clearErrors(){
$(BUTTON_OK).removeAttr("disabled"); // change password form
$(BUTTON_SAVE).removeAttr("disabled"); //new user form
}
function isValidPassword(text){
if(!text){
return true;
}
//check for number in text
return /\d/.test(text);
}
function showErrorAlert(message, title){
var fui = $(window).adaptTo("foundation-ui"),
options = [{
text: "OK",
warning: true
}];
title = title || "Error";
fui.prompt(title, message, "notice", options);
$(BUTTON_OK).attr("disabled", "disabled"); // change password form
$(BUTTON_SAVE).attr("disabled", "disabled"); //new user form
}})(jQuery, jQuery(document));

Titanium: can't switch tabs, close tabs, anything other than my current tab

Everything I try just does nothing, no errors, message, really anything. So I have three tabs, the first being a login tab, each tab has its own .js code, so for example, the login has its own login.js. Now, I use the httpClient to authenticate back to our website, and now want to remove the login tab and display the other tabs, cannot get it to work for the life of me, I can now remove the login tab but cannot load ay of the other tabs. Driving me nuts because I am finding 20 examples but they either don't separate the tabs into their own .js files or the example just plain doesn't work for me. Help! This seems so basic but yet...
app.js
// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');
// create tab group
var tabGroup = Titanium.UI.createTabGroup();
// create base UI tab and root window
//
var scan = Titanium.UI.createWindow({
title:'Scan',
backgroundColor:'#fff',
url:'scan.js',
mylabel:'Hello Scan'
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Scan',
window:scan
});
var login = Titanium.UI.createWindow({
title:'User Authentication',
tabBarHidden:true,
url:'login.js'
});
var loginTab = Titanium.UI.createTab({
title:"Login",
window:login
});
//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
title:'Manual',
backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
icon:'KS_nav_ui.png',
title:'Manual',
window:win2
});
var label2 = Titanium.UI.createLabel({
color:'#999',
text:'I am Manual Window ',
font:{fontSize:20,fontFamily:'Helvetica Neue'},
textAlign:'center',
width:'auto'
});
win2.add(label2);
//
// add tabs
//
tabGroup.addTab(loginTab);
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
// open tab group
tabGroup.open();
login.js
var win = Titanium.UI.currentWindow;
var tabGroup = Ti.UI.currentWindow.tabGroup;
var appUrl = "http://localhost:3001/ticket_agents/sign_in";
var email = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Email',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(email);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
var loginReq = Titanium.Network.createHTTPClient({
onload : function(e) {
var json = this.responseText;
var response = JSON.parse(json);
Ti.API.info("Received text: " + this.responseText);
if (response.id > 0)
{
alert("login Success");
win.tabGroup.close();
tabGroup.removeTab(loginTab);
tabGroup.setActiveTab(2);
tabGroup.open();
}
else
{
alert("Unknown login error");
}
},
onerror : function(e) {
var response = this.responseText;
Ti.API.debug(e.error);
alert('error: ' + this.responseText);
},
timeout : 5000
});
loginBtn.addEventListener('click',function(e)
{
if (email.value != '' && password.value != '')
{
loginReq.open("POST",appUrl);
var params = {ticket_agent: {email: email.value, password: password.value, remember_me: 0}
};
var authstr = 'Basic ' + Titanium.Utils.base64encode(email.value + ':' + password.value);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
loginReq.setRequestHeader('Authorization', authstr);
loginReq.send(JSON.stringify(params));
}
else
{
alert("Email/Password are required");
}
});
win.add(loginBtn);
I think that's all you'd need to see, the login.js has my latest attempt but I've tried things like tabGroup.open({url : 'app.js'}) and about three our four other option. Thanks.
You may want to add this eventListener to your app.js where the tabGroup is.
You can then fire a "app:gotoTab" event from anywhere.
app.js
Ti.App.addEventListener('app:gotoTab', function(e) {
tabGroup.setActiveTab(e.tab);
});
login.js
// tab index starts with 0, so 0 is your first tab
Ti.App.fireEvent('app:gotoTab', { tab: 0 });
Simply Copy paste this code
Login.js
var win = Titanium.UI.currentWindow;
var appUrl = "http://localhost:3001/ticket_agents/sign_in";
var email = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Email',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(email);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
var loginReq = Titanium.Network.createHTTPClient({
onload : function(e) {
var json = this.responseText;
var response = JSON.parse(json);
Ti.API.info("Received text: " + this.responseText);
if (response.id > 0)
{
alert("login Success");
tabGroup.setActiveTab(2);
}
else
{
alert("Unknown login error");
}
},
onerror : function(e) {
var response = this.responseText;
Ti.API.debug(e.error);
alert('error: ' + this.responseText);
},
timeout : 5000
});
loginBtn.addEventListener('click',function(e)
{
if (email.value != '' && password.value != '')
{
loginReq.open("POST",appUrl);
var params = {ticket_agent: {email: email.value, password: password.value, remember_me: 0}
};
var authstr = 'Basic ' + Titanium.Utils.base64encode(email.value + ':' + password.value);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
loginReq.setRequestHeader('Authorization', authstr);
loginReq.send(JSON.stringify(params));
}
else
{
alert("Email/Password are required");
}
});
win.add(loginBtn);
Hey Ross, You always remember window.close work on child Window perfectly.
In this application. You can use single Window base Application.
If, In First Window Login Successfully then, you can OPEN Second child Window.
for more details you can use KICHEN Shink Example. this is very useful for You.
You may want to redesign your UI. The Apple Human Interface Guidelines specifically say that you shouldn't programmatically switch tabs or add/remove tabs. They expect that a tabgroup should only be controlled by the user once you put it in front of them.
If the user needs to log in before they can use other features of your app you can present the a login window before the window with the tab group. Otherwise, you should replace the content of the login tab with something else after a successful login, perhaps with user profile information or some instructions.