Jquery logics confusion - javascript

I want to make a bit of code that will check the value of an input box, count how many letters there are in the input box and if the value is divisable by 4 then to insert a -
Its so when the user is entering a code, in automatically inserts - after every 4 letters :)
Thanks

$("input").keyup(function () {
if(this.value.replace(/-/g, "").length % 4 == 0) {
this.value += "-";
}
});

This seems to work in the way you want
$(document).ready(function() {
$("#search").keyup(function(){
var stringFull = $(this).val();
if(stringFull.replace(/-/g, "").length % 4 == 0 ){
$(this).val(stringFull+"-");
}
});
});

Related

Form calculator based on input values

I am working on a Cardio Test calculator which calculates heart attack risk. I want to get score based value for each input. The results logic is already working, I just need to get result score value. See the code below.
<script>
$(document).ready(function() {
$("#female").change(function() {
if ($(this).is(":checked")) {
$("#femaleage").show();
$("#maleage").hide();
}
});
$("#male").change(function() {
if ($(this).is(":checked")) {
$("#maleage").show();
$("#femaleage").hide();
}
});
$( "#cardio__test" ).submit(function( event ) {
event.preventDefault();
if ($("#score").val() <= 3) {
$(".risk__score.low__risk").show();
}
if ($("#score").val() >= 4 && $("#score").val() <= 6) {
$(".risk__score.moderate__risk").show();
}
if ($("#score").val() >= 7) {
$(".risk__score.high__risk").show();
}
if ($("#maleage").val() >= 70) {
$("#score").val() + 8;
}
$(this).hide();
});
});
</script>
Here's a link!
I tested out your codepen and I found out the value of your score is a string type instead of int as I tested using parseInt() and typeof... and the result string value is blank (maybe i changed some code in the codepen during testing) How do you check the value of the score and do you get it as a number? Anyway, to print out the result value you can do it in many ways such as
adding a new div in your results div and print the results inside the div
$(".(new div class name) h3").text($("#score").val());
or simply alert the results
alert($("#score").val());
you can simply use
var scoreValue = $("#score").val();

How to edit the correct phone number in my script?

I have this sample:
link
CODE HTML:
<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input" value="" maxlength="10">
CODE CSS:
.invalid{
border:1px solid red !important;
}
.valid{
border:1px solid green !important;
}
CODE JS:
function phoneFormat(){
$( "._phone" ).on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
var testt=$(this).val().match(text);
if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
{
$(this).removeClass('valid').addClass('invalid');
}
else{
$(this).removeClass('invalid').addClass('valid');
}
$(this).val(text);
});
}
$( "#primary_phone" ).blur(function() {
phoneFormat();
});
I put a script that arranges text format
for example, we can add this number :
1234567890
After calling script appears next form (what is right)
(123) 456-7890
The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Just remove all special characters when you focus in on the input box:
$("#primary_phone").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,'');
$(this).val(value);
});
Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]
function keyCode(keyCode) {
if (alwaysAllowed.indexOf(keyCode) !== -1) {
return "allowed";
} else if (keyCode >= 48 && keyCode <= 57) {
// 0 - 9
return "number";
} else {
// any other character
return false;
}
}
function countNumbers(text) {
// return the number of characters [0-9] in the string "text"
var counter = 0;
for (var i = 0; i < text.length; i++) {
if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
counter++;
}
}
return counter;
}
$primaryPhone.on("keypress", function () {
var keyCodeEvaluation = keyCode(event.keyCode);
if (keyCodeEvaluation === false) {
event.preventDefault();
} else if (keyCodeEvaluation === "number") {
var value = this.value,
counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
//
if (counter === 0 && countNumbers(value) > 9) {
event.preventDefault();
}
}
});
This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.

Don't submit email form unless minimum total is reached

I apologize in advance for my ignorance... We have an order form where we'd like the users to order at least 6 items (not each necessarily but sum/combination of items that equals 6 or more). I have it totaling the quantities up but not a working onclick/onsubmit function that can alert you to reach the minimum order quantity before submitting the form. Any ideas? Thanks in advance. In lieu of posting all the actual code i'm hoping this is enough info to go on. If not I can create some dummy text to apply if necessary.
Add a class to the inputs you want to tally:
<input name="LEDname" type="text" id="v8" class="tallyable" />
Then scrub and tally them up on keyup, then enable or disable submit if value is >= 6:
$('.tallyable').on('keyup', function () {
var total = getTotal();
$('#orderCount').html(total);
enableOrDisableSubmit(total);
});
function getTotal(){
var total = 0;
$('.tallyable').each(function(){
if ($(this).val().trim().length > 0) {
var currentVal = isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
total += currentVal;
$(this).val(currentVal);
}
});
return total;
}
function enableOrDisableSubmit(val) {
if (val >= 6) {
$('#submit').removeAttr('disabled');
} else {
$('#submit').attr('disabled', 'disabled');
}
}
Here is a fiddle

Remove only second character in jQuery

$('input').keypress(function(e){
if(($(this).val().split('a').length - 1) > 0){
console.log($('input').val());
$('input').val($('input').val().replace('a', ''));
}
})
jsfiddle: http://jsfiddle.net/Ht8rU/
I want have only one "a" in input. I check if length a > 1 and next remove "a" from input, but this not working good. I would like remove only second a from this input. One "a" is allow.
Edit: Oh I see now... If you want to keep only the first a you can try this:
$('input').keypress(function(e) {
var key = String.fromCharCode(e.which);
if (/a/i.test(key) && /a+/i.test(this.value)) {
e.preventDefault();
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/6/
You have to check if the current letter being typed is a:
if (String.fromCharCode(e.which) == 'a')
But here's a simplified version. You don't need to use val() if you can use value, specially because it makes your code cleaner. Also you might want to check for A or a so a regex might be a better option. Here's the code:
$('input').keypress(function(e) {
var A = /a/gi,
letter = String.fromCharCode(e.which);
if (A.test(letter)) {
$(this).val(this.value.replace(A,''));
}
});
Demo: http://jsfiddle.net/elclanrs/Ht8rU/3/
I suggest using preventDefault to stop the key from being pressed:
$('input').keypress(function(e) {
if (e.keyCode === 97 && $(this).val().split('a').length > 1) {
e.preventDefault();
}
});
JSFiddle
This code may seem long and without any usefulness, but it works.
$('input').keyup(function(e) {
var e = $(this),
val = e.val(),
aPos = val.indexOf('a'),
spl1 = val.substring(0, aPos + 1),
spl2 = val.substring(aPos, val.length).replace(/a/gi, ''),
v = spl1 + spl2;
e.val(v);
});
Here is a working JSFiddle of this.
I would try something like this. Not sure how well supported is the input event currently, though.
(function() {
var elem = $('input');
var value = elem.val();
elem.bind("input propertychange", function(e) {
if (elem.val().split('a').length - 1 > 1)
elem.val(value);
else
value = elem.val();
});
})();
http://jsfiddle.net/Ht8rU/8/
When the user presses 'a' or 'A', you can check if there is one 'a' or 'A' already present, if there is one already then you don't add it to the input.
$('input').keypress(function(e){
if ((e.keyCode === 65 || e.keyCode === 97) & $(this).val().match(/a/gi) !== null) e.preventDefault();
})
Updated jsFiddle
Here's a modified version of your fiddle that works: http://jsfiddle.net/orlenko/zmebS/2/
$('input').keypress(function(e){
var that = $(this);
var parts = that.val().split('a');
if (parts.length > 2) {
parts.splice(1, 0, 'a');
that.val(parts.join(''));
} else {
// no need to replace
}
})
Note that we only replace the contents of the input if we have to - otherwise, constant rewriting of the contents will make it impossible to type in the midle or at the beginning of the text.
If you want to further improve it and make it possible to type at the beginning even when we are replacing the contents, check out this question about detecting and restoring selection: How to get selected text/caret position of an input that doesn't have focus?

How do I target an input when 5 characters have been entered?

What I want to do is take an input for a zipcode and in jQuery if input#zip has 5 characters then function. Also same for a list box when the user chooses one of the choices, might be simpler?
$('#zip-input').keyup(function(){
if($(this).val().length == 5) {
//do your stuff here
}
})
For your zip scenario:
$("#zip").keypress(function() {
if ($(this).val() && $(this).val().length == 5) {
someFunction($(this).val());
}
});
For your listbox scenario:
$("#listbox").change(function() {
if ($(this).val()) {
someFunction($(this).val());
}
});
You might want to use a keyup event handler for instance.
$('input').bind('keyup', function(){
if($(this).val().length >= 5){
alert('5 characters');
return false;
}
});
Perhaps use the .change(). Each time change is fired get the length of the input and, if its 5 or more, run your code.

Categories

Resources