Checking form submission for minimum and maximum quantities - javascript

Working with an existing script that checks input values on form submission against existence of minimum quantity. I need to include a condition to check for the existence of maximum quantity and display an error message when the condition is not met. I believe it's a matter of editing the existing conditional logic but for the life of me I cannot get the edits to function without hosing up the functioning minimum condition. Rather than submitting my failed attempt at altering the code I'm submitting a functional version that only validates minimum quantities.
$('#button-cart').on('click', function() {
var total_quantity = 0;
var min_oneside = parseInt("<?php echo $min_oneside; ?>");
var min_bothside = parseInt("<?php echo $min_bothside; ?>");
var min_noprint = parseInt("<?php echo $min_noprint; ?>");
var min_standard = parseInt(" <?php echo $minimum; ?>");
var max_standard = parseInt(" <?php echo $maximum; ?>");
var validQty = true;
var validMaxQty = true;
var validInput = true;
var oth_minimum = "Quantity must be at least <?php echo $minimum; ?>";
var oth_maximum = "Quantity must be less than <?php echo $maximum; ?>"
$('#content').find('input[name^="option-quantity"]').each(function(){
total_quantity = total_quantity + parseInt($(this).val());
});
$('#content').find('input[name="quantity"]').each(function(){
total_quantity = total_quantity + parseInt($(this).val());
});
var element = $("label:contains('Printing')").attr('for');
if(element === undefined){
if( total_quantity < min_standard ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_standard;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
} else {
if ( ($("#" + element + " option:selected").text()).match("Printed One Side") ){
if( total_quantity < min_oneside ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_oneside;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
if ( ($("#" + element + " option:selected").text()).match("Printed Both Sides") ){
if( total_quantity < min_bothside ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_bothside;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
if ( ($("#" + element + " option:selected").text()).match("No Printing") ){
if( total_quantity < min_noprint ) {
validQty = false;
validInput = false;
oth_minimum = "Quantity must be at least " + min_noprint;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
}
}
if(!validQty) {
$('#errorQuantity').html(oth_minimum);
}
var minimum = "Quantity must be at least <?php echo $minimum; ?>";
if($('#errorQuantity').length > 0 && validQty) {
var quantity = 0;
$('#errorQuantity').empty();
$('input[type=number]').each(function () {
var currentId = $(this).attr('id');
checkboxId = currentId.replace("quantity-", "");
if(isNaN($(this).val()) || $(this).val() < 0) {
$(this).focus();
$(this).css('background-color', 'red');
validInput = false;
} else {
quantity += parseInt($(this).val());
}
});
if(quantity <= 0) {
$('#errorQuantity').append(minimum);
validInput = false;
}
}
if(validInput){
$('input[type=number]').each(function () {
$(this).css('background-color', '#FFFFFF');
});
$('#errorQuantity').empty();
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('.product-info input[type=\'text\'], .product-info input[type=\'number\'], .product-info input[type=\'date\'], .product-info input[type=\'datetime\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').attr('disabled', true);
$('#button-cart').after('<i class="fa fa-circle-o-notch fa-spin"></i>');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
$('#button-cart').next('.fa-spin').remove();
$('#button-cart').attr('disabled', false);
if (json['error']) {
var errors = '';
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
element.parents('.form-group').first().find('> label + div').append('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
if (json['error']['recurring']) {
$('select[name="recurring_id"]').after('<span class="error">' + json['error']['recurring'] + '</span>');
}
// Highlight any found errors
$('.text-danger').each(function() {
$(this).parents('.form-group').first().addClass('has-error');
});
}
if (json['success']) {
$('.tb_widget_cart > .tb_nav').load('index.php?route=common/cart/info .tb_nav > *');
window.location = $('base').attr('href') + 'index.php?route=checkout/cart';
//displayNotice('product', 'success', 'product', json['success']);
}
}
});
}
});

Should be something like :
if(element === undefined){
if( total_quantity < min_standard ) {
validQty = false;
validInput = false;
oth_message = oth_minimum;
}else if (total_quantity > max_standard){
validQty = false;
validInput = false;
oth_message = oth_maximum;
}
} else {
if ( ($("#" + element + " option:selected").text()).match("Printed One Side") ){
if( total_quantity < min_oneside ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_oneside;
}
}
if ( ($("#" + element + " option:selected").text()).match("Printed Both Sides") ){
if( total_quantity < min_bothside ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_bothside;
}
}
if ( ($("#" + element + " option:selected").text()).match("No Printing") ){
if( total_quantity < min_noprint ) {
validQty = false;
validInput = false;
oth_message = "Quantity must be at least " + min_noprint;
}
}
}
if(!validQty) {
$('#errorQuantity').html(oth_message);
}
You can add in the same way for the other conditionals, I added only for the first one.

Related

keyboard selection for custom dropdown

I have made a custom jquery dropdown plugin which is seems to be working good on desktop and mobile.
However,on mobile we are using native html behavior and in desktop we are designing the dropdown as we need with the help of ul li and then appending it to the select tag.
But i am not able to make any selection from keyboard which we normally can from the default native dropdown. Is there any solution ?
could someone help me how should i do it with keyCode or is there any solution ?
alphaDropdown: function(){
(function(jQuery){
jQuery.fn.AlphaDropdown = function( configurations ){
var defaultConfigurations = {
disabledFirst: false
};
var extendedconfigurations = jQuery.extend(defaultConfigurations, configurations || {});
function setBackData( ){
jQuery('.selectr-desktop-custom').each(function(){
var selectedValue = jQuery(this).removeClass('active').find('select').eq(0).val();
var selectedIndex = jQuery(this).removeClass('active').find('select').eq(0)[0].selectedIndex;
if( !selectedValue || selectedValue == ""){
var dropdown = jQuery(this).find('select').eq(0)[0];
var _index = dropdown.selectedIndex;
if( _index >= 0 ){
selectedValue = dropdown.options[_index].innerText;
selectedIndex = _index;
}
}
if ( selectedIndex != -1 ) {
var moveBy = -(selectedIndex * 40), movewithY = 'translateY('+moveBy+'px)';
jQuery(this).find('ul').eq(0).css({
transform: movewithY
});
};
});
}
jQuery(this).each(function(){
if( jQuery(this).parents('.selectr-desktop-custom').length > 0 ){
jQuery(this).parents('.selectr-desktop-custom').children('ul').remove();
jQuery(this).unwrap('.selectr-desktop-custom');
}
var preselectedvalue = jQuery(this).val() ;
if( !preselectedvalue || preselectedvalue == ""){
var dropdown = jQuery(this).eq(0)[0];
var _index = dropdown.selectedIndex;
if( _index >= 0 ){
preselectedvalue = dropdown.options[_index].innerText;
}
}
var list = "<ul>"
jQuery(this).wrap("<div class='selectr-desktop-custom' tabindex='0'></div>");
jQuery(this).find('option').each(function(){
var currentValue = jQuery(this).val() && jQuery(this).val().trim() != ""?jQuery(this).val():jQuery(this).text();
if( jQuery(this).index() == 0 ){
if( extendedconfigurations.disabledFirst && currentValue == preselectedvalue ){
list += "<li class='disabled active drop' alpha-value='" + currentValue +"'>" + jQuery(this).text() + "</li>";
}else if( extendedconfigurations.disabledFirst && currentValue != preselectedvalue ){
list += "<li class='disabled drop' alpha-value='" + currentValue+"'>" + jQuery(this).text() + "</li>";
}else if( !extendedconfigurations.disabledFirst && currentValue == preselectedvalue ){
list += "<li class='active' alpha-value='" + currentValue +"'>" + jQuery(this).text() + "</li>";
}
else{
list += "<li alpha-value='" + currentValue +"'>" + jQuery(this).text() + "</li>";
}
}
else{
if( currentValue == preselectedvalue ){
list += "<li class='active' alpha-value='"+ currentValue +"'>"+ jQuery(this).text() +"</li>";
}else{
list += "<li alpha-value='"+ currentValue +"'>"+ jQuery(this).text() +"</li>";
}
}
});
list += "</ul>";
jQuery(this).before(list);
jQuery(this).parents('.selectr-desktop-custom').click(function(e){
e.stopPropagation();
jQuery('.selectr-desktop-custom').removeClass('active');
jQuery(this).addClass('active');
jQuery(this).find('ul').eq(0).css('transform','translateY(0)');
}).find('ul').eq(0).find('li').click(function(e){
var _index = jQuery(this).index();
var moveBy = -(_index * 40), movewithY = 'translateY('+moveBy+'px)';
var ul = jQuery(this).parent();
var dropdown = ul.parent().find('select').eq(0);
jQuery(this).parent().css({
transform: movewithY
});
var seletedValue = jQuery(this).attr('alpha-value') || null;
if( seletedValue ){
dropdown.val(seletedValue).find('option').each(function(){
if( jQuery(this).text() === seletedValue || jQuery(this).val() === seletedValue ){
jQuery(this).attr('selected','selected');
}else{
jQuery(this).attr('selected',null);
}
});
dropdown[0].selectedIndex = _index;
dropdown.trigger('change');
}
jQuery(this).addClass('active').siblings().removeClass('active').closest('.selectr-desktop-custom').removeClass('active');
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});
jQuery('body').click(function(e){
setBackData();
});
});
setBackData();
return this;
}
})($);
}

Job For Wordpress by blueglass plugin apply button validation API

i want to insert following Java Script into my Wordpress plugin
please help me
this what i written which validate from Sheetsu API
Details at - https://codepen.io/santosh-panda/pen/YOedWv?editors=1010
<input id="input-text_flacement-id">
<script src="https://script.sheetsu.com/"></script>
<script>
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\nchecking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\nid found");
}
else{
document.body.append('\nid not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
}
else {
document.body.append('\ninvalid id');
}
}
</script>
this code ^^ want to inster in Wordpress plugin JS
which excutive in http://www.flacement.com/jobssearch/iffco-tokio-job-in-jharsuguda/
i want it when some one apply [apply text field 1
in flacement ID it should validate from JS API if found then procedd or if not then invalide as first code. code is ready but i am confuse where to instert in follwing so it start working
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
(function($){
$.fn.filterFind = function(selector) {
return this.find('*') // Take the current selection and find all descendants,
.addBack() // add the original selection back to the set
.filter(selector); // and filter by the selector.
};
$.fn.svgDraw = function(progress) {
this.filterFind('path').each(function() {
var pathLength = this.getTotalLength();
$(this).css('strokeDasharray', pathLength + ' ' + pathLength);
$(this).css('strokeDashoffset', pathLength * ((1 - progress)).clamp(0, 1));
});
return this;
};
$(document).ready(function(){
if( $('.jobs-modal').length ){
setTimeout(function(){
$('.jobs-modal').removeClass('hide');
}, 500);
$('.jp-apply-button').click(function(e){
e.preventDefault();
$('body').addClass('jobs-modal-open');
$('.jobs-modal').addClass('open');
});
$('.jobs-modal .modal-close').click(function(e){
e.preventDefault();
$(this).parents('.jobs-modal').removeClass('open');
$('body').removeClass('jobs-modal-open');
});
$('.jobs-modal-content').each(function(k){
$(this).find( '.inputfile' ).each(function(k){
var label = this.nextElementSibling;
var labelVal = label.innerHTML;
$(this).change(function(e){
var fileName = '';
if( this.files && this.files.length > 2 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
label.querySelector( 'span' ).innerHTML = fileName;
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}else{
label.innerHTML = labelVal;
}
});
$(this).focus(function(){ $(this).addClass('has-focus') });
$(this).blur(function(){ $(this).removeClass('has-focus') });
});
});
if( $('.choose_file_multi_add').length ){
var i = 1;
$('.choose_file_multi_add').click(function(e){
e.preventDefault();
var key_id = $(this).data('key');
var parent = $(this).parents('.modal-input-fileinput');
var input = $('#file-input-tpl-'+key_id).html();
var label = $('#file-label-tpl-'+key_id).html();
var id = key_id + '-'+i;
var key = key_id + '-key-'+i;
input = input.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
input = input.replace( '{nr}', i ).replace( '{nr}', i ).replace( '{nr}', i );
input = input.replace( '{key}', key ).replace( '{key}', key ).replace( '{key}', key );
label = label.replace( '{id}', id ).replace( '{id}', id ).replace( '{id}', id );
$(input).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
$(label).insertBefore( $('#'+key_id+' .choose_file_multi_add') );
//parent.prepend( input );
//parent.prepend( label );
$('#'+id).change(function(e){
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName ){
$('#label-'+id).find('span.name').text( fileName );
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) + 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
}
});
$('.choose_file_multi .remove').click(function(e){
e.preventDefault();
var id = $(this).parents('.choose_file_multi').attr('id');
id = id.replace('label-', 'jobgroup-');
var num = $(this).parents('.modal-input-fileinput').attr('data-files');
num = Number(num) - 1;
$(this).parents('.modal-input-fileinput').attr('data-files', num);
$('.'+id).remove();
recalculateInputs();
return false;
});
$('#'+id).click();
recalculateInputs();
i++;
});
}
function recalculateInputs(){
if( $('.modal-input-fileinput.multiple .modal-input-multifile').length == 0 ){
$('.disabled-file-placeholder').addClass('input-reqired');
}else{
$('.disabled-file-placeholder').removeClass('input-reqired');
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
var sending_form = false;
$('.progress-button .progress-circle').svgDraw(0);
$("form#jobs-modal-form").submit(function(e){
e.preventDefault();
var self = this;
var toreturn = true;
$('#jobs-modal-form .input-reqired').each(function(){
var value = $(this).val();
var is_checked = false;
if( $(this).hasClass('input-job_email') ){
if( value == '' || !validateEmail(value) ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-checkbox') ){
var checkboxes_checked = 0;
$(this).parents('.checkbox_field').find('input[type="checkbox"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else if( $(this).hasClass('modal-input-radio') ){
var checkboxes_checked = 0;
$(this).parents('.radio_field').find('input[type="radio"]').each(function(){
var checked = $(this).prop('checked');
if( checked == true ){
checkboxes_checked++;
}
});
if( checkboxes_checked == 0 ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}else{
if( value == '' ){
$(this).addClass('alert').parents('.jobs-modal-input').addClass('alert');
toreturn = false;
}else{
$(this).removeClass('alert').parents('.jobs-modal-input').removeClass('alert');
}
}
});
var input = document.getElementById('input-text_flacement-id');
var is_focused = false;
input.onfocus = function () {
is_focused = true;
}
input.onblur = function () {
if (is_focused) {
is_focused = false;
check_id(input.value);
}
}
function check_id(id) {
if (id.match(/\d{4}-\d{4}-\d{4}/)) {
document.body.append("\n checking...");
function successFunc(data) {
var row = data.filter((row)=>row['adhar_no'] == id)
if(row.length){
document.body.append("\n id found");
}
else{
document.body.append('\n id not found');
}
}
// Get all rows where column 'adhar_no' is '3894-8873-7149'
var searchQuery = {
status: 'active',
};
Sheetsu.read("https://sheetsu.com/apis/v1.0dh/dd98887de543/", {
search: searchQuery
}, successFunc);
} else {
document.body.append('\n invalid id');
}
}
if( toreturn && sending_form == false ){
/*
var progressBTN = $(self).find('.progress-button');
progressBTN.addClass('loading');
var progressCRCL = $(self).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
progressCRCL.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
}
}, 200);
*/
sending_form = true;
$('.job-submit').hide();
$('.jobs-sending').show();
var formData = new FormData($("form#jobs-modal-form")[0]);
$.ajax({
type: 'POST',
url: jpsd.ajaxurl,
data: formData,
processData: false,
contentType: false,
success: function (data) {
//clearInterval(intervalId);
//progressCRCL.svgDraw(1);
// Clear all smaces and newlines that can happen on response on some servers
data = data.replace(/\s/g, "");
if( data == 'ok' ){
//setTimeout(function(){
// $(self).find('.progress-button').addClass('success');
//}, 500);
//setTimeout(function(){
$(self).slideUp();
$('#job-apply-confirmation').slideDown();
//}, 1000);
}else{
//setTimeout(function(){
// $(self).find('.progress-button').addClass('error');
//}, 500);
//setTimeout(function(){
$('.jobs-sending').hide();
//}, 1000);
}
return false;
},
});
return false;
}
return false;
});
/*
$('.progress-button').on('click', function() {
var $button = $(this);
$(this).addClass('loading');
var $progress = $(this).find('.progress-circle');
var progress = 0;
var intervalId = setInterval(function() {
progress += Math.random() * 0.5;
$progress.svgDraw(progress);
if(progress >= 1) {
clearInterval(intervalId);
//console.log("cleared interval");
$button.removeClass('loading');
if($button.attr('data-result') == "true") {
$button.addClass('success');
}
else {
$button.addClass('error');
}
}
}, 300);
// Now that we finished, unbind
$(this).off('click');
});
*/
} // end .jobs-modal length
});
})(jQuery);

javascript add and delete section of html dynamically

I am trying to add and delete sections of HTML on the click of Add or delete button. The first 3 times I click the add button it adds more sections as expected and deletes the section as well when delete is clicked. But the problem is when I delete any row after that the AddMore Rows function doesn't work and no more rows are added.
Here is the code for Adding more rows
var hasHsa3 = false;
var hasHsa4 = false;
var hasHsa5 = false;
function addMoreRows() {
// console.log("A: "+hasHsa3 + " " + hasHsa4 + " " + hasHsa5);
if(!hasHsa3 && !hasHsa4 && !hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(hasHsa3 && !hasHsa4 && !hasHsa5)
{
hsaNum = 4;
hasHsa4 = true;
}
else if(hasHsa3 && hasHsa4 && !hasHsa5)
{
hsaNum = 5;
hasHsa5 = true;
console.log(hsaNum);
$("#addMore_1").attr("disabled", true);
}
else if(!hasHsa3 && hasHsa4 && hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(!hasHsa3 && hasHsa4 && !hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(!hasHsa3 && !hasHsa4 && hasHsa5)
{
hsaNum = 3;
hasHsa3 = true;
}
else if(hasHsa3 && !hasHsa4 && hasHsa5)
{
hsaNum = 4;
hasHsa4 = true;
}
else if(hasHsa3 && hasHsa4 && hasHsa5)
{
$("#addMore_1").attr("disabled", true);
// document.getElementById("addMore_1").disabled = true;
console.log("button is disabled");
}
console.log("B: "+hasHsa3 + " " + hasHsa4 + " " + hasHsa5 + "\n");
hsaBlock ++;
hsaIds.push(hsaNum);
Here is the function for deleting the rows once Delete button is clicked.
function removeRow(removeNum,hsaNum)
{
// Remove from array
var index = hsaIds.indexOf(hsaNum);
if (index > -1) {
hsaIds.splice(index, 1);
if(hsaNum == 3)
{
hasHsa3 = false;
}
else if(hsaNum == 4)
{
hasHsa4 = false;
}
else if(hsaNum == 5)
{
hasHsa5 = false;
}
}
updateHSATable();
$('.hsaBlock'+removeNum).remove();
};
I don't know what your actual code so from what I understood I think you try to do something like below. For adding element I use appendChild() and for deleting element I used removeChild(). hope this helps.
function add(){
var node = document.createElement("LI");
var len = document.querySelectorAll("ul li")
var textnode = document.createTextNode(len.length+1);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
function delete1(){
var len = document.querySelectorAll("ul li");
if(len.length>0){
len[0].parentElement.removeChild(len[len.length-1]);
}
}
<button onclick="add()">Add</button>
<button onclick="delete1()">Delete</button>
<ul id="myList">
<li>1</li>
<li>2</li>
</ul>

How to delete object in array using localstorage?

I have to delete object in array and it should be deleted from localstorage. I am trying to delete it by using splice method but not actually getting how to use it.
Folloeing is my code which i have tried-
var details = [];
function addEntry() {
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
var srno = document.getElementById("txtpid").value;
var name = document.getElementById("txtpname").value;
var dob = document.getElementById("txtpdob").value;
var email = document.getElementById("txtpemail").value;
var address = document.getElementById("txtpaddr").value;
var contact = document.getElementById("txtpmobile").value;
var obbbj = {
txtpid: srno,
txtpname: name,
txtpdob: dob,
txtpemail: email,
txtpaddr: address,
txtpmobile: contact
};
localStorage.setItem("details", JSON.stringify(obbbj));
existingEntries.push(obbbj);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
showEntry();
console.log(existingEntries);
//location.reload();
}
function showEntry() {
var messageBox = document.getElementById("display");
messageBox.value = "";
document.getElementById("txtpid").value = "";
document.getElementById("txtpname").value = "";
document.getElementById("txtpdob").value = "";
document.getElementById("txtpemail").value = "";
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpmobile").value = "";
var render = "<table border='1'>";
render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";
var allEntriesoo = {};
var detailsOOO = {};
for (i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var person = localStorage.getItem(key);
if (key == 'allEntries')
allEntriesoo = JSON.parse(person);
if (key == 'details')
detailsOOO = JSON.parse(person);
var data = JSON.parse(person);
}
for (var key in allEntriesoo) {
console.error(allEntriesoo[key])
render += "<tr><td>" + allEntriesoo[key].txtpid + "</td><td>" + allEntriesoo[key].txtpname + " </td>";
render += "<td>" + allEntriesoo[key].txtpdob + "</td>";
render += "<td>" + allEntriesoo[key].txtpemail + "</td>";
render += "<td>" + allEntriesoo[key].txtpaddr + "</td>";
render += "<td>" + allEntriesoo[key].txtpmobile + "</td>";
render += "<td><input type='button' value='Delete' onClick='return deleteEntry(" + i + ")'></td>";
render += "<td><input type='button' value='Edit' onClick='return editInfo(" + i + ")'></td></tr>";
}
render += "</table>";
display.innerHTML = render;
}
function nameVal() {
document.getElementById("txtpname").focus();
var n = document.getElementById("txtpname").value;
var r;
var letters = /^[a-zA-Z]+$/;
if (n == null || n == "") {
alert("please enter user name");
return null;
n.focus();
} else {
if (n.match(letters) && n != "") {
r = ValidateEmail();
return r;
} else {
alert("please enter alphabates");
document.getElementById("txtpname").value = "";
document.getElementById("txtpname").focus();
return null;
}
}
}
function ValidateEmail() {
var uemail = document.getElementById("txtpemail").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
document.getElementById("txtpemail").value = "";
document.getElementById("txtpemail").focus();
return null;
}
}
function alphanumeric() {
var uadd = document.getElementById("txtpaddr").value;
var letters = /^[0-9a-zA-Z]+$/;
if (uadd == null || uadd == "") {
alert("plz enter address");
uadd.focus();
} else {
if (uadd.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpaddr").focus();
return false;
}
}
}
function cntVal() {
var n = document.getElementById("txtpmobile").value;
var r1;
var letters = /^\d{10}$/;
if (n !== null || n !== "") {
if (n.match(letters)) {
r1 = alphanumeric();
return r1;
} else {
alert("please enter contact number");
document.getElementById("txtpmobile").value = "";
document.getElementById("txtpmobile").focus();
return null;
}
} else {
alert("please enter contact Number");
return null;
n.focus();
}
}
function deleteEntry(id) {
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') JSON.parse(localStorage.getItem('allEntries')): [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index = i;
break;
}
}
if (index === undefined) return
entry.splice(index, 1);
localStorage.setItem('entry', JSON.stringify(entry));
}
function clearstorage() {
localStorage.clear();
window.location.reload();
}
window.onload = function() {
showEntry();
};
In your deleteEntry function you are setting a new item in localStorage called 'entry'. So you are not setting 'allEntries' and thats probably why its showing up like that, 'allEntries' has not been updated. So just set all entries again. localStorage.setItem('allEntries', JSON.stringify(entry));
You are also missing the '?' for you variable 'entry'...
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; <-- it should look like this.
Its the same as an 'if else statement'
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index=i;
break;
}
}
if(index === undefined) return
entry.splice(index, 1);
localStorage.setItem('allEntries', JSON.stringify(entry)); <--- like this
}
You can use create a temporary object and then replace it in localStorage.
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = JSON.parse(localStorage.getItem('allEntries'));
var temp= [];
for (var i = 0; i < entry.length; i++) {
if (entry[i].id !== id) {
temp.push(entry[i]);
}
}
localStorage.setItem('entry', JSON.stringify(temp));
}

Null error is coming document.getElementByid("dthchannel" + [i] is null)

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;
You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Categories

Resources