How to Disable this save/submit button? - javascript

I am wondering what is the best method to disable this save button after one click?
Here is the code :
<button data-bind="enable: !$root.isSaving(), click: $root.addNewCard.bind($data, $root)" class="primary button" role="button" data-size="sm">
Save
</button>
Above is the .cshtml code
Below is the javascript code:
BillingInformation.prototype.addNewCard = function (parent, creditCard) {
parent.isSaving(true);
parent.isSettingDefault(true);
creditCard.cardNumber(creditCard.cardNumber().replace(/-|\s/g, ''));
let $form = $('#addNewCardForm' + creditCard.walletItemId()),
cardNumber = creditCard.cardNumber();
parseDynamicFormElements($form);
if ($form.valid()) {
verifyAddress($form, function () {
authentication.checkReAuthenticatedThenLaunchLoginOrExecuteTask(() => {
creditCard
.save()
.then(response => {
if (response.status === HTTP_STATUS_OK) {
creditCard.walletItemId(response.content);
parent.walletItems.push(creditCard);
creditCard.lastFourDigits(
creditCard.cardNumber() ? creditCard.cardNumber().substr(-4) : ''
);
creditCard.obfuscatedCardNumber(cardNumber.replace(/.(?=.{4})/g, '*'));
parent.newCardInstance(new CreditCard({paymentType: 'creditCards'}));
checkForRedirect();
} else {
let container = document.createElement('div');
container.append(
'We were unable to save your payment information. Please try again or give us a call at 1-800-461-8898'
);
smartPak.ui.modal(container, {
title: 'Unable to Save Payment Method',
buttons: {
Close: function (modal) {
modal.close();
}
}
});
}
})
.then(() => {
parent.isSaving(false);
});
});
});
parent.isSaving(false);
} else {
parent.isSaving(false);
parent.isSettingDefault(false);
}
};
What is the best method to prevent this from being clicked more than once after submission? currently if clicked multiple times it will duplicate the cc.
Thank you!

Maybe the the enable property should bind to a variable, not a function like you do in
enable: !$root.isSaving()

did you try switching click:
$root.addNewCard.bind($data, $root) to click: $root.addNewCard.bind($root, $data) ?
according to your declaration:
BillingInformation.prototype.addNewCard = function (parent, creditCard)
creditCard = $data from the form and parent = $root ?

Related

how to return created attribute in javascript

I'm having trouble retrieving data from a data-tag attribute on a button that is created by createElement
chatbot.js
const selectServiciosMoviles = document.querySelector('#selectServiciosMoviles')
const addSelect = (select, id, datatag) => {
const selection = document.createElement('button')
selection.classList.add('chatbot__selection')
selection.id = id
selection.setAttribute("data-tag", datatag)
selection.innerHTML = select
messageArea.appendChild(selection)
scrollToBottom(messageArea)
}
selectServiciosMoviles.addEventListener('click', () => {
setTimeout(() => {
addSelect('Portabilidad', 'selectPortabilidad', '{"categoria":"chatbot", "nombre":"chatbot","ubicacion":"home_b2b", "accion":"seleccionar", "etiqueta":"subcategoria_portabilidad"}')
addSelect('Planes Moviles', 'selectMoviles', '{"categoria":"chatbot", "nombre":"chatbot","ubicacion":"home_b2b", "accion":"seleccionar", "etiqueta":"subcategoria_planes_moviles"}')
addSelect('Roaming', 'selectRoaming', '{"categoria":"chatbot", "nombre":"chatbot","ubicacion":"home_b2b", "accion":"seleccionar", "etiqueta":"subcategoria_roaming"}')
addSelect('Seguro Movil', 'selectSeguros', '{"categoria":"chatbot", "nombre":"chatbot","ubicacion":"home_b2b", "accion":"seleccionar", "etiqueta":"subcategoria_seguro_movil"}')
scrollToBottom()
}, 2000)
});
html
<button class="chatbot__selection" id="selectPortabilidad" data-tag="{"categoria":"chatbot", "nombre","chatbot", "ubicacion":"home_b2b", "accion":"seleccionar","etiqueta":"subcategoria_portabilidad"}">Portabilidad</button>
<button class="chatbot__selection" id="selectMoviles" data-tag="{"categoria":"chatbot", "nombre","chatbot", "ubicacion":"home_b2b", "accion":"seleccionar","etiqueta":"subcategoria_portabilidad"}">Planes Moviles</button>
<button class="chatbot__selection" id="selectRoaming" data-tag="{"categoria":"chatbot", "nombre","chatbot", "ubicacion":"home_b2b", "accion":"seleccionar","etiqueta":"subcategoria_portabilidad"}">Roaming</button>
<button class="chatbot__selection" id="selectSeguros" data-tag="{"categoria":"chatbot", "nombre","chatbot", "ubicacion":"home_b2b", "accion":"seleccionar","etiqueta":"subcategoria_portabilidad"}">Seguro Movil</button>
libreria.js
var tagItems = document.querySelectorAll('[data-tag]')
tagItems.forEach(function (e) {
e.addEventListener('click', function (e) {
if(e.target.dataset.tag != undefined){
var data = JSON.parse(e.target.dataset.tag)
console.log(data)
}
})
})
the problem when seeing the console nothing appears to me, the data-tag of the button does not rescue me. please i need help, thanks

Button within modal's table not firing [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
Attempted to put a delete button that works in a table into a modal, with a table and it's like the click event is not firing at all. Hit's not back end code, no console.log(s), or js break points. Am I missing something?
Modal's Table
<table class="table table-hover table-md ">
<thead>
<tr>
<td class="text-left TableHead">Role</td>
<td class="text-right TableHead">Delete</td>
</tr>
</thead>
#*--Table Body For Each to pull DB records--*#
<tbody>
#foreach (var role in Model.Roles)
{
<tr>
<td>#role</td>
<td>
<button class="sqButton btnRed float-right zIndex"
title="Delete" data-toggle="ajax-modal" data-target="#deleteRoleUser"
data-url="#Url.Action("Delete", "Administration",
new {Id = Model.Id , Type = "roleUser"})" >
<i class="glyphicon glyphicon-remove"></i>
</button>
</td>
</tr>
}
</tbody>
</table>
Controller that it's supposed to call
[HttpGet]
public async Task<IActionResult> Delete(string id, string type)
{
if (type == "user") {
ViewBag.Type = "user";
var user = await userManager.FindByIdAsync(id);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
return View("NotFound");
}
var model = new EditUserViewModel
{
Id = user.Id,
UserName = user.UserName,
};
ViewBag.UN = user.UserName;
return PartialView("~/Views/Modals/_DeleteModalPartial.cshtml", model);
}
if (type == "roleUser")
{
ViewBag.Type = "roleUser";
var role = await roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
return View("NotFound");
}
var model = new EditRoleViewModel
{
Id = role.Id,
RoleName = role.Name,
};
ViewBag.Role = role.Name;
return PartialView("~/Views/Modals/_DeleteModalPartial.cshtml", model);
}
else
{
ViewBag.ErrorMessage = $"cannot be found";
return View("NotFound");
}
}
I am not sure why the click event on the button is not working at all. I have tried removing random code and literally nothing is making it go over to the controller at the least.
EDIT added javascript
$(function () {
var placeholderElement = $('#modal-placeholder');
$('[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
});
$('.sqButton').click( function (event) {
event.stopPropagation();
});
Since the button doesn't exist on page load you will have to create a event delegate to something that does exist on page load that will attach the event to the right element when it finally does appear in the DOM
In this case we will use the document (because it always exists on page load, some people use 'body') to delegate the event to the [data-toggle="ajax-modal"], like this:
$(document).on('click', '[data-toggle="ajax-modal"]', function (event) {
// code here
});
This will attach the event to the [data-toggle="ajax-modal"] elements on page load AND after page load if the element gets added later.
Try replacing your javascript code
$('.sqButton').click( function (event) {
event.stopPropagation();
});
With the following code
$('.sqButton').click(function(event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
if you manually force click, does it hit your controller?
document.querySelector('.btnRed').click();
is there any other element(s) "hijacking" click event?

cannot change language of text based on localStorage at button click

I made buttons to switch language of data on click based on localStorage language item value, but it does not work as expected
HTML:
<a id="arbutton" href="#ar">arabic</a>
<a id="enbutton" href="#en">english</a>
<a id="" href="localStorage1.html">page</a>
<!-- data here will change -->
<div id="hello">yes language</div>
JS:
var creatbtnAr = document.querySelector('#arbutton');
var creatbtnEn = document.querySelector('#enbutton');
// button language arabic
creatbtnAr.addEventListener('click', event => {
localStorage.setItem("language", "ar");
console.log(localStorage.language);
});
// button language english
creatbtnEn.addEventListener('click', event => {
localStorage.setItem("language", "en");
console.log(localStorage.language);
});
// methods
var lg = localStorage.getItem.language;
function translate(lg) {
if(lg == 'ar') {
document.querySelector('#hello').textContent = 'u arabic';
}
if(lg == 'en') {
document.querySelector('#hello').textContent = 'u english';
}
}
https://codepen.io/pen/?editors=1111
Try this:
var creatbtnAr = document.querySelector('#arbutton');
var creatbtnEn = document.querySelector('#enbutton');
// button language arabic
creatbtnAr.addEventListener('click', event => {
localStorage.setItem("language", "ar");
console.log(localStorage.language);
translate();
});
// button language english
creatbtnEn.addEventListener('click', event => {
localStorage.setItem("language", "en");
console.log(localStorage.language);
translate();
});
// methods
function translate() {
const lg = localStorage.getItem("language");
if(lg == 'ar') {
document.querySelector('#hello').textContent = 'u arabic';
}
if(lg == 'en') {
document.querySelector('#hello').textContent = 'u english';
}
}

Jquery collection plugin for symfony not working

Since I've put together all of my Javascript and jQuery file, the Jquery plugin collection for Symfony didn't work. I don't know why but when I click on the add button, nothing happen ...
Here is my jQuery code :
var indexAdd = 0
var collectionToAdd ='';
jQuery('.my-selector').collection({
allow_up: false,
allow_add: true,
allow_down: false,
after_remove: function(collection, element) {
indexAdd--;
var count = 0;
jQuery(collection).children().each(function(){
if(jQuery(this).is('div')){
count++;
}
})
if(count > 1){
jQuery(element).find("a.collection-add.collection-action").eq(indexAdd-1).parent().show();
}
if(count == 0){
jQuery(collection).find('a.collection-action.collection-rescue-add').css('display','unset');
}
},
after_add: function(collection, element) {
jQuery(element).css('margin-top','50px');
indexAdd++;
collectionToAdd = '';
collectionToAdd = collection;
jQuery('#modalCollection .modal-body .col-6').empty()
var nomCollection = jQuery(jQuery(collection).parent()).parent().find('label').eq(0).text()
if(jQuery('#modalCollection .modal-body .col-6 h1').length == 0){
jQuery('#modalCollection .modal-body .col-6').append('<h1>'+nomCollection+'</h1>')
}
jQuery('#modalCollection .modal-body .col-6').append('<div class="detach"></div>')
jQuery('#modalCollection').modal('show');
jQuery(jQuery(element).detach()).appendTo('#modalCollection .modal-body .detach')
jQuery(element).parent().children("div").each(function(){
jQuery(this).children("label").css('display','none')
})
jQuery(element).find('label').each(function(event){
if(jQuery(this).text().indexOf('label') > 0){
jQuery(this).hide();
}
})
newCollection = jQuery(element).parent().find("div:last").parent()
jQuery(newCollection).find("div").wrap('<td></td>')
jQuery(newCollection).find("div").each(function(){
jQuery(this).find("td").wrapAll(('<tr></tr>'))
if(jQuery(this).find("label")){
label = jQuery(this).find("label").attr("for")
if(typeof label !== 'undefined'){
label = (label.substring(0, String(label).indexOf('-'))).substring(label.lastIndexOf("_")+1)
jQuery(this).find("label").html(label)
}
}
})
jQuery(element).find('td').each(function(){
jQuery(this).find('div').attr("class","md-form")
jQuery(this).find('div').each(function(){
if(jQuery(this).find('input').attr('type') == 'file'){
jQuery(this).find('label').hide();
}
})
})
}
})
Here is the form view : formView
That's how I create my CollectionType :
$builder->add($key, CollectionType::class, array(
'entry_type' => DynamicFormType::class,
'entry_options' => array('data' => $arrayOfFieldType),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'attr' => array(
'class' => 'my-selector',
),));
When i clicked on the add button (in blue) nothing happen.
If someone have an idea, will be great to know.
Thanks in advance.
Problem solved. I just add to add a my-selector class that was deleted i dont know how but everything is working now.

I would like to show an error message after a user clicks on a save button if the URL they entered was invalid. Using Angular JS

I would like to show an error message AFTER a user clicks on a save button. The field that they need to complete is a URL link and it must be a valid url.. I have a working regex in place, I just have no clue how this is supposed to be done as I am very new to angular.
Here is what I have so far:
<div class="form-group">
<button type="button" class="btn btn-primary btn-block btn-lg"
ng-click="save()">
<spring:message code="journalist.social.submit.label"/>
<span class="glyphicon glyphicon-chevron-right"</span>
</button>
<span style="color: #d2232a;padding-left: 0px" class="btn"
ng-show="!canSave()">
<spring:message code="journalist.info.error.fill.all"/>
</span>
And in my scripts (The save button only works if the canSave function is true):
$scope.save = function () {
var res = [];
var files = [];
var ind = 0;
if ($scope.canSave()){ //save button should only work if the URL is valid
$scope.linkList.forEach(function (clip) {
if (!clip.link) {
return;
}
if (!CommonUtils.startsWithHttp(clip.link)) {
clip.link = CommonUtils.EMPTY_LINK + clip.link;
}
if (clip.imgData && clip.imgData.input) {
files.push({id: ind, file: clip.imgData.input, cropData: clip.imgData.cropData})
clip.logos = undefined;
}
ind = ind + 1;
res.push({
id: clip.id,
title: clip.title,
description: clip.description,
name: clip.name,
link: clip.link,
ordering: ind,
logoUrl: clip.logos ? clip.logos[clip.logoInd] : null
})
});
Journalist.updateClips(
files,
res,
$scope,
function (e) {
$scope.warningOnLocationChange = false;
Navigation.open($scope, ["journalist", "profile", "profile"]);
}
);
};
$scope.showUpload = function (clip) {
if(clip.link) {
clip.showUpload = true;
}
};
}}]
);
If you think the condition I have in my script for the save() function is not right then by all means tell me otherwise. How can I show an alert after the button is clicked? The alert shows before a URL is even entered (or as they are typing and will go away once the url is correct.) Thanks!

Categories