How to Write Knockout Js Code. Magento 2
-
14-03-2021 - |
Domanda
I'm trying to Hide 3 Radio Buttons when Checkbox is unchecked when I checked it the all 3 buttons need to show in Jquery the code will be like
show_hide_fun: function(){
window.alert("Nadeem is running1");
$("#custom_jazz_s").hide();
$("#custom_jazz_m").hide();
$("#custom_jazz_c").hide();
$("#show_hide_jazz").click(function(){
if($("#show_hide_jazz").attr('checked'))
{window.alert("Nadeem is running2");
$("#custom_jazz_s").show();
$("#custom_jazz_m").show();
$("#custom_jazz_c").show();
}else{window.alert("Nadeem is running3");
$("#custom_jazz_s").hide();
$("#custom_jazz_m").hide();
$("#custom_jazz_c").hide();
}
});
},
list.html
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<h2>Pakistan</h2>
<div class="myJazz"><label for="show_hide_jazz">
<input type="radio" name="payment[method]" id="show_hide_jazz" data-bind="event: { click: myFunction }"> JazzCash</label>
</div>
<div if="isPaymentMethodsAvailable()"
class="items payment-methods">
<div repeat="foreach: paymentGroupsList, item: '$group'"
class="payment-group">
<div if="getRegion($group().displayArea)().length"
translate="getGroupTitle($group)"
class="step-title"
data-role="title">
</div>
<each args="data: getRegion($group().displayArea), as: 'method'" render=""/>
<h2>Testing</h2>
</div>
<div ifnot="isPaymentMethodsAvailable()"
class="no-payments-block"
translate="'No Payment Methods'">
</div>
and the other Id's I mentioned in my Jquery code is coming from other html
file
JazzCashS/view/web/template/payment/form.html
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div class="payment-method" id="custom_jazz_s" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice">
<input type="radio" name="payment[method]" class="radio" data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()" />
<label class="label" data-bind="attr: {'for': getCode()}">
<img src="https://lh3.googleusercontent.com/-KR3uhnuU3qo/W4fpRKRGM0I/AAAAAAAAAFc/cmogQ-czRIcsQTkDwR-ZanDT--s6SC3HQCL0BGAYYCw/h50/2018-08-30.png"
alt="JazzCash Shop" width="100px" height="50px"
/>
<span data-bind="text: getTitle()"></span>
</label>
</div>
<div class="payment-method-content">
<!-- ko foreach: getRegion('messages') -->
<!-- ko template: getTemplate() -->
<!-- /ko -->
<!--/ko-->
<p>
JazzCash Shop is an easy payment solution.<br /> Click "Place Order" and your JazzCash voucher number will be generated and displayed on your screen<br /> You can visit any JazzCash shop and pay against your token within 24 hours.<br /> To
see the list of JazzCash shop locations, <a href="http://www.jazzcash.com.pk/agent-locator/">Click Here</a><br /> You are almost done!<br /> To change or edit your order, go back. No changes will be allowed once you click "Place Order".<br
/>
</p><br><br>
<div class="actions-toolbar">
<div class="primary">
<!-- --><button class="action primary checkout" type="submit" data-bind="
click: placeOrder,
attr: {title: $t('Place Order')}">
<span data-bind="i18n: 'Place Order'"></span>
</button>
</div>
</div>
</div>
</div>
JazzCashC/view/web/template/payment/form.html
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div class="payment-method" id="custom_jazz_c" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice">
<input type="radio" name="payment[method]" class="radio" data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()" />
<label class="label" data-bind="attr: {'for': getCode()}">
<!-- <img src="https://lh3.googleusercontent.com/-t8IBL-2jMOY/W4T5YR_HaHI/AAAAAAAAAFA/x68pD0gVP-EnMXqDkuBg6v9UPlk6RkcoACL0BGAYYCw/h512/2018-08-28.png"
alt="Jazz Cash Credit Card" width="50px" height="50px" /> -->
<img src="https://lh3.googleusercontent.com/-gqE4diqupEc/W4fpQTpyfnI/AAAAAAAAAFc/ccVFkANPyrgcVU1W-VAzMb-E6A7d7MDVgCL0BGAYYCw/h50/2018-08-30.png" alt="Jazz Cash Credit Card" width="100px" height="50px" />
<span data-bind="text: getTitle()"></span>
</label>
</div>
<div class="payment-method-content">
<!-- ko foreach: getRegion('messages') -->
<!-- ko template: getTemplate() -->
<!-- /ko -->
<!--/ko-->
<p>
Any local or international Visa/Mastercard Credit or Debit Card holder can pay online.<br /> Please make sure your card is activated for online shopping.<br /> You are almost done!<br /> To change or edit your order, go back. No changes will
be allowed once you click "Place Order".<br />
</p><br><br>
<div class="actions-toolbar">
<div class="primary">
<button class="action primary checkout" type="submit" data-bind="
click: placeOrder,
attr: {title: $t('Place Order')}">
<span data-bind="i18n: 'Place Order'"></span>
</button>
</div>
</div>
</div>
</div>
JazzCashM/view/web/template/payment/form.html
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<div class="payment-method" id="custom_jazz_m" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice">
<input type="radio" name="payment[method]" class="radio" data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()" />
<label class="label" data-bind="attr: {'for': getCode()}">
<img src="https://lh3.googleusercontent.com/-oBKXNWhW9lY/W4fpR3i6tII/AAAAAAAAAFc/_KAo2ntBFTMuSfaNEhTqiD7gtoLO9tE4QCL0BGAYYCw/h50/2018-08-30.png" alt="JazzCash Mobile Account" width="100px" height="50px" />
<span data-bind="text: getTitle()"></span>
</label>
</div>
<div class="payment-method-content">
<!-- ko foreach: getRegion('messages') -->
<!-- ko template: getTemplate() -->
<!-- /ko -->
<!--/ko-->
<p>
JazzCash Mobile Account can be registered on any Jazz or Warid number<br /> Biometric-verified Jazz and Warid customers can self-register their Mobile Account simply by dialing *786#.<br /> Enter the confirmation code within 30 seconds to
make a successful payment!<br /> You are almost done!<br /> To change or edit your order, go back. No changes will be allowed once you click "Place Order".<br />
</p><br><br>
<div class="actions-toolbar">
<div class="primary">
<!-- --><button class="action primary checkout" type="submit" data-bind="
click: placeOrder,
attr: {title: $t('Place Order')}">
<span data-bind="i18n: 'Place Order'"></span>
</button>
</div>
</div>
</div>
</div>
When I add this code in my list.js
file then it gives me many errors because this is a Jquery code how can I write the above code in knockoutjs like when #show_hide_jazz
is unclicked then #custom_jazz_s
, #custom_jazz_m
and #custom_jazz_c
needs to be hidden n when I clicked on #show_hide_jazz
then it need to be shown...
Soluzione
Folder path:
Vendor/Module/view/frontend/web/js/view/payment/list.js
Added customChange function.
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'underscore',
'ko',
'mageUtils',
'uiComponent',
'Magento_Checkout/js/model/payment/method-list',
'Magento_Checkout/js/model/payment/renderer-list',
'uiLayout',
'Magento_Checkout/js/model/checkout-data-resolver',
'mage/translate',
'uiRegistry'
], function ($, _, ko, utils, Component, paymentMethods, rendererList, layout, checkoutDataResolver, $t, registry) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendor_Module/payment-methods/list',
visible: paymentMethods().length > 0,
configDefaultGroup: {
name: 'methodGroup',
component: 'Magento_Checkout/js/model/payment/method-group'
},
paymentGroupsList: [],
defaultGroupTitle: $t('Select a new payment method')
},
/**
* Initialize view.
*
* @returns {Component} Chainable.
*/
initialize: function () {
this._super().initDefaulGroup().initChildren();
paymentMethods.subscribe(
function (changes) {
checkoutDataResolver.resolvePaymentMethod();
//remove renderer for "deleted" payment methods
_.each(changes, function (change) {
if (change.status === 'deleted') {
this.removeRenderer(change.value.method);
}
}, this);
//add renderer for "added" payment methods
_.each(changes, function (change) {
if (change.status === 'added') {
this.createRenderer(change.value);
}
}, this);
}, this, 'arrayChange');
return this;
},
/** @inheritdoc */
initObservable: function () {
this._super().
observe(['paymentGroupsList']);
return this;
},
/**
* Creates default group
*
* @returns {Component} Chainable.
*/
initDefaulGroup: function () {
layout([
this.configDefaultGroup
]);
return this;
},
/**
* Create renders for child payment methods.
*
* @returns {Component} Chainable.
*/
initChildren: function () {
var self = this;
_.each(paymentMethods(), function (paymentMethodData) {
self.createRenderer(paymentMethodData);
});
return this;
},
/**
* @returns
*/
createComponent: function (payment) {
var rendererTemplate,
rendererComponent,
templateData;
templateData = {
parentName: this.name,
name: payment.name
};
rendererTemplate = {
parent: '${ $.$data.parentName }',
name: '${ $.$data.name }',
displayArea: payment.displayArea,
component: payment.component
};
rendererComponent = utils.template(rendererTemplate, templateData);
utils.extend(rendererComponent, {
item: payment.item,
config: payment.config
});
return rendererComponent;
},
/**
* Create renderer.
*
* @param {Object} paymentMethodData
*/
createRenderer: function (paymentMethodData) {
var isRendererForMethod = false,
currentGroup;
registry.get(this.configDefaultGroup.name, function (defaultGroup) {
_.each(rendererList(), function (renderer) {
if (renderer.hasOwnProperty('typeComparatorCallback') &&
typeof renderer.typeComparatorCallback == 'function'
) {
isRendererForMethod = renderer.typeComparatorCallback(renderer.type, paymentMethodData.method);
} else {
isRendererForMethod = renderer.type === paymentMethodData.method;
}
if (isRendererForMethod) {
currentGroup = renderer.group ? renderer.group : defaultGroup;
this.collectPaymentGroups(currentGroup);
layout([
this.createComponent(
{
config: renderer.config,
component: renderer.component,
name: renderer.type,
method: paymentMethodData.method,
item: paymentMethodData,
displayArea: currentGroup.displayArea
}
)]);
}
}.bind(this));
}.bind(this));
},
/**
* Collects unique groups of available payment methods
*
* @param {Object} group
*/
collectPaymentGroups: function (group) {
var groupsList = this.paymentGroupsList(),
isGroupExists = _.some(groupsList, function (existsGroup) {
return existsGroup.alias === group.alias;
});
if (!isGroupExists) {
groupsList.push(group);
groupsList = _.sortBy(groupsList, function (existsGroup) {
return existsGroup.sortOrder;
});
this.paymentGroupsList(groupsList);
}
},
/**
* Returns payment group title
*
* @param {Object} group
* @returns {String}
*/
getGroupTitle: function (group) {
var title = group().title;
if (group().isDefault() && this.paymentGroupsList().length > 1) {
title = this.defaultGroupTitle;
}
return title + ':';
},
/**
* Checks if at least one payment method available
*
* @returns {String}
*/
isPaymentMethodsAvailable: function () {
return _.some(this.paymentGroupsList(), function (group) {
return this.getRegion(group.displayArea)().length;
}, this);
},
/**
* Remove view renderer.
*
* @param {String} paymentMethodCode
*/
removeRenderer: function (paymentMethodCode) {
var items;
_.each(this.paymentGroupsList(), function (group) {
items = this.getRegion(group.displayArea);
_.find(items(), function (value) {
if (value.item.method.indexOf(paymentMethodCode) === 0) {
value.disposeSubscriptions();
value.destroy();
}
});
}, this);
},
customChange: function () {
if( $("#show_hide_jazz").attr('checked') ) {
$("#custom_jazz_s").show();
$("#custom_jazz_m").show();
$("#custom_jazz_c").show();
} else {
$("#custom_jazz_s").hide();
$("#custom_jazz_m").hide();
$("#custom_jazz_c").hide();
}
}
});
});
Vendor/Module/view/frontend/web/template/payment-methods/list.html
Added customChange as change event
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<h2>Pakistan</h2>
<div class="myJazz"><label for="show_hide_jazz">
<input type="radio" name="payment[method]" id="show_hide_jazz" data-bind="event: { change: customChange }"> JazzCash</label>
</div>
<div if="isPaymentMethodsAvailable()"
class="items payment-methods">
<div repeat="foreach: paymentGroupsList, item: '$group'"
class="payment-group">
<div if="getRegion($group().displayArea)().length"
translate="getGroupTitle($group)"
class="step-title"
data-role="title">
</div>
<each args="data: getRegion($group().displayArea), as: 'method'" render=""/>
<h2>Testing</h2>
</div>
<div ifnot="isPaymentMethodsAvailable()"
class="no-payments-block"
translate="'No Payment Methods'">
</div>
Run below comment
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f