I am trying to create a function that auto formats the text box as the user is typing in their Canadian Postal Code.
This is my original function, but the problem is that it doesn't catch if the person writes in the wrong format.
EX. AA1 10A when it should always be in the format of A0A 0A0.
$("#tbPostalCode").on("change keyup paste", function(){
var output;
var input = $(this).val();
input = input.replace(/[^a-zA-Z0-9]/g, '');
input = input.toUpperCase();
var front = input.substr(0, 3);
var end = input.substr(3, 5);
if (front.length < 3) {
output = front;
} else if (front.length == 3 && end.length < 3) {
output = front+ " " + end;
} else if (front.length == 3 && end.length == 3) {
output = front+ " " + end;
}
$(this).val(output);
});
This is what I have been trying to make work. To basically split the string and replace the specific spots of the index according to the regEx requirements. So I am just trying to figure out how to make this work.
$("#tbPostalCode").on("change keyup paste", function(){
var output;
var input = $(this).val();
input = input.splice("");
input[1,4,6] = input.replace(/[^0-9]/g, '');
input[0,2,5] = input.replace(/[^a-zA-Z]/g,'');
input = input.toUpperCase();
var front = input.substr(0, 3);
var end = input.substr(3, 5);
if (front.length < 3) {
output = front;
} else if (front.length == 3 && end.length < 3) {
output = front+ " " + end;
} else if (front.length == 3 && end.length == 3) {
output = front+ " " + end;
}
$(this).val(output);
});
Code Block 1 Fiddle: https://jsfiddle.net/jessica_mather123/730gj842/7/
Code Block 2 Fiddle: https://jsfiddle.net/jessica_mather123/f21sx97j/
This is the RegEx I want it to follow:
[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d
Debuggex Demo
HTML5 input validation handles this pretty well across browsers. Automatically deleting input without providing notice as to what is going on makes for a confusing UI experience. Try HTML input/form validation. You can plug your regex right in there...
Related
I've seen similar questions asked on Stack Overflow regarding this topic, but I haven't seen anything specific that would help me. My issue is that I can't seem to figure out how to replace a dash in hiddenWord with a correctly guessed letter while still retaining the dashes for un-guessed letters. Here is what I have so far and I'm not even sure if it's on the right track.
<script type="text/javascript">
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
for(i = 0; i < wordChoice.length; i++){
hiddenWord = wordChoice.replace(/./g,"- ");
}
console.log(hiddenWord);
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
selectedWord();
}
console.log(myLetter);
}
</script>
I have seen some stuff with jQuery and PHP but I have to do it in javascript for class. Any help would be appreciated and if this has been addressed before please let me know.
You can check each character at the word string, compare it with the chosen character and replace it, if it is the same character.
I changed your code a bit to reflect what you are looking for.
Also make sure to lowercase all characters to make it easier for the player.
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Change character to selected one
function checkCharacter(n) {
for(i = 0; i < wordChoice.length; i++){
console.log(wordChoice[i].toLowerCase() + "==" + n);
if(wordChoice[i].toLowerCase() == n.toLowerCase()){
hiddenWord = setCharAt(hiddenWord,i,n);
}
}
console.log("[" + hiddenWord + "]");
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
hiddenWord = wordChoice.replace(/./gi,"-");
console.log(wordChoice + "[" + hiddenWord + "]");
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
if(lives == 0){
selectedWord();
lives = 6;
}else{
lives--;
}
}
console.log(myLetter);
checkCharacter(myLetter);
}
//Select a random word at start
selectedWord();
I made a JSfiddle that is working and playable:
Check it out here...
Try
hiddenWord += "- "
Instead of replace
Or
hiddenWord += wordChoice[i].replace(/./g,"- ");
Here's an example:
var word = "do this";
var displayWord = [];
for (var i = 0; i < word.length; i++) {//build array
if (word[i] === " ") {
displayWord.push(" ");
} else {
displayWord.push("-");
}
}
function update(userGuess) {//update array
for (var i = 0; i < word.length; i++) {
if (word[i] === userGuess) {
displayWord[i] = userGuess;
} else {
displayWord[i] = displayWord[i];
}
}
}
//Guess letters
update("h");
update("o");
displayWord = displayWord.join('');//convert to string
alert(displayWord);
Check out the pen - https://codepen.io/SkiZer0/pen/VbQKPx?editors=0110
EDIT: If anyone, ever need this script for some reason, i made a cleaner fully working version: https://jsfiddle.net/qmgob1d5/3/
I have a jquery script that is supposed to highlight elements in a from-to manner. It should work backwards as well.
Here is working fiddle: https://jsfiddle.net/qmgob1d5/
It works fine, until I select zero (first box) as second element. Then the var Start = Math.min(ClickOne, ClickTwo || 16); doesn't seems to work as expected. What went wrong?
Here is the script:
var FirstClick;
var ClickOne;
var ClickTwo;
$('.ColorPreview').on('click',function() {
var ColorId = $(this).attr('id');
ColorId = Number(ColorId.split('_')[1]);
if (!FirstClick) {
//reset function
for (var i = 0; i < 16; i++) {
$('#Color_' + i).removeClass('SelectColor'); }
var ClickTwo;
ClickOne = ColorId;
FirstClick = true;
}
else {
ClickTwo = ColorId;
FirstClick = false; }
console.log('ClickOne ' + ClickOne)
console.log('Clicktwo ' + ClickTwo)
var Start = Math.min(ClickOne, ClickTwo || 16);
var End = Math.max(ClickOne, ClickTwo || 0);
console.log('start ' + Start)
console.log('end ' + End)
for (var i = Start; i <= End; i++) {
$('#Color_' + i).addClass('SelectColor'); }
});
When ClickTwo is 0, the expression ClickTwo || 16 will evaluate to 16.
Try
var Start = Math.min(ClickOne, ClickTwo == null ? 16 : ClickTwo);
Or else initialize ClickTwo to 16 at the beginning of the function.
I am trying to format an <input> box using javascript / jquery.
The Goal - As the user types, add hyphens automatically after every third character.
123123123 becomes 123-123-123
I have a working code, but it is super slow and clunky. I am looking for recommendations on how to improve the code
$('#serial').keyup(function(){
$(this).val( $(this).val().trim() );
var str = $(this).val();
var newStr = str.replace(/-/g, "");
var valuesArray = newStr.split("");
var newVal = "";
while ( i = valuesArray.shift() ){
if(newVal.length === 3){
newVal += "-";
} else if (newVal.length === 7){
newVal += "-";
}
newVal += i;
}
$(this).val(newVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<label for="serial">Type something magical</label>
<input type="text" id="serial" name="serial">
Use input event istead of keyup it's very useful to track input fields changes :
$('#serial').on('input', function(){
NOTE : The code seems slow because keyup won't fire until you release the key, but you can type the next character before releasing the first.
Hope this helps.
Update :
You don't need any loop here, you can use substr to cut your string and insert the separator - and use maxlength to define the max number of charaters you want to contain your serial :
$('#serial').on('input', function()
{
var input_value = $(this).val().trim().replace(/-/g, "");
if(input_value.length > 3){
input_value = input_value.substr(0, 3) + '-' + input_value.substr(3);
}
if (input_value.length > 7){
input_value = input_value.substr(0, 7) + '-' + input_value.substr(7);
}
$(this).val(input_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="serial" name="serial" maxlength="11">
try this code, replaced inefficient regex with substring
$('#serial').input(function(){
$(this).val( $(this).val().trim() );
var str = $(this).val().trim().split( "-" ).join("");
var output = "";
while ( str.length > 3 )
{
output += str.substring(0,3) + "-";
str = str.substring(3);
}
output += str;
$(this).val(output);
});
A little further optimization
$('#serial').on('input', function() {
var str = $(this).val().trim();
var i = 3;
while (i < str.length) {
if (str.charAt(i) == '-') {
i += 4;
} else {
str = str.slice(0, i) + '-' + str.charAt(str.length-1);
}
}
$(this).val(str);
});
jsfiddle https://jsfiddle.net/h5hdvcwu/1/
I have array which length is 13 .
form has 13 simultaneous fields user can enter in any field i want that if user enter 5 or 7 or any field value then i want add validation that it's previous field value should not be empty and it should not check validation for next field.
I have used this code ...
datesId[0] = "bankNocForTorDateId";
datesId[1] = "advertisingDateShortlistingId";
datesId[2] = "torShortlistFinalizedDateId";
datesId[3] = "bankNocForShortlistDateId";
datesId[4] = "rfpDraftToBankDateId";
datesId[5] = "bankNocForRfpDateId";
datesId[6] = "rfpIssuedDateId";
datesId[7] = "proposalReciptDateTechnicalId";
datesId[8] = "evaluationFinalTechnicalDateId";
datesId[9] = "bankNocTechnicalDateId";
datesId[10] = "proposalReciptDateFinancialId";
datesId[11] = "evaluationFinalCombinedDateId";
datesId[12] = "nocBankDraftDate";
for(var i = 0; i<datesId.length ; i++ ){
if(!(document.getElementById (datesId[i]).value == "")){
for(var j =datesId[i].length-1 ;j>0 ; j-- ){
if(document.getElementById(datesId[j]).value == ""){
var message = "Please Enter "+datesLabel[j];
alert(message);
return false;
}
}
}
}
Actually i am new in Javascript...not having much idea about it.I have made this logic on the basis of java. please clearify what's basic difference.
Thanks in Advance
Done!
var datesId = []
datesId[0] = "bankNocForTorDateId";
datesId[1] = "advertisingDateShortlistingId";
datesId[2] = "torShortlistFinalizedDateId";
datesId[3] = "bankNocForShortlistDateId";
datesId[4] = "rfpDraftToBankDateId";
datesId[5] = "bankNocForRfpDateId";
datesId[6] = "rfpIssuedDateId";
datesId[7] = "proposalReciptDateTechnicalId";
datesId[8] = "evaluationFinalTechnicalDateId";
datesId[9] = "bankNocTechnicalDateId";
datesId[10] = "proposalReciptDateFinancialId";
datesId[11] = "evaluationFinalCombinedDateId";
datesId[12] = "nocBankDraftDate";
// if datesId[6] value is not blank
if (datesId[6] != ''){
// validate previous 5 field values should not be blank, but it should not check next 6 value.
for (var i = (6-5); i < 6; i ++){
console.log('validating field ' + datesId[i] + " (index=" + i + ")")
if (datesId[i] == ''){
alert('Field ' + datesId[i] + " must not be blank!")
}
}
}
I have a textarea on the page. And decide validate this element. I insert simple text and in js I check the length this element. But when I delete all text I can save without any problem. I see in firebug and in textarea I find
<ul></ul><br/>
}
// js
for(var i=0; length > i; i++){
value = textElements[i].value;
if(value == "" ||(value == "<br/>" && element.tagName == "TEXTAREA")){
full = false;
emptyElements.push(elements[i]);
} else {
empty = false;
elements[i].style.borderColor = "";
elements[i].style.border = "";
}
}
Ad HTML
<br /><div id="edit-contentFrame-form:editor" style="visibility:hidden"><textarea id="edit-contentFrame-form:editor_input" name="edit-contentFrame-form:editor_input"><h3></h3><h3></h3><h3><br/></h3><ul>
</ul></textarea></div>
I try to find existing way to resolve this problem. But nothing to find.
///EDITED
function isEmptyTextArea(){
var str = document.getElementById('edit-contentFrame-form:editor_input').value;
var regexp = new RegExp("(<+[\w]+>+)*", "g");
var matches_array_tags = str.replace(regexp, '');
if(matches_array_tags.length == 0){
return true;
}
return false;
}
You can use regex to replace and strip all the "markup symbols" tags from the textarea if you don't want people to be able to input html.
var txtarea = document.getElementById('txtarea');
if(escape(txtarea.value) === '')
// textarea is empty
Not including whitespaces:
if(escape(txtarea.value.trim()) === '')
// textarea is empty (not including whitespaces)
I resolve my problem with next js function
function isCompleteTagContent(str){
var re= /<\S[^><]*>/g;
var matches_array_tags = str.replace(re, "");
if(matches_array_tags.trim().length == 0){
return true;
}
return false;
}