Conflict with counting filled fields with input hints. Any work around? - javascript

I have a script to count the number of fields that are filled. Works great. But I discovered the script only counts the fields that DO NOT have input hints. Is there any work around?
http://jsbin.com/oguzaj/4
SCRIPT TO COUNT FIELDS:
$(document).ready(function () {
(function ($) {
$('#form_register').on('keyup change', function () {
var number = 0;
$(this).find('input, textarea').each(function () {
if (this.value !== '') {
$('.input_count').val(number++);
}
});
});
})(jQuery);
});
SCRIPT FOR INPUT HINTS:
(function ($) {
$.fn.hint = function (blurClass) {
if (!blurClass) {
blurClass = 'blur';
}
return this.each(function () {
var $input = $(this),
title = $input.attr('title'),
$form = $(this.form),
$win = $(window);
function remove() {
if ($input.val() === title && $input.hasClass(blurClass)) {
$input.val('').removeClass(blurClass);
}
}
if (title) {
$input.blur(function () {
if (this.value === '') {
$input.val(title).addClass(blurClass);
}
}).focus(remove).blur();
$form.submit(remove);
$win.unload(remove);
}
});
};
})(jQuery);
$(function () {
$('input[title!=""]').hint();
$('textarea[title!=""]').hint();
});

$(document).ready(function() {
$('#form_register').on('keyup change', function() {
var number = 0;
$(this).find('input, textarea').each(function() {
if ($(this).val() && !$(this).hasClass('blur')) {
$('.input_count').val(number++);
}
});
});
});
Edit:
If you've got an button which fills one field you'll need to add this to the button.
$(buttonSelector).on('click', function() {
var number = 0;
$('#form_register').find('input, textarea').each(function() {
if ($(this).val() && !$(this).hasClass('blur')) {
$('.input_count').val(number++);
}
});
});

Related

Improve my Jquery code to hide and show elements

I am new to Jquery and learning. I wrote some script, but I know its not efficient. Trying to follow DRY principles. Can someone please make this look nicer...it works fine, but i dont like it.
It works, just not efficient code.
<script>
$(document).ready(function () {
var val = $('#id_ocftype').val();
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
$('#id_ocftype').change(function () {
var val = $(this).val();
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
});
});
</script>
Since the conditional statement inside the jquery code is same. You can wrap it into single javascript function and call it whereever it is needed.
<script>
$(document).ready(function () {
const showAndHide = (val) => {
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
}
var val = $('#id_ocftype').val();
showAndHide(val);
$('#id_ocftype').change(function () {
var val = $(this).val();
showAndHide(val);
});
});
</script>
The elements to show or hide are always the same, so you can put them all into a single variable and reference that variable.
$(document).ready(function () {
const elms = $('#div_id_date, #div_id_amount, #div_id_signedby');
const onChange = () => {
const val = $('#id_ocftype').val();
if (val <= 3) {
elms.hide();
} else {
elms.show();
};
};
onChange();
$('#id_ocftype').change(onChange);
});
You can look into .toggleClass.
It allows you to specify when to add/ remove class.
function handleVisibility() {
var val = $('#id_ocftype').val();
const hide = val <= 3
$('#div_id_date').toggleClass('hide', hide)
$('#div_id_amount').toggleClass('hide', hide)
$('#div_id_signedby').toggleClass('hide', hide)
}
$(document).ready(function() {
$('#id_ocftype').change(handleVivibility);
handleVisibility()
});
you can create a common function
<script>
$(document).ready(function () {
var val = $('#id_ocftype').val();
const hideEl = () => {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
const showEl = () => {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
}
if (val <= 3) {
hideEl();
}
else {
showEl();
};
$('#id_ocftype').change(function () {
var val = $(this).val();
if (val <= 3) {
hideEl();
}
else {
showEl();
};
});
});
</script>
also you can use toggle
$("button").click(() => {
$("#test").toggle();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">test</div>
<button>Hide/Show</button>

Code does not reflect updates to category name in each text box

the code does not allow me to update/edit the name in each text box. I've reviewed the code several times but could not find any errors. Grateful for any help. Thanks.
THE HTML
/*
* Confirm category deletion
*/
$("body").on("click", "a.delete", function () {
if (!confirm("Confirm page deletion")) return false;
});
/////////////////////////////////////////////////////////
/*
* Rename Category
*/
var originalTextBoxValue;
$("table#pages input.text-box").dblclick(function () {
originalTextBoxValue = $(this).val();
$(this).attr("readonly", false);
});
$("table#pages input.text-box").keyup(function (e) {
if (e.keyCode == 13) {
$(this).blur();
}
});
$("table#pages input.text-box").blur(function () {
var $this = $(this);
var ajaxdiv = $this.parent().find(".ajaxdivtd");
var newCatName = $this.val();
var id = $this.parent().parent.attr("id").substring(3);
var url = "/admin/shop/RenameCategory";
if (newCatName.length < 2) {
alert("Category name must be at least 2 characters long.");
$this.attr("readonly", true);
return false;
}
$.post(url, { newCatName: newCatName, id: id }, function (data) {
var response = data.trim();
if (response == "titletaken") {
$this.val(originalTextBoxValue);
ajaxdiv.html("<span class='alert alert-danger'>That title
is taken!</span>").show();
} else {
ajaxdiv.html("<span class='alert alert-success'>The category name has been changed!</span>").show();
}
setTimeout(function () {
ajaxdiv.fadeOut("fast", function () {
ajaxdiv.html("");
});
}, 2000);
}).done(function () {
$this.attr("readonly", true);
});
});
///////////////////////////////////////////
});
</script>
\\\

How to add validation so that the form does not accept blank spaces?

$scope.addTodo = function ()
{
$scope.todos.push({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
};
try this:
$scope.addTodo = function () {
if ($scope.formTodoText.replace(/\s/g,'').length > 0) {
$scope.todos.push({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
}
};
Remove all spaces in the value and check if there's anything left.
I would do like this:
`$('#MyForm input').blur(function()
{
if( !$(this).val() && $(this).val() != "" ) {
$(this).parents('p').addClass('warning');
}
});`

Reset jquery setTimeout after second Click on Button

I got a problem that wastes more and more time. Now I want to ask you guys to help me out. I really think it's not a big thing but I can't find the solution:
I have two code snippets, both really similar:
$(function () {
$('.plus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal)) {
$qty.val(currentVal + 1);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
var timeout = setTimeout(function () {
$.overlay.open();
form.submit();
}, 2000);
});
}
});
$('.minus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal) && currentVal > 0) {
$qty.val(currentVal - 1);
window.clearTimeout(timeout);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
$.overlay.open({
closeOnClick: false
});
form.submit();
}, 2000);
});
}
});
});
I just want to reset the timeout after a click on one of the buttons.
var time;
}, 2000); use this-> }, time);
$(".test").on("click", function(){
time = 0;
});

jQuery .hide(), then .show() based on text input

Using a jQuery filter example I found. Here is my live example. Here is the CodePen, (also the Fiddle if you don't like CodePen).
After typing something in the input, the boxes do realign and the numbers dissapear. However, when you delete the text you inputted, the numbers do not reappear unless you refresh the page. I tried messing around with the code below but wasn't having any luck. Thanks for you help!
$('#sortable').change(
function(){
if ($(this).val().length) {
$('#number').hide();
}
else {
$('#number').show();
}
});
Try this out:- http://jsfiddle.net/adiioo7/nYYBU/10/
JS:-
(function ($) {
jQuery.expr[':'].Contains = function (a, i, m) {
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
function listFilter(header, list) {
var form = $("<form>").attr({
"class": "filterform",
"action": "#"
}),
input = $("<input>").attr({
"class": "filterinput",
"type": "text",
});
$(form).append(input).appendTo(header);
$(input).change(function () {
var list = $("#sortable");
var filter = $(this).val();
console.log(filter.length);
if (filter.length > 0) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(".number").hide();
$(".numberstwo").hide();
} else {
console.log($(".number"));
$(".number").show();
$(".numberstwo").show();
$(list).find("a").parent().slideDown();
}
return false;
}).keyup(function () {
$(this).change();
});
}
$(function () {
listFilter($("#header"), $("#sortable"));
});
}(jQuery));
Here's updated js...
Checkout Demo Fiddle
(function ($) {
jQuery.expr[':'].Contains = function (a, i, m) {
return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};
function listFilter(header, list) {
var form = $("<form>").attr({
"class": "filterform",
"action": "#"
}),
input = $("<input>").attr({
"class": "filterinput",
"type": "text",
});
$(form).append(input).appendTo(header);
$(input).change(function () {
var filter = $(this).val();
if (filter) {
$(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
$(list).find("a:Contains(" + filter + ")").parent().slideDown();
} else {
$(list).find("li").slideDown();
}
return false;
}).keyup(function () {
$(this).change();
if ($(this).val().length) {
$('.number').hide();
} else {
$('.number').show();
}
});
}
$(function () {
listFilter($("#header"), $("#sortable"));
});
}(jQuery));
To check the entered text I normally use keyup.
Change is not triggered when the user types something but when he types and exits the box.
$('#sortable').blur(function(){
var len = $(this).val().length;
if (len) {
$('#number').hide();
}
else {
$('#number').show();
}

Categories