I need to put the return of the function validarCartao()
into that HiddenField value. The alert(response.brand.name)
works fine but I cant get this, even if I move the HiddenField to inside the function. I've tried lots of ways but nothing works. I really appreciate any help you can provide. Thanks.
var hiddenBandeiraTemp = document.getElementById('<%=hiddenBandeira.ClientID%>');
hiddenBandeiraTemp.value = validarCartao(tbNumeroCartao.value);
function validarCartao(element) {
var cardNum = element.replace(/[^\d.]/g, '');
var card_invalid = 'Número do cartão inválido.';
if (cardNum.length >= 6) {
PagSeguroDirectPayment.getBrand({
cardBin: cardNum.substr(0, 6),
success: function (response) {
if (typeof response.brand.name != 'undefined') {
alert(response.brand.name); // OK
return response.brand.name; // <<--
} else {
alert(card_invalid);
}
},
error: function (response) {
alert(card_invalid);
}
});
}
}
The return
statement that you put inside the success
callback will return a value for the function success()
not for the function validarCartao()
success: function (response) {
if (typeof response.brand.name != 'undefined') {
alert(response.brand.name); // OK
return response.brand.name; // <<--
} else {
alert(card_invalid);
}
}
Moreover, as the function PagSeguroDirectPayment.getBrand()
seems to be asynchronous, it is impossible to return its value inside validarCartao()
. In my opinion, this would be a better solution:
var hiddenCompradorIdTemp = document.getElementById('<%=hiddenCompradorId.ClientID%>');
validarCartao(tbNumeroCartao.value);
function validarCartao(element) {
var cardNum = element.replace(/[^\d.]/g, '');
var card_invalid = 'Número do cartão inválido.';
if (cardNum.length >= 6) {
PagSeguroDirectPayment.getBrand({
cardBin: cardNum.substr(0, 6),
success: function (response) {
if (typeof response.brand.name != 'undefined') {
alert(response.brand.name); // OK
hiddenBandeiraTemp.value = response.brand.name;
} else {
alert(card_invalid);
}
},
error: function (response) {
alert(card_invalid);
}
});
}
}