I've been stuck for some time. Trying to make a quick donation widget push donation amount onto a donation form on the next page inside the "Other Amount" field.
The form is embedded in the website and hosted by Blackbaud Online Express and has actions like /?BBGiftAmount= online for fixed gift amounts. However not for custom amounts.
Below is my HTML markup of the form.
<div class="donation-wrapper">
<div class="container ">
<div class="row d-flex align-items-center">
<div class="col-lg-2 title">
<h2>Make a Gift:</h2>
<p>Give Generously</p>
</div>
<div class="col-lg-10">
<form action="https://islamic-relief.com.au/what-we-do/aid-and-development/#become-volunteers" class="form-inline ">
<label class="sr-only">Donation Type</label>
<select class="form-control my-1 mr-sm-2">
<option selected>One Time Donation</option>
<option value="1">Recurring Donation</option>
</select>
<label class="sr-only">Donation Amount</label>
<input value="" class="form-control my-1 mr-sm-2" type="number" placeholder="Donation Amount">
<label class="sr-only">Choose Fund</label>
<select name="BBFund" id="bboxdonation_designation_ddDesignations" class="form-control my-1 mr-sm-2">
<option value="103">Lebanon Disability Centre</option>
<option value="84">Water and Sanitation</option>
</select>
<button type="submit" class="btn btn-primary my-1">Donate Now</button>
</form>
</div>
</div>
</div>
</div>
Also, through Chrome console found where the hosted form is reading actions for "?BBGiftAmount=".
function i(t) {
var p = location.search.replace("?", "").split("&"),
m = BBOX.buildQuerystringObject(p),
s, q, u = false,
o = false,
l = m.hasOwnProperty("bbhideothergifts") && m.bbhideothergifts === "1",
v = m.hasOwnProperty("bbhideotherfunds") && m.bbhideotherfunds === "1",
n = !t || l,
r = !t || v;
if (n && m.hasOwnProperty("bbgiftamount")) {
q = parseFloat(m.bbgiftamount);
f.each(a.find(".BBFormRadioGivingLevelItem .BBFormRadioGivingLevelOther"), function() {
if (parseFloat(f(this).val()) === q) {
a.find(".BBDFormSectionGiftInfo input[data-giftchoice][value='1']").attr("checked", "checked").change();
f(this).attr("checked", "checked").change();
u = true;
return false
}
})
}
if (n && m.hasOwnProperty("bbpledgeamount")) {
q = parseFloat(m.bbpledgeamount);
f.each(a.find(".BBFormRadioPledgeAmountItem .BBFormRadioGivingLevel"), function() {
if (parseFloat(f(this).val()) === q) {
a.find(".BBDFormSectionGiftInfo input[data-giftchoice][value='0']").attr("checked", "checked").change();
f(this).attr("checked", "checked").change();
o = true;
return false
}
})
}
if (l) {
if (u && o) {
a.find(".BBFormRadioGivingLevelItem .BBFormRadioLabelGivingLevelNotSelected").parent().remove();
a.find(".BBFormRadioPledgeAmountItem .BBFormRadioLabelGivingLevelNotSelected").parent().remove()
} else {
if (u) {
a.find(".BBFormGiftChoice").remove();
a.find(".BBFormRadioGivingLevelItem .BBFormRadioLabelGivingLevelNotSelected").parent().remove()
} else {
if (o) {
a.find(".BBFormGiftChoice").remove();
a.find(".BBFormRadioPledgeAmountItem .BBFormRadioLabelGivingLevelNotSelected").parent().remove()
}
}
}
}
if (r && m.hasOwnProperty("bbfund")) {
s = a.find('.BBDFormSectionDesignationInfo select[id*="ddDesignations"]');
if (s.find('option[value="' + m.bbfund + '"]').length > 0) {
s.val(m.bbfund);
if (v) {
s.find('option[value!="' + m.bbfund + '"]').remove()
}
}
}
}
Related
Am JavaScript newbie, and i wanted some help.
the above script can validate valid and invalidate credit card / debit
my problem is that, how can i clear the "invalid credit / debit card number" error message when user has started typing again the card
its like i want to auto clear error message when user has re-type again
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError"></span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<script type="text/javascript">
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
</script>
</body>
</html>
I have added a input event listener to the input, and based on the length of text present in input, I clear the error message (if its length is greater than 0, which marks user has started typing again.)
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError"></span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
<script type="text/javascript">
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
document.querySelector("#cc_number").addEventListener("input", function() {
if (document.querySelector("#cc_number").value.length > 0) {
document.getElementById("loginError").innerHTML = "";
}
})
</script>
</body>
</html>
Based on your code, I'd suggest adding a line to clear the error message into your event handler:
document.getElementById('cc-cvv').addEventListener('change', function() {
document.getElementById("loginError").innerHTML = "";
CWcheck();
});
This will reset the message to an empty string every time a keystroke is read. It'll also show error messages when the check comes back as invalid.
Hopes this helps.
There are multiple ways of doing this. With your current setup you could use a class to show and hide the error rather than adding the innerHTML. This class could just be removed after each change. Example with your code, attached.
document.getElementById('cc-cvv').addEventListener('change', CWcheck); //recommended way
document.getElementById('cc_number').onchange = creditCheck; //it is OK too
function CWcheck() { //function name should conventionally start with lower case but isn't big deal
//"this" is the element which fired the event
if (!/^\d{3,4}$/.test(this.value)) {
this.value = '';
this.focus();
alert('CVV is 3 or 4 digits');
}
}
function creditCheck() {
document.getElementById("loginError").classList.remove('card-error--active')
// hide cc logos
var ccImgs = document.querySelectorAll('h2 img');
for (var i = 0, ccImg; ccImg = ccImgs[i]; ++i) {
ccImg.style.visibility = 'hidden';
}
var ccNum = this.value.replace(/\D/g, ''); //remove all non-digits
if (ccNum.length < 15 /*15 is amex*/ || ccNum.length > 16) {
document.getElementById("loginError").classList.add('card-error--active')
this.focus();
return false;
}
//implement Luhn algorithm
var check = ccNum.split('') //get array
.reverse()
.map(function(el, index) {
return el * (index % 2 + 1); //multiply even positions by 2
})
.join('') //combine array of strings
.split('')
.reduce(function(a, b) { //sum digits
return a + (b - 0);
}, 0);
if (!check || (check % 10)) { //checksum should be none-zero and dividable by 10
document.getElementById("loginError").classList.add('card-error--active')
this.focus();
return false;
}
//test passed. show card logo
if (/^5[1-5]/.test(ccNum))
document.querySelector('h2 img.mastercard').style.visibility = 'visible';
else if (/^4/.test(ccNum))
document.querySelector('h2 img.visacard').style.visibility = 'visible';
else if (ccNum.length == 15 && /^3[47]/.test(ccNum))
document.querySelector('h2 img.amexcard').style.visibility = 'visible';
else if (/^6011/.test(ccNum))
document.querySelector('h2 img.discovercasd').style.visibility = 'visible';
//and so on
else {
document.getElementById("loginError").innerHTML = "invalid credit / debit card number";
this.focus();
return false;
}
//test passed. format the string
this.value = ccNum
.replace(/^(\d{4})(\d{4})(\d{4})(\d+)$/, '$1 $2 $3 $4');
}
.card-error{
display:none;
}
.card-error--active{
display:block;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h2>Payment
<img style="visibility: hidden" class="mastercard" src="https://img.icons8.com/color/48/000000/mastercard.png">
<img style="visibility: hidden" class="visacard" src="https://img.icons8.com/color/48/000000/visa.png">
<img style="visibility: hidden" class="discovercard" src="https://img.icons8.com/color/48/000000/discover.png">
<img style="visibility: hidden" class="amexcard" src="https://img.icons8.com/color/48/000000/amex.png">
</h2>
<div class="form-group">
<label for="name-on-card">Name on Card</label>
<input class="cc_name" type="text" name="card-name" class="form-control" placeholder="">
</div>
<div class="form-group">
<label for="cc-number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" name="cc_number" placeholder="" maxlength="20">
<span id="loginError" class="card-error">invalid credit / debit card number</span>
</div>
<!--<div class="">
<select class="month_year_select" name="month" id="month">
<option value="">exp month</option>
</select>
</div>
<div class="">
<select class="month_year_select" id="year" name="year">
<option value="">exp year</option>
</select>
</div>-->
<div class="CVV">
<label for="cc-cvv">CVV</label>
<input type="text" class="form-control" id="cc-cvv" name="cc-cvv" placeholder="" maxlength="4">
</div>
</body>
</html>
Having issue when i am using fileupload object to show the files while before upload in the modal
Even Try make a shallow copy of DOM object to use it but it still not working
Kindly Give me a possible solution for this problem
HTML and javascript Kindly see the FileConfigHandler Method
<div id="filedata"></div>
<div class="col-md-9">
<div class="homepage_contant">
<div class="container">
<!-- Start File Upload Section -->
<h4>File Upload</h4>
<form id="drag-and-drop-zone" class="upload_container" action="/Home/Upload" method="POST" enctype="multipart/form-data" ondrop="dropHandler(event);">
<div class="text-center">
<img class="cloud_upload_img" src="~/Content/images/cloud.png" />
<p>Drag & Drop Files Here or <span class="browse_btn_holder">Browse <input class="browse_btn" type="file" accept=".xls..xlsx image/* " multiple id="mfile" name="mfile" title='Click to add Files' /> </span> to upload files</p>
</div>
<!-- Modal -->
<div class="upload_file_modal modal" id="uploadFileModal" tabindex="-1" role="dialog" aria-labelledby="uploadFileModal" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">File Upload</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<ul class="list-unstyled p-2 d-flex flex-column col" style="padding:0 !important" id="files">
<li class="text-muted text-center empty"><p id="txt"> Files has been seleted. </p></li>
</ul>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="upload_field_wrap">
<label for="ItemTitle"> File Title</label>
<input type="text" class="form-control" id="title" name="title" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
#Html.DropDownList("Department", ViewBag.lst as SelectList, "Select Department", new { #class = "form-control" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select class="form-control" id="CourseId" name="CourseId">
<option value="" disabled selected>Course</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select class="form-control" id="category" name="category">
<option value="" disabled selected>Select Category</option>
<option value="mid">
Mid Term
</option>
<option value="final">
Final
</option>
<option value="quiz">
Quiz
</option>
<option value="summary">
Summary
</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select id="yearOfPublish" name="yearOfPublish" class="form-control">
<option value="" disabled> Select Year</option>
#for (int i = 2000; i < 2020; i++)
{
<option value="#i">#i</option>
}
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="upload_field_wrap">
<label for="description">Description</label>
<textarea class="form-control" id="" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
<!-- End File Upload Section -->
#section scripts
{
<script src="~/Scripts/jquery.dm-uploader.min.js"></script>
<script src="~/Scripts/upload_file_ui.js"></script>
<script>
function dropHandler(event) {
event.preventDefault();
mfile.files = event.dataTransfer.files;
console.log(mfile);
//ChangeImageHandler();
FileConfigHandler();
}
function formatBytes(bytes, decimals) {
if (bytes == 0) return '0 Bytes';
var k = 1024,
dm = decimals <= 0 ? 0 : decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function ChangeImageHandler()
{
var x = $('#mfile').val();
let file = $('#mfile')[0].files[0];
var size = $('#mfile')[0].size;
var sizeWithTag = formatBytes(size);
$('#item_size').text(sizeWithTag);
$('#item_title').text(file.name);
if (x.split('.').pop()=='pdf') {
$("#item_type_img").attr("src", "../../Content/images/files_types/pdf.png");
}
else if (x.split('.').pop() == 'docx') {
$("#item_type_img").attr("src", "../../Content/images/files_types/doc.png");
}
else if (x.split('.').pop() == 'jpg') {
$("#item_type_img").attr("src", "../../Content/images/files_types/jpg.png");
}
else if (x.split('.').pop() == 'png') {
$("#item_type_img").attr("src", "../../Content/images/files_types/png.png");
}
else if (x.split('.').pop() == 'ppt') {
$("#item_type_img").attr("src", "../../Content/images/files_types/ppt.png");
}
else if (x.split('.').pop() == 'txt') {
$("#item_type_img").attr("src", "../../Content/images/files_types/txt.png");
}
else if (x.split('.').pop() == 'xls') {
$("#item_type_img").attr("src", "../../Content/images/files_types/xls.png");
}
else if (x.split('.').pop() == 'csv') {
$("#item_type_img").attr("src", "../../Content/images/files_types/csv.png");
}
console.log();
}
function FileConfigHandler()
{
console.log('chal raha h')
var files1 = mfile.files;
console.log(mfile.files);
for (var i = 0; i < files1.length; i++) {
// console.log(files1[i]);
//var x= AddChild(files1[i]);
$('#files').append(x);
}
}
function AddChild(item)
{
var template = $('#files-template').html();
var parent = $(template);
var extention = item.name.split('.').pop();
// console.log(item.name.split('.').pop());
var name = item.name;
var temp_size = item.size;
var size = formatBytes(temp_size);
parent.find('#item_size').text(size)
parent.find('#item_title').text(name)
if (extention == 'pdf') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/pdf.png");
}
else if (extention == 'docx') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/doc.png");
}
else if (extention == 'jpg') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/jpg.png");
}
else if (extention == 'png') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/png.png");
}
else if (extention == 'ppt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/ppt.png");
}
else if (extention == 'txt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/txt.png");
}
else if (extention == 'xls') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/xls.png");
}
else if (extention == 'csv') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/csv.png");
}
return '<li class="uploaded_item">' + parent.html() + '</li>'
}
//function dropHandler(ev) {
// console.log('File(s) dropped');
// // Prevent default behavior (Prevent file from being opened)
// ev.preventDefault();
// var file = ev.dataTransfer.files;
// // var file = e.originalEvent.dataTransfer.files;
// var fileData = new FormData();
// for (var i = 0; i < file.length; i++) {
// fileData.append("fileData", ev.dataTransfer.files[i]);
// }
//if (ev.dataTransfer.items) {
// // Use DataTransferItemList interface to access the file(s)
// for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// // If dropped items aren't files, reject them
// if (ev.dataTransfer.items[i].kind === 'file') {
// file[i] = ev.dataTransfer.items[i].getAsFile();
// fileData.append("fileData",ev.dataTransfer.files[i]);
// console.log('... file[' + i + '].name = ' + file.name);
// }
// }
//} else {
// // Use DataTransfer interface to access the file(s)
// for (var i = 0; i < ev.dataTransfer.files.length; i++) {
// fileData.append("fileData", ev.dataTransfer.files[i]);
// console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
// }
//}
// $.ajax({
// type: "POST",
// dataType: "json",
// enctype: 'multipart/form-data',
// url:'/Home/SendFile',
// contentType: false, // Not to set any content header
// processData: false, // Not to process data
// data: fileData,
// success: function (result, status, xhr) {
// alert(result);
// },
// error: function (xhr, status, error) {
// alert(status);
// }
// })
//}
$(document).ready(function () {
$('#uploadFileModal').hide();
$('#drag-and-drop-zone').dmUploader({
onDragEnter: function () {
// Happens when dragging something over the DnD area
this.addClass('active');
$('.upload_container .cloud_upload_img').addClass('animated infinite shake')
},
onDragLeave: function (e) {
// Happens when dragging something OUT of the DnD area
this.removeClass('active');
$('.upload_container .cloud_upload_img').removeClass('animated infinite shake');
//readmultifiles(document.getElementById('#file'));
$('#uploadFileModal').modal("show");
}})
})
$('#mfile').change(function () {
console.log(mfile.files);
$('#uploadFileModal').modal("show");
//document.getElementById("#txt").innerHTML = "1 file has been Selected";
// console.log(mfile.files);
//ChangeImageHandler();
FileConfigHandler();
});
$("#Department").change(function () {
LoadDepartments();
});
function LoadDepartments() {
var collegeId = document.getElementById("Department");
var ID = collegeId.options[collegeId.selectedIndex].value;
var depatments = document.getElementById("CourseId");
console.log(ID);
$.ajax({
url: '#Url.Action("getCourses", "Home")',
type: 'GET',
dataType: "json",
data: { idString: ID },
success: function (result) {
console.log(result)
depatments.innerHTML = "";
$.each(result, function (i, result) {
var options = "<option value='" + result.Id + "' id='" + result.Id + "'>" + result.name + "</option>";
$('#CourseId').append(options);
});
},
failure: function (response) {
alert(response.responseText);
console.log(response.responseText);
},
error: function (response) {
alert(response.responseText);
console.log(response.responseText);
}
});
}
</script>
}
<!-- Debug item template -->
<script type="text/html" id="debug-template">
<li class="list-group-item text-%%color%%"><strong>%%date%%</strong>: %%message%%</li>
</script>
<!-- File item template -->
<script type="text/template" id="files-template">
<li class="uploaded_item">
<div class="item_body">
<div class="item_img_and_info_holder">
<div class="item_type_img_holder">
<img class="item_type_img" id="item_type_img" src="../../Content/images/files_types/pdf.png" />
</div>
<div class="item_info" style="width: 100%">
<h6 class="item_title" id="item_title">%%filename%% </h6>
<div class="item_details" style="margin-bottom: 10px;">
<span class="item_size" id="item_size">00.0 MB</span>
</div>
</div>
</div>
</div>
</li>
</script>
When removing AddChild() from loop it start working
also tried to do shallow copy but it did not work for me
function FileConfigHandler()
{
console.log('chal raha h')
var files1 = mfile.files;
console.log(mfile.files);
for (var i = 0; i < files1.length; i++) {
// console.log(files1[i]);
//var x= AddChild(files1[i]);
$('#files').append(x);
}
}
function AddChild(item)
{
var template = $('#files-template').html();
var parent = $(template);
var extention = item.name.split('.').pop();
// console.log(item.name.split('.').pop());
var name = item.name;
var temp_size = item.size;
var size = formatBytes(temp_size);
parent.find('#item_size').text(size)
parent.find('#item_title').text(name)
if (extention == 'pdf') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/pdf.png");
}
else if (extention == 'docx') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/doc.png");
}
else if (extention == 'jpg') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/jpg.png");
}
else if (extention == 'png') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/png.png");
}
else if (extention == 'ppt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/ppt.png");
}
else if (extention == 'txt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/txt.png");
}
else if (extention == 'xls') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/xls.png");
}
else if (extention == 'csv') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/csv.png");
}
return '<li class="uploaded_item">' + parent.html() + '</li>'
}
Here is the code:
<form class="ui form attached fluid loading segment" onsubmit="return contact(this)">
<div class="field">
<label>Preferred Tour</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select required id="tourInfo">';
echo '<option value="" selected disabled>--Preferred Tour--</option>';
$db = mysqli_query($conn, "SELECT `id`,`tourprice`,`tourname` FROM `available_tours`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['id']." id=".$d['tourname']. " data-price=".$d['tourprice'].">".$d['tourname']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="field" id="hiddenTortu" style="display: none;">
<label>Attention</label>
<div class="ui icon">
<p><b>The minimum of people for this tour is 5, less than 5 the tour is not realisable</b></p>
</div>
</div>
<div class="field">
<label>Available Time</label>
<div class="field">
<?php
$conn=mysqli_connect('####','####','####','####');
echo '<select name="gender" required id="timeInfo">';
echo '<option value="" selected disabled>--Preferred Time--</option>';
$db = mysqli_query($conn, "SELECT `time_real` FROM `available_time`");
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value=".$d['time_real'].">".$d['time_real']."</option>";
}
echo "</select>";
?>
</div>
</div>
<div class="two fields">
<div class="field" id="pax">
<label>Please specify the number of People according to the perred tour selection</label>
Here starts the problem with the following script according to the tour selection I'm trying to set up a minimum and maximum so that the user can't choose more numbers for the people on the tour.
The problem is that when the user select first one option, and then realised that the best option is another one, when he/she does another selection the input created with jQuery that was appended remains and because of the new selection a new input is created.
The intention is that if the user chooses option 1 the input append appears according to option one, but if the user regrets and prefers option 2 that the input for the option 1 disappears and a new input according to option 2 appears and so on for the entire if conditions.
<script>
$(document).ready(function(){
$('#tourInfo').on('change', function() {
if ( this.value == '1')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="1" max="2" value="1" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '2')
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="3" max="5" value="3" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}
else if (this.value == '3')
{
$("#pax").append($('<input placeholder="Number of People" type="number" id="peopleInfo" min="6" max="15" value="6" required>'));
(function ($) {
$.fn.restrict = function () {
return this.each(function(){
if (this.type && 'number' === this.type.toLowerCase()) {
$(this).on('change', function(){
var _self = this,
v = parseFloat(_self.value),
min = parseFloat(_self.min),
max = parseFloat(_self.max);
if (v >= min && v <= max){
_self.value = v;
}
else {
_self.value = v < min ? min : max;
}
});
}
});
};
})(jQuery);
$('#peopleInfo').restrict();
}...
...});
};
})(jQuery);
$('#peopleInfo').restrict();
}
});
});
</script>
</div>
<div class="field">
<label><br>Date of Tour</label>
<input type="text" readonly required id="tourDate" class="datepicker-here form-control" placeholder="ex. August 03, 1998">
</div>
</div>
<div style="text-align:center">
<div>
<label>Ensure all details have been filled correctly</label>
</div>
<button class="ui green submit button">Submit Details</button>
</div>
</form>
</div>
Move your script out from inside the div with id pax, then
Clear your html of the element with id pax before appending:
//Using JQuery
$('#pax').html('');
This is my first post here, so please no penalty points for me if there is anything unclear with my question. If so, I will edit or add necessary info.
I have an assignment for creating javascript validation method for html input and select, that validates both fields and removes error message after entering details or selecting drop-down option. And, I am having a problem with the second part which I do not seem to be able to find a solution for, and precisely:
1) error message does not disappear when an option from select is chosen (it works for input)
I was trying few things but obviously I do not see my mistakes and I really hope someone could point me in the right direction here.
And here is the code for validation:
var validations = {
req: function(data){
return (data != '' && data.length > 0);
}
}
$(document).ready(function(){
function addError(fname, error){
$('[name=' + fname + ']').after('<span class="validationError"> ' + error + '</span>');
}
function removeError(fname){
$('[name=' + fname + ']').parent('div').find('.validationError').remove();
}
var map = {};
for(var x in validationRules){
var fname = validationRules[x][0];
if(typeof fname == 'undefined') continue;
if(typeof map[fname] == 'undefined') map[fname] = [];
map[fname].push({
'method' : validationRules[x][1],
'error' : validationRules[x][2]
});
};
for(var x in map){
$('[name=' + x + ']').on('keyup', function(){
var fname = $(this).attr('name'),
validators = map[fname];
removeError(fname);
for(var y in validators){
if(typeof validators[y] == 'function') continue;
if(!validations[validators[y].method]($(this).val())) addError(fname, validators[y].error);
}
});
}
$('#send, #insert').on('click', function(ev){
var isOk = true;
$('.validationError').remove();
for(var x in map){
for(var y in map[x]){
if(typeof map[x][y] == 'function' || !$('[name=' + x + ']').is(':visible')) continue;
if(!validations[map[x][y].method]($('[name=' + x + ']').val())){
addError(x, map[x][y].error);
isOk = false;
}
}
};
return isOk;
});
});
and html form:
<form action="form-handler.php" method="post" class="form-contacts">
<div class="row col-sm-12 form-break1">
<div class="col-sm-3 col-lg-3 form-label">Your name</p></div>
<div class="col-sm-6 col-lg-6">
<input class="textInput" type="text" name="Name" value="" placeholder="Name & Surname" maxlength="50" />
</div>
</div>
<div class="row col-sm-12 form-break1">
<div class="col-sm-3 col-lg-3 form-label">Vehicle Make </div>
<div class="col-sm-3 col-lg-3">
<select name="Vehicle">
<option value=""></option>
<option value="Vehicle 1">Vehicle 1</option>
<option value="Vehicle 2">Vehicle 2</option>
</select>
</div>
</div>
<div class="wrapper sendButtons">
<div class="col-sm-3 col-lg-3"><input id="send" type="submit" value="Send Request"></div>
</div>
</form>
And finally, just before closing body tag, validation rules
<script>
var validationRules = [
// section 1
["Name","req","Please enter your full name & surname"],
["Vehicle","req","Select Vehicle"]
]
</script>
I am using a form for editing purposes.The Taxonomy Code gets populated when the form is getting loaded.The fields are bound to knockout observables in HTML using the data-bind attribute.The only issue I am facing is this particular field(Taxonomy Code) is NULL when the data is sent to the controller.
The HTML is
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Certification:</label>
<div class="col-sm-6">
<select class="form-control" id="certification" name="certification" data-bind="value:certification,options:certificationArray, optionsCaption: 'Select a Certification'">
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Specialization:</label>
<div class="col-sm-6">
<select class="form-control" id="specialization" name="specialization" data-bind="value:specialization,options:specializationArray, optionsCaption: 'Select a Specialization'"></select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Taxonomy Code:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Taxonomy code" id="taxonomyCode" name="taxonomyCode" data-bind="textInput: taxonomyCode,valueUpdate: 'input'" disabled="disabled">
</div>
</div>
JavaScript is
var provider = function() {
var self = this;
if ((providerEditInfo.Certification == "M.D.") || (providerEditInfo.Certification == "M.B.B.S")) {
specialities = ["Dermatology", "Hematology", "Neurology"];
} else if ((providerEditInfo.Certification == "R.N.") || (providerEditInfo.Certification == "M.S.N.")) {
specialities = ["Pediatric Nursing", "Critical Care Nursing", "Occupational Health Nursing"];
}
self.certificationArray = ko.observableArray(["M.B.B.S", "M.D.", "R.N.", "M.S.N."]);
self.certification = ko.observable(providerEditInfo.Certification);
self.specializationArray = ko.observableArray(specialities);
self.specialization = ko.observable(providerEditInfo.Specialization);
self.taxonomyCode = ko.observable(providerEditInfo.TaxonomyCode);
self.certification.subscribe(function(val) {
self.specializationArray([]);
if (val == "M.D." || val == "M.B.B.S") {
self.specializationArray(["Dermatology", "Hematology", "Neurology"])
} else if (val == "R.N." || val == "M.S.N.") {
self.specializationArray(["Pediatric Nursing", "Critical Care Nursing", "Occupational Health Nursing"])
} else {
self.specializationArray([]);
}
});
self.specialization.subscribe(function(val) {
self.taxonomyCode("");
if (val == "Dermatology")
self.taxonomyCode("207N00000X");
else if (val == "Hematology")
self.taxonomyCode("207RH0000X");
else if (val == "Neurology")
self.taxonomyCode("2084N0400X");
else if (val == "Pediatric Nursing")
self.taxonomyCode("363LP0200X");
else if (val == "Critical Care Nursing")
self.taxonomyCode("363LC0200X");
else if (val == "Occupational Health Nursing")
self.taxonomyCode("363LX0106X");
});
};
$(document).ready(function() {
ko.applyBindings(new provider());
});
I have added only minimal code.Could someone please tell me why the taxonomy field is null.Please refer the attached images.
Most browsers do not submit the values of disabled fields. If you want the value to be sent to the server you need figure out a different way to prevent the user from editing the field.