How to achieve a HTML check in JavaScript and jQuery - javascript

I want to create a check that will create the class form-group has-success has-feedback in a div and glyphicon glyphicon-ok form-control-feedback in an li.
What I am trying to achieve (when user has filled it out correctly):
<div class="form-group has-success has-feedback ">
<div class="col-sm-10">
<input type="text" class="form-control" id="inputSuccess">
<span class="glyphicon glyphicon-ok form-control-feedback"></span>
</div>
</div>
How my code looks like:
function InputChecker(InputChecker, tracker) {
let div = ($('<div/>', {
'class': InputChecker
}));
return div;
}
function password(tracker) {
let input = ($('<input/>', {
'type': 'password',
'name': 'password',
'class': 'form form-control',
'id': 'password',
'placeholder': 'Fill in your password (minimum length of 8 characters required!)',
'required': true
})).on('keyup', function() {
tracker.pwd = $(this).val();
if ($(this).val().length < 8) {
var x = InputChecker('form-group has-success has-feedback', tracker);
console.log(x);
$(this).after('<span class="glyphicon glyphicon-ok form-control-feedback"></span>');
} else {
// Do something else
}
});
return input;
}
How my document.ready looks like:
let inputFieldStructure = $(eBlock('col-md-6 col-md-offset-3', tracker).append(InputChecker('', tracker)));
inputFieldStructure.append(loginName(tracker), userName(tracker), password(tracker), confirmPassword(tracker)).appendTo('#registerAndLogin');
How my HTML looks like:
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h1>test</h1>
</div>
<div class="panel-body">
<form action="registerAndLogin.php" method="POST" id="registerAndLogin">
</form>
</div>
<div class="panel-footer">
<h1>test</h1>
</div>
</div>
</div>
</body>

Just need two changes based upon information provided:
HTML:
<div id="passwordDiv">
<div class="col-sm-10">
<input type="text" class="form-control" id="inputSuccess">
<span id="passwordSpan"></span>
</div>
</div>
JS on success:
if ($(this).val().length < 8) {
$("#passwordDiv").addClass("form-group");
$("#passwordDiv").addClass("has-success");
$("#passwordDiv").addClass("has-feedback");
$("#passwordSpan").addClass("glyphicon");
$("#passwordSpan").addClass("glyphicon-ok");
$("#passwordSpan").addClass("form-control-feedback");
} else {
// Do something else
}

Related

Hidden input not submitted after updating value in on submit event

Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.

how can I clone ajax dropdown

I've got a dropdown box which is populated with ajax according to what option i choose from another dropdown. I need to duplicate the dropdown box keeping the same options loaded via ajax, this is what i've done o far. Many thanks for your help
This is the code to get tha value from the first dropbox and then use it for ajax
$('#flatGroup').on('change',function(){
var countryID = $(this).val();
console.log(countryID);
if(countryID){
$.ajax({
type:'POST',
url:'../controllers/ctrl_admin_group_table_app/ctrl_admin_get_building_table.php',
data: {
group_id: countryID
},
success:function(html){
$('#flatTable-1').html(html);
$(".bs-select").selectpicker('refresh');
}
});
}
});
This is the code i'm using to close the second dropbox that receive the option from ajax
// start repeating form tabelle
//Start repeating form group add limit
var maxGroup1 = 5;
//add more fields group
var fieldGroup1= $(".fieldGroup1").clone();
$(".addMore1").click(function() {
var fgc1 = $('body').find('.fieldGroup1').length;
if (fgc1 < maxGroup1) {
var fieldHTML1 = '<div class="form-group fieldGroup1">' + fieldGroup1.html() + '<div class="col-md-1"><label class="control-label"> </label><i class="fa fa-close"></i></div></div>';
fieldHTML1 = fieldHTML1.replace('flatTable-1', 'flatTable-' + (fgc1 + 1));
fieldHTML1 = fieldHTML1.replace('flatMillesimi-1', 'flatMillesimi-' + (fgc1 + 1));
$('body').find('.fieldGroup1:last').after(fieldHTML1);
$('.bs-select').selectpicker({
iconBase: 'fa',
tickIcon: 'fa-check'
});
} else {
swal("Operazione Annullata", "Hai raggiunto il massimo numero di proprietari registrabili", "error");
}
});
//remove fields group
$("body").on("click", ".remove", function() {
$(this).parents(".fieldGroup1").remove();
});
// end repeating form
This is the HTML code
<div class="row">
<div class="col-md-9">
<div class="portlet-body form">
<div class="col-md-9">
<div class="mt-repeater">
<div data-repeater-list="group-b">
<div data-repeater-item class="row">
<div class="form-group fieldGroup1">
<div class="col-md-4">
<div class="form-group">
<label class="control-label">Tabella</label>
<select class="form-control bs-select" id="flatTable-1" name="flatTable[]" title="Seleziona tabella millesimale"></select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label">
<i class="fa fa-info-circle red tooltips" data-placement="top" data-original-title="Quota del titolare dell'immobile" ></i>Millessimi<span class="required"> * </span>
</label>
<input type="text" id="flatMillesimi-1" name="flatMillesimi[]" class="form-control" placeholder="Millessimi dell'immobile" >
</div>
</div>
</div> <!-- Fine field group -->
</div>
</div>
<!-- <hr> -->
<a href="javascript:;" data-repeater-create class="btn btn-info mt-repeater-add addMore1">
<i class="fa fa-plus"></i> Aggiungi tabella</a>
<br>
<br>
</div>
</div>
</div>
</div>
</div>

Trying to send custom inputs to braintree but only payment_method_nonce works

I am attempting to have the user inputs( first name, last name, contract number, amount) pass to payment.php and then be sent via $result = Braintree_Transaction::sale but payment_method_nonce is the only thing that passes to payment.php. When test payment.php with <?php print_r($_POST); ?> I only receive Array ( [payment_method_nonce] => 9ce4f24f-9746-076c-760b-d30d18a3cdf5 ) Thanks in advance Here is my code:
HTML
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default bootstrap-basic">
<div class="panel-heading">
<h3 class="panel-title">Enter Payment Details</h3>
</div>
<form class="panel-body" id="paymentportal" action="payment.php" method="post">
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">First Name</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="John" class="form-control" id="first-name">
</div>
<div class="form-group col-sm-6">
<label class="control-label">Last Name</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="Doe" class="form-control" id="last-name">
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Contract Number</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="1462" class="form-control" id="order-number">
</div>
<div class="form-group col-sm-6">
<label class="control-label">Amount</label>
<!-- Hosted Fields div container -->
<input type="text" placeholder="$1234.56" class="form-control" id="amount">
</div>
</div>
<div class="row">
<div class="form-group col-sm-8">
<label class="control-label">Card Number</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="card-number"></div>
<span class="helper-text"></span>
</div>
<div class="form-group col-sm-4">
<div class="row">
<label class="control-label col-xs-12">Expiration Date</label>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-month"></div>
</div>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-year"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Security Code</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="cvv"></div>
</div>
<div class="form-group col-sm-6">
<label class="control-label">Zipcode</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="postal-code"></div>
</div>
</div>
<input type="hidden" name="payment_method_nonce" id="payment_method_nonce">
<button value="btnSubmit" id="btnSubmit" class="btn-box center-block">Pay with <span id="card-type">Card</span></button>
</form>
</div>
</div>
JS
var form = document.getElementById('paymentportal');
braintree.client.create({
authorization: 'sandbox_authorization'
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationMonth: {
selector: '#expiration-month',
placeholder: 'MM'
},
expirationYear: {
selector: '#expiration-year',
placeholder: 'YY'
},
postalCode: {
selector: '#postal-code',
placeholder: '90210'
}
}
}, function (err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
if (field.isValid) {
if (event.emittedBy === 'expirationMonth' || event.emittedBy === 'expirationYear') {
if (!event.fields.expirationMonth.isValid || !event.fields.expirationYear.isValid) {
return;
}
} else if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
// Remove any previously applied error or warning classes
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
// Apply styling for a valid field
$(field.container).parents('.form-group').addClass('has-success');
} else if (field.isPotentiallyValid) {
// Remove styling from potentially valid fields
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
} else {
// Add styling to invalid fields
$(field.container).parents('.form-group').addClass('has-warning');
// Add helper text for an invalid card number
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('Looks like this card number has an error.');
}
}
});
hostedFieldsInstance.on('cardTypeChange', function (event) {
// Handle a field's change, such as a change in validity or credit card type
if (event.cards.length === 1) {
$('#card-type').text(event.cards[0].niceType);
} else {
$('#card-type').text('Card');
}
});
$('.panel-body').submit(function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
console.error(err);
return;
}
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
// This is where you would submit payload.nonce to your server
form.submit();
});
});
});
});
PHP
<?php
$result = Braintree_Transaction::sale([
'amount' => $_POST['amount'],
'orderId' => $_POST['order-number'],
'paymentMethodNonce' => $_POST['payment_method_nonce'],
'customer' => [
'firstName' => $_POST['first-name'],
'lastName' => $_POST['last-name'],
],
'options' => [
'submitForSettlement' => true
]
]);
if ($result->success === true){
}else
{
print_r($result->errors);
die();
}
?>
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.
Remember when you collect form data on your server, you need to reference those inputs by their name attribute. Once you add the respective name values to each of these inputs, it should work as expected.
For example, your first name input;
<input type="text" placeholder="John" class="form-control" id="first-name" name="first-name">

jQuery ajax form submission to php not working with response from server

Note: this is a jQuery coding exercise and I am not allowed to use plugins or other modules.
I have a typical signup form. When the user completes registration and everything is valid I want to fade in a sign in element that the user can use to sign in right away.
Note: I am using the Skeleton framework
HTML:
<div class="container">
<form id="myForm" action="validate_signup.php" method="post">
<div class="row">
<div class="twelve columns">
<h3 class="center">Sign Up</h3>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="email" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="four columns offset-by-four">
<input class="u-full-width" type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span>
</div>
</div><!--end row-->
<div class="row">
<div class="six columns offset-by-four">
<input class="button-primary" type="submit" value="Submit" name="signup">
</div>
</div><!--end row-->
</form>
<div class="row">
<div class="twelve columns">
<p id="response" class="center no-display"></p>
</div>
</div>
</div><!--end container-->
<script src="../js/jquery.js"></script>
<script src="../js/signup.js"></script>
jQuery:
// jQuery form validation
$(document).ready(function(){
// field mapping
var form_fields = {
'email' : 'email',
'pword' : 'password',
'fname' : 'first name',
'lname' : 'last name'
};
// ajax data
var ajaxData = {};
// make sure form fields were entered
$('#myForm').on('submit', function() {
for (var field in form_fields) {
if (!$('#' + field).val()) {
$('#' + field).next().addClass('error_show');
} else if ($('#' + field).val()) {
$('#' + field).next().removeClass('error_show');
ajaxData[field] = $('#' + field).val();
}
}
// 'signup' post field to indicate to php a submission was made
ajaxData['signup'] = 'Submit';
// send data if it is all there
if (Object.keys(ajaxData).length === 5) {
$('#response').hide().empty();
var request = $.ajax({
url : 'validate_signup.php',
method : 'POST',
data : ajaxData,
dataType : 'html'
});
request.done(function(response) {
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}
$('#response').html(response).fadeIn();
$("input[name=email], input[name=pword], input[name=fname], input[name=lname]").val('');
});
request.fail(function() {
alert('Your request could not be processed.');
});
}
return false;
});
});
I am not going to post the php as it is a big piece of code. Just know that if all user data is valid and a successful registration is made PHP outputs, Sign up complete. That is the response.
The main line in question is:
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}
First I tested this condition with console.log('response was Sign up complete) in place of $('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn(); to make sure the condition worked, which it did. But, the fading in of a signin.php link does not work. Instead I am only seeing,
Sign up complete.
change this line
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}
$('#response').html(response).fadeIn();
to
if (response === 'Sign up complete.') {
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn();
}else{
$('#response').html(response).fadeIn();
}
Your can also change the div style to see the fadein effect. example:
<div id="response" style="display:none">
Use time parameter to see the real effect.
$('#response').html(response + "<a href='signin.php'>Sign in</a>").fadeIn(1000);

How to get values from input Boxes

I have the following HTML and JS Code and the problem, that I'm not quite sure how to get the values from the input-boxes with the classes bti, bi, bp and bb when I click on the savebtn Button. I really hope someone can help me and give me a hint! best regards
$(document).ready(function() {
$('.savebtn').click(function() {
//how to i get the values?
});
});
<div class="modal-body">
<?php
for ($i=0; $i<count($barkeeperarr); $i++) {
?>
<div class="panel panel-primary" value="<?php echo $barkeeperarr[$i]->getID(); ?>" >
<div class="panel-heading clickablePanel">
<div class="panel-title"><?php echo $barkeeperarr[$i]->getFirstname().' '.$barkeeperarr[$i]->getLastname(); ?></div>
</div>
<div class="panel-body" style="display: none">
<div class="container-fluid">
<div class="row" value="row" style="margin-bottom: 3px">
<div class="col-xs-5">
<input type="text" class="form-control bti" placeholder="Gesamtumsatz">
</div>
<div class="col-xs-5">
<input type="text" class="form-control bi" placeholder="Einladung">
</div>
<div class="col-xs-2">
<button type="button" class="btn btn-primary btn-sm savebtn">Hinzufügen</button>
</div>
</div>
<div class="row" style="margin-bottom: 3px">
<div class="col-xs-5">
<input type="text" class="form-control bp" placeholder="Personal">
</div>
<div class="col-xs-5">
<input type="text" class="form-control bb" placeholder="Bruch">
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
It will something like this,
$('.savebtn').click(function() {
$.each($('input:text.form-control'), function(){
if ($(this).prop('class') === 'bti'){
alert('form-control bti value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bp'){
alert('form-control bp value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bb'){
alert('form-control bb value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bi'){
alert('form-control bi value = ' + $(this).val()));
});
});
You could store the values in an array and then process that array to add the values to your database.
For instance, let's create an array called values :
var values = [];
Then add an object to that array with the values of the respective classes bti, bi, bp and bb like :
jQuery(document).ready(function ($) {
var formControl = $(".form-control");
$('.savebtn').on("click", function () {
//how to i get the values?
for (var i = 0; i < formControl.length; i++) {
values[i] = {
name: formControl[i].className.split(" ")[1],
val: formControl[i].value
}
}
});
}); // ready
Notice we targeted the selector .form-control, which is a common class to all input fields.

Categories