JavaScript form onchange getting Nan - javascript

I am calling onchange event on form but when I checked in console values are coming in Nan
HTML
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
JavaScript
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($(e.target).find('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($(e.target).find('#admin-percent').val());
console.log(adminPercent);
const province = $(e.target).find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
Where I did wrong code?

Please use e.currentTarget instead of e.target because e.target can be your text fields but e.currentTarget will always be your form. This code is working fine.
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
<script>
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($(e.currentTarget).find('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($(e.currentTarget).find('#admin-percent').val());
console.log(adminPercent);
const province = $(e.currentTarget).find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
</script>

There's no need to use e.target in your example. You can just access the values from the selectors directly:
function calculateHSA(e) {
e.preventDefault();
const claimAmount = parseInt($('#claim-amnt').val());
console.log(claimAmount);
const adminPercent = parseInt($('#admin-percent').val());
console.log(adminPercent);
const province = parseInt($('#province').val());
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onchange="calculateHSA(event)">
<div class="col-sm-4">
<input type="number" name="claim-amnt" id="claim-amnt" required="">
</div>
<div class="col-sm-4">
<input type="number" name="admin-percent" id="admin-percent" required="">
</div>
<div class="col-sm-4">
<span class="dataText">Select your province
</span><br>
<select name="province" id="province">
<option value="abc">ABC</option>
</select>
</div>
</form>
Note that you will get NaN in the console for any field that doesn't have a value that can be parsed as an integer. So if you leave the field blank, you're still going to get NaN in the console.

You are getting NaN because your target element is pointing to the input tag instead of form element
I have made some changes in the function and added new line in the code
function calculateHSA(e) {
e.preventDefault();
var form = $(e.target).parent().parent(); // <-- get the form element
const claimAmount = form.find('#claim-amnt').val();
console.log(claimAmount);
const adminPercent = form.find('#admin-percent').val();
console.log(adminPercent);
const province = form.find('#province').val();
console.log(province);
displayTaxDetails(claimAmount, adminPercent, province);
}
have a look at this plunker https://plnkr.co/edit/BQ538zbYBk857zT1wAgT

Related

Select Option Doesn't Set on Button Click with jQuery

I've tried following a couple of answers with no success. I am trying to get the select box to go back to the "Please Select One Option" when the Add Exercise button is clicked. I got it to work in a simple scenario like this:
<div id="retro_add_exercises">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized">
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise from cardio</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#add_exercise_from_cardio').click(function() {
$('#exercise_category').val('0').change();
});
});
</script>
But in my main project, it isn't working when I have the row show and hide on button click too. Any help would be appreciated.
$(document).ready(function() {
$('#retroactive_date_form').submit(function(e) {
e.preventDefault();
var date = $('#retroactive_date_picker');
var exercise_date = date.val();
if (exercise_date !== '') {
var exercise_category;
var weight_set_type;
console.log(exercise_date);
date.prop('disabled', true);
$('#retroactive_date_submit').addClass('disabled');
$('#retro_add_exercises').show();
//Exercise Category Function
$('#exercise_category').on('change', function() {
exercise_category = $('#exercise_category').val();
console.log(exercise_category);
if (this.value === '1')
{
$('#select_cardio').show();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_cardio').hide();
if (this.value === '2')
{
$('#select_weight').show()
}
else
$('#select_weight').hide();
if (this.value === '3')
{
$('#select_stretch_fields').show();
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#select_weight').hide();
$('#drop_or_reg_set_table_row').hide();
}
else
$('#select_stretch_fields').hide();
return exercise_category;
});
///////////Cardio Training Functions///////////////
//Selecting Cardio Exercise
$('#cardio_exercise').on('change', function (e) {
var cardio_exercise;
cardio_exercise = $('#cardio_exercise').val();
console.log(cardio_exercise);
});
//Adding Another Exercise After Done Adding Current Cardio Exercise
$('#add_exercise_from_cardio').on('click', function(e) {
e.preventDefault();
$('#exercise_category option[value="0"]').attr('selected', true);
$('#select_cardio').hide();
$('#drop_or_reg_set_select_exercise').hide();
$('#super_set_select_exercises').hide();
$('#drop_and_regular_set_action_btn').hide();
$('#super_set_action_btn').hide();
$('#super_set_table_row').hide();
$('#drop_or_reg_set_table_row').hide();
});
//Error Handling If No Date is Selected Before Starting
else {
alert('Please select date')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="retro_add_exercises" style="display:none">
<div class="row">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select class="initialized" id="exercise_category">
<option value="0" disabled="" selected="">Please Select One</option>
<option value="1">Cardio</option>
<option value="2">Weight Lifting</option>
<option value="3">Stretching</option>
</select>
</div>
<label>Choose Exercise Type</label>
</div>
</div>
<!-- CARDIO SELECT FIELD -->
<div class="row" style="display:none" id="select_cardio">
<form method="POST" id="cardio_form">
<div class="input-field col s12">
<div class="select-wrapper initialized"><span class="caret">▼</span>
<select id="cardio_exercise" name="cardio_exercise" class="initialized">
<option value="0" disabled selected>Choose Cardio Exercise</option>
<option value="1">Jumping Jacks</option>
<option value="2">Jump Rope</option>
<option value="3">Precor</option>
<option value="4">Running (outside)</option>
<option value="5">Swimming</option>
<option value="6">Treadmill</option>
</select>
</div>
<input type="date" style="display:none" id="cardio_exercise_date" name="cardio_exercise_date">
<input placeholder="Duration (minutes)" name="cardio_duration" id="cardio_duration" type="number" class="validate">
<input placeholder="Distance (optional)" name="cardio_distance" id="cardio_distance" type="number" class="validate">
<button class="btn waves-effect waves-light" id="add_exercise_from_cardio" type="submit" name="action" value="ADD">Add Exercise</button>
<button class="btn waves-effect waves-light" id="finish_tracking" type="submit" name="action" value="FINISH">Finish Workout</button>
<label for="cardio_exercise">Choose Exercise</label>
</div>
</form>
</div>
The jQuery documentation dictates that since jQuery 1.6, attr will not update the dynamic state of a DOM element. In addition, it appears your select is disabled after being selected. Try:
$('#exercise_category option[value="0"]').prop('disabled', false);
$('#exercise_category option[value="0"]').prop('selected', true);
There is probably a better and more efficient way to solve it, but I figured it out. I wrapped the select option in form wrappers and gave the form an ID. Then on the button click I triggered reset of the form using
$('#button_id').on('click', function(e) {
e.preventDefault();
$('#form_id').trigger('reset');
});
Although I'm sure there is a better way, this method worked for me and hopefully it works for someone else too.

Submit form not working when using jQuery

I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>

Bootstrap website payments with Stripe

I'm completely new to using Stripe for payments, and as it's a Bootstrap site & I'm using Stripe.js v2.
From my understanding of how Stripe works, my HTML form needs to initially communicate with Stripe with the credit card num, cvc & expirary using Javascript, which will return a token (or an error) - and I then submit this token, and other payment information like the amount etc.. to the PHP script on my Server (which then sends this Stripe).
My problem is, my JavaScript is never executed first - and instead my page tries to run submit.php first.
What should I do to correct this - and have my JavaScript create the token, and then have the token passed to my submit.php code?
*Note - my HTML form does contain more than what's listed here (such as asking the user for Name, Address, State, Phone, Amount etc), but i shortened it, so it was easier to read.
HTML Code:
<form action="/PHP/submit.php" method="POST" class="contact-form" id="payment-form">
<div id="creditcard">
<span class="payment-errors"></span>
<div class="form-group has-feedback row">
<label for="cardnumber" class="col-sm-2 form-control-sm">Card Number:</label>
<div class="col-sm-5">
<!--<input type="text" autocomplete="off" class="form-control form-control-sm card-number" value="" pattern="[0-9]{10}" data-stripe="number">-->
<input type="text" autocomplete="off" class="form-control form-control-sm card-number" data-stripe="number">
</div>
<label for="cvc" class="col-sm-1 form-control-sm">CVC:</label>
<div class="col-sm-4">
<!--<input type="text" autocomplete="off" class="form-control form-control-sm card-cvc" maxlength="3" value="" pattern="[0-9]{3}" data-stripe="cvc">-->
<input type="text" autocomplete="off" class="form-control form-control-sm card-cvc" data-stripe="cvc">
</div>
</div>
<div class="form-group has-feedback row">
<label for="expiration" class="col-sm-2 form-control-sm">Expiration Date </label>
<div class="col-sm-2">
<select class="card-expiry-month form-control form-control-sm" data-stripe="exp-month">
<option value="01" selected>01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<div class="col-sm-2">
<select class="card-expiry-year form-control form-control-sm" data-stripe="exp-year">
<option value="2018" selected>2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="cardname" class="col-sm-2 form-control-sm">Name on Card:</label>
<div class="col-sm-10">
<input type="text" class="form-control form-control-sm" autocomplete="off" name="cardname" id="cardname">
</div>
</div>
<div class="form-row form-submit">
<button type="submit" class="btn btn-default submit-button">Submit Donation</button>
</div>
</div>
</form>
And my Javascript:
<script src="https://js.stripe.com/v2/"></script>
<script>
(function() {
Stripe.setPublishableKey('pk_test_xxxxx');
})();
</script>
<script>
$(document).ready(function() {
$('#payment-form').on('submit', generateToken);
var generateToken = function(e) {
var form = $(this);
//No pressing the buy now button more than Once
form.find('button').prop('disabled', true);
//Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
//Prevent the form from submitting
e.preventDefault();
});
});
var stripeResponseHandler = function(status, response) {
var form = $('#payment-form');
//Any validation errors?
if (response.error) {
form.find('.payment-errors').text(response.error.message);
alert(result.error.message);
//Make the submit button clickable again
form.find('button').prop('disabled', false);
} else {
//Otherwise, we're good to go! Submit the form.
//Insert the unique token into the form
$('<input>', {
'type': 'hidden',
'name': 'stripeToken',
'value': response.id
}).appendTo(form);
alert(result.token.id);
//Call tge native submit method on the form
//to keep the submission from being cancelled
form.get(0).submit();
}
};
</script>
You should define the generateToken function before the $('#payment-form').on('submit', generateToken);. Otherwise the submit event has no handler, and e.preventDefault(); is never reached.
$(document).ready(function() {
$('#payment-form').on('submit', generateToken);
var generateToken = function(e) {
var form = $(this);
//No pressing the buy now button more than Once
form.find('button').prop('disabled', true);
//Create the token, based on the form object
Stripe.create(form, stripeResponseHandler);
//Prevent the form from submitting
e.preventDefault();
});
});
Demo: https://www.codeply.com/go/wRcqjxfVmf
I ended up going a slightly different direction, using an 'onsubmit' event on the form, to trigger the javascript before the PHP;
<form action="/PHP/submit.php" method="POST" class="contact-form" id="payment-form" onsubmit="return onSubmitDo()">
I also completely changed the Javascript so it looked like this:
Stripe.setPublishableKey('pk_test_******');
function onSubmitDo () {
Stripe.card.createToken( document.getElementById('payment-form'), myStripeResponseHandler );
return false;
};
function myStripeResponseHandler ( status, response ) {
console.log( status );
console.log( response );
if ( response.error ) {
document.getElementById('payment-error').innerHTML = response.error.message;
} else {
var tokenInput = document.createElement("input");
tokenInput.type = "hidden";
tokenInput.name = "stripeToken";
tokenInput.value = response.id;
var paymentForm = document.getElementById('payment-form');
paymentForm.appendChild(tokenInput);
paymentForm.submit();
}
};
The actual javascript code I used here, i found on this github account which has some Stripe payment samples;
https://github.com/wsmoak/stripe/blob/master/php/test-custom-form.html
Now the form just needs to integrate jquery.payment (to format & validate card details), and it should all be complete.
https://github.com/stripe/jquery.payment

Using jQuery validate on select list

I have the following javascript:
var $step = $(".wizard-step:visible:last"); // get current step
var validator = $("#WizardForm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function ()
{
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
This is successfully validating all my input fields but upon trying to apply a similar method to the select type using code:
$step.find("select").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
My HTML is as follows:
<div class="wizard-step" id="step1" visibility="hidden" style="display: block;">
<div class="row">
<div class="col-md-6 column ui-sortable">
<div class="form-group">
<label class="control-label col-md-4" for="Tariff_Type">Tariff Type</label>
<div class="col-md-8">
<select style="width:100%;height:35px;border-radius:4px;padding-left:10px;" id="TariffType" name="TariffType" class="form-control input required">
<option value="">Please Select Tariff Type</option>
<option value="keypad account">Say Hello To Budget Extra Discount</option>
<option value="bill pay account">Standard 24H</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="TariffType" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
</div>
How can I ensure that a TariffType value is selected using this method?
Try the .valid() method instead...
if (! $(this).valid()) { ...

onchange can't find function

I'm trying to make an input change value depending on another inputs value.
What I've come up with so far is this. But when running the onchange commmand I get an error that updateCity doesn't exist. Even thou it's there. Am I doing something wrong, is pretty new to coding with javascript.
<div class="form-inline">
<div class="form-group">
<label class="sr-only" for="zip">Indtast postnummer</label>
<input class="form-control" type="text" name="register_zip" id="zip" placeholder="Indtast postnummer" value="#city.zip" onchange="updateCity(this.value)" />
</div> <!-- class="form-group" -->
<div class="form-group">
<label class="sr-only" for="city">Indtast by</label>
<input class="form-control" type="text" name="register_city" id="city" placeholder="Indtast by" value="#city.name" />
</div> <!-- class="form-group" -->
</div>
<script>
function updateCity(city_zip) {
var city = findCity(city_zip);
if(city != null){
document.getElementById("register_city").value = city_name;
}
};
function findCity(zip){
var cities = [];
#{
foreach (var c in cities)
{
<text>
cities.push({zip: #c.zip, name: #c.name});
</text>
}
}
for(var i=0;i<cities.length;i++){
if(cities[i].zip == zip){
return cities[i]
}
}
};
</script>

Categories

Resources