Unable to display jquery alert from dojo template - dojo-1.9

I'm working with Dojo-1.9.1 and trying to build a templatized form for our application. I'm using noty to display an error alert when form validation fails. Invoking noty works when I directly use within the template like this:
<form data-dojo-attach-point="formNode" data-dojo-type="dijit/form/Form"
enctype="application/x-www-form-urlencoded" action=${submitUrl} method="post">
<script type="dojo/on" data-dojo-event="submit">
if(!this.validate()){
noty({
text: '${messages.invalidForm}',
type: 'error',
modal: true,
timeout: 2000, // false, to wait for user click
closeWith: ['click', 'hover'], // ['click', 'button', 'hover']
}); // works
return false;
}
return true;
</script>
<!-- other fields -->
</form>
However noty fails to show when created within onSubmit method like this:
<form data-dojo-attach-point="formNode" data-dojo-type="dijit/form/Form"
enctype="application/x-www-form-urlencoded" action=${submitUrl} method="post" data-dojo-attach-event="onSubmit:handleSubmit">
</form>
//Within the template.js
handleSubmit: function() {
if(!this.formNode.validate()) {
noty({text:...}); //fails to come up
return false;
}
return true;
}
dojoConfig:
// ... preceding dojo packages
{ name: "jquery", location: "lib", main: "jquery-1.10.2.min" },
{ name: "noty", location: "lib", main: "jquery.noty.packaged.min" }
It fails to come up in the console too. I guess I've correctly AMD'd the libraries since it works in the first instance. Could anyone please point out any missing links in my implementation. Thanks.

Answering my own question. I got this working by loading noty as a non-amd file:
//Within the template.js
define([..., 'resources/js/lib/jquery.noty.packaged.min.js'], function(...) {
handleSubmit: function() {
if(!this.formNode.validate()) {
noty({text:...}); //fails to come up
return false;
}
return true;
}
})

Related

Getting credit card brand and show error message when using hosted fields in Braintree

I am trying to create payment page using braintree's hosted fields.
I have created sandbox account.
But i am not getting additional details like Card brand, error message like Drop in UI.
How to get those functionalities using Hosted fields.
import React from 'react';
var braintree = require('braintree-web');
class BillingComponent extends React.Component {
constructor(props) {
super(props);
this.clientDidCreate = this.clientDidCreate.bind(this);
this.hostedFieldsDidCreate = this.hostedFieldsDidCreate.bind(this);
this.submitHandler = this.submitHandler.bind(this);
this.showPaymentPage = this.showPaymentPage.bind(this);
this.state = {
hostedFields: null,
errorOccurred: false,
};
}
componentDidCatch(error, info) {
this.setState({errorOccurred: true});
}
componentDidMount() {
this.showPaymentPage();
}
showPaymentPage() {
braintree.client.create({
authorization: 'sandbox_xxxxx_xxxxxxx'
}, this.clientDidCreate);
}
clientDidCreate(err, client) {
braintree.hostedFields.create({
onFieldEvent: function (event) {console.log(JSON.stringify(event))},
client: client,
styles: {
'input': {
'font-size': '16pt',
'color': '#020202'
},
'.number': {
'font-family': 'monospace'
},
'.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
'card-brand-id': true,
supportedCardBrands: 'visa'
},
cvv: {
selector: '#cvv',
type: 'password'
},
expirationDate: {
selector: '#expiration-date',
prefill: "12/21"
}
}
}, this.hostedFieldsDidCreate);
}
hostedFieldsDidCreate(err, hostedFields) {
let submitBtn = document.getElementById('my-submit');
this.setState({hostedFields: hostedFields});
submitBtn.addEventListener('click', this.submitHandler);
submitBtn.removeAttribute('disabled');
}
submitHandler(event) {
let submitBtn = document.getElementById('my-submit');
event.preventDefault();
submitBtn.setAttribute('disabled', 'disabled');
this.state.hostedFields.tokenize(
function (err, payload) {
if (err) {
submitBtn.removeAttribute('disabled');
console.error(err);
}
else {
let form = document.getElementById('my-sample-form');
form['payment_method_nonce'].value = payload.nonce;
alert(payload.nonce);
// form.submit();
}
});
}
render() {
return (
<div className="user-prelogin">
<div className="row gutter-reset">
<div className="col">
<div className="prelogin-container">
<form action="/" id="my-sample-form">
<input type="hidden" name="payment_method_nonce"/>
<label htmlFor="card-number">Card Number</label>
<div className="form-control" id="card-number"></div>
<label htmlFor="cvv">CVV</label>
<div className="form-control" id="cvv"></div>
<label htmlFor="expiration-date">Expiration Date</label>
<div className="form-control" id="expiration-date"></div>
<input id="my-submit" type="submit" value="Pay" disabled/>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default BillingComponent;
I am able to get basic functionalities like getting nonce from card details. But i am unable to display card brand image/error message in the page as we show in Drop in UI.
How to show card brand image and error message using hosted fields?
Page created using Hosted fields:
Page created Drop in UI - Which shows error message
Page created Drop in UI - Which shows card brand
Though we do not get exact UI like Drop in UI, we can get the card type and display it ourselves by using listeners on cardTypeChange.
hostedFieldsDidCreate(err, hostedFields) {
this.setState({hostedFields: hostedFields});
if (hostedFields !== undefined) {
hostedFields.on('cardTypeChange', this.cardTypeProcessor);
hostedFields.on('validityChange', this.cardValidator);
}
this.setState({load: false});
}
cardTypeProcessor(event) {
if (event.cards.length === 1) {
const cardType = event.cards[0].type;
this.setState({cardType: cardType});
} else {
this.setState({cardType: null});
}
}
cardValidator(event) {
const fieldName = event.emittedBy;
let field = event.fields[fieldName];
let validCard = this.state.validCard;
// Remove any previously applied error or warning classes
$(field.container).removeClass('is-valid');
$(field.container).removeClass('is-invalid');
if (field.isValid) {
validCard[fieldName] = true;
$(field.container).addClass('is-valid');
} else if (field.isPotentiallyValid) {
// skip adding classes if the field is
// not valid, but is potentially valid
} else {
$(field.container).addClass('is-invalid');
validCard[fieldName] = false;
}
this.setState({validCard: validCard});
}
Got the following response from braintree support team.
Hosted fields styling can be found in our developer documentation. Regarding the logos, you can download them from the card types official websites -
Mastercard
Visa
AMEX
Discover
JCB
Or online from other vendors.
Note: Drop-In UI will automatically fetch the brand logos and provide validation errors unlike hosted fields as it is less customizable.

Click event if element is checked and reload page

I would like a reload.location click-event only if a checkbox is checked. To me this seems to be basic conditions, but it's not working. Perhaps a different approach is needed? What I figured out, is when the checkbox is ticked, there is no html change in the <input type="checkbox"> element. Maybe this is the reason or is the combination of these conditions not possible? The else statement is a call back to the previous UI page. In below attempt, it's skipping the if-statement.
My attempt:
$(document.body).on("click", "#button", function(){
if (document.getElementById('checkbox').checked) {
location.reload(true);
} else {
return_to_page( this.dataset.return )
}
});
Above is working, however it's ignored due to the missing preventDefault:
$(document.body).on("click", "#button", function(e){
e.preventDefault();
//etc
});
checked is not a property of a jQuery object. You can use prop() to get the property instead:
$('#button').click( function() {
if ($('#checkbox').prop('checked')) {
location.reload(true);
}
// alternative #1 - use the 'checked' property of the Element in the jQuery object:
if ($('#checkbox')[0].checked) {
location.reload(true);
}
// alternative #2 - use the 'checked' property of the Element outside of jQuery:
if (document.getElementById('checkbox').checked) {
location.reload(true);
}
});
Here's a working example:
$('#button').click(function() {
if ($('#checkbox').prop('checked')) {
// location.reload(true);
console.log('Reload would happen now...');
} else {
console.log('Staying on the current page');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" id="checkbox" />
Reload?
</label>
<button id="button">Go</button>
$('#button').click( function() {
if( $("input[id='checkbox']:checked") ) {
location.reload(true);
}
});
alternative
$('#button').click( function() {
if( $('#checkbox').is(':checked') ) {
location.reload(true);
}
});
All in a one plate methods:
$('#checkbox').is(":checked")
$('#checkbox').prop('checked')
$('#checkbox')[0].checked
$('#checkbox').get(0).checked

Opencart if product available Button show else disable that button

Hi i'm creating a application using Opencart. It fully customized, i have doubt in this.
I have filter.tpl page, in this page i need to display and hide button based on product availability
Eg:
If product available show like this
enter image description here
else button show like this enter image description here
Am trying this fowling code using ajax
filter.tpl
$('input[name=\'filter_name\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/product/getProductCheck' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
label: item['name'],
value: item['product_id']
}
}));
}
});
},
'select': function(item) {
$('input[name=\'filter_name\']').val(item['label']);
}
});
In controller
product.php
public function getProductCheck()
{
/*Some code here*/
}
So you can use if ($product['quantity']) statement for example
I got the out put am using javascript following code
<div class="form-group">
<div style='display:none;' id='instock'>
<a class='instock-btn'>Product / Solution Available</a>
<input type='submit' class='btn-orng available' name='' value="Click here for more details" size='20' />
</div>
<div style='display:none;' id="outstock">
<input type='submit' class='outstock-btn' name='' value="Product / Solution Not Available" size='20' />
<input type='submit' class='btn-orng' name='' value="We will contact you at the earliest" size='20' />
</div>
</div>
script
$(document).ready(function(){
$('#dia1').on('change', function() {
//var value =
if (this.value <='320' )
{
$("#instock").show();
$("#outstock").hide();
}
else
{
$("#instock").hide();
$("#outstock").show();
}
});
$('#len1').on('change', function() {
//var value =
if (this.value <='310' )
{
$("#instock").show();
$("#outstock").hide();
}
else
{
$("#instock").hide();
$("#outstock").show();
}
});
});

Ember-rails: function returning 'undefined' for my computed value

Both functions here return 'undefined'. I can't figure out what's the problem.. It seems so straight-forward??
In the controller I set some properties to present the user with an empty textfield, to ensure they type in their own data.
Amber.ProductController = Ember.ObjectController.extend ({
quantity_property: "",
location_property: "",
employee_name_property: "",
//quantitySubtract: function() {
//return this.get('quantity') -= this.get('quantity_property');
//}.property('quantity', 'quantity_property')
quantitySubtract: Ember.computed('quantity', 'quantity_property', function() {
return this.get('quantity') - this.get('quantity_property');
});
});
Inn the route, both the employeeName and location is being set...
Amber.ProductsUpdateRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('product', params.product_id);
},
//This defines the actions that we want to expose to the template
actions: {
update: function() {
var product = this.get('currentModel');
var self = this; //ensures access to the transitionTo method inside the success (Promises) function
/* The first parameter to 'then' is the success handler where it transitions
to the list of products, and the second parameter is our failure handler:
A function that does nothing. */
product.set('employeeName', this.get('controller.employee_name_property'))
product.set('location', this.get('controller.location_property'))
product.set('quantity', this.get('controller.quantitySubtract()'))
product.save().then(
function() { self.transitionTo('products') },
function() { }
);
}
}
});
Nothing speciel in the handlebar
<h1>Produkt Forbrug</h1>
<form {{action "update" on="submit"}}>
...
<div>
<label>
Antal<br>
{{input type="text" value=quantity_property}}
</label>
{{#each error in errors.quantity}}
<p class="error">{{error.message}}</p>
{{/each}}
</div>
<button type="update">Save</button>
</form>
get rid of the ()
product.set('quantity', this.get('controller.quantitySubtract'))
And this way was fine:
quantitySubtract: function() {
return this.get('quantity') - this.get('quantity_property');
}.property('quantity', 'quantity_property')
Update:
Seeing your route, that controller wouldn't be applied to that route, it is just using a generic Ember.ObjectController.
Amber.ProductController would go to the Amber.ProductRoute
Amber.ProductUpdateController would go to the Amber.ProductUpdateRoute
If you want to reuse the controller for both routes just extend the product controller like so.
Amber.ProductController = Ember.ObjectController.extend ({
quantity_property: "",
location_property: "",
employee_name_property: "",
quantitySubtract: function() {
return this.get('quantity') - this.get('quantity_property');
}.property('quantity', 'quantity_property')
});
Amber.ProductUpdateController = Amber.ProductController.extend();
I ended up skipping the function and instead do this:
product.set('quantity',
this.get('controller.quantity') - this.get('controller.quantity_property'))
I still dont understand why I could not use that function.. I also tried to rename the controller.. but that was not the issue.. as mentioned before the other two values to fetches to the controller...
Anyways, thanks for trying to help me!

check url without http and ".com"

I would like to check if the given url is valid.
It should accept:
www.gmail.com
and should reject:
www.gmail
I tried using this /((ftp|http|https):\/\/)?(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
It works but if the given input is www.gmail it does accepts it.
Any Ideas?
UPDATE
http://jsfiddle.net/aabanaag/VktaX/
You could use Jquery Validate plugin for that.
$("#myform").validate({
rules: {
field: {
required: true,
url: true
}
}
});
You can find about it here
try this .It is working for me
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
In jQuery
you can use url validation
<input type="text" class="url"/>
solved my problem:
found this while googling over the internet.
/^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/
var pattern1 = /^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/;
var result = "www.gmail";
if (pattern1.test(result)) {
console.log("test");
}else{
console.log("fail");
}
It works best.