avoid delete space while wrong typing - javascript

I have a code in JQuery to validate a name with format letters and spaces only. The problem is, when I type a wrong format next to space, the space disappeared and the cursor is next to last letter. This is my code:
<script>
$('input[name="name"]').on('keyup', function(e) {
var re = /^[a-zA-Z\s]+$/.test(this.value);
if(!re) {
this.value = this.value.replace(/[0-9\W]+$/, '');
$('#err_name').show();
} else {
$('#err_name').hide();
}
})
</script>

Please replace this line
this.value = this.value.replace(/[0-9\W]+$/, '');
to this line
this.value = this.value.replace(/[0-9]+$/, '');
Because if you will use \w it replace space also.

Related

HTML5 JavaScript, How can I clear my input field every time I hit the spacebar so there is only ever max 1 word showing in the input field?

I have 2 input fields where the second is a copy of the first using this code.
window.onload = function() {
var src = document.getElementById("paragraph-text"),
dst = document.getElementById("copy");
src.addEventListener('input', function() {
dst.value = src.value;
});
};
For every key I press when filling the first field, it shows up in the second filed. However, I'd like to have only 1 word show up at a time in the second (copy) field, meaning I want the field to clear every time I hit the spacebar (or keycode 32). Could someone help me out please.
It probably doesn't matter but here are the 2 html fields:
<input type="text" id="paragraph-text" name="paragraph-text" placeholder="type here to begin...">
<input type="text" id="copy" name="copy">
I tried this in the JavaScript:
window.onload = function() {
var src = document.getElementById("paragraph-text"),
dst = document.getElementById("copy");
src.addEventListener('input', function() {
dst.value = src.value;
window.onkeydown = function(event) {
if (event.keyCode == 32) {
src.value += ' '
dst.value = ''
if(event.preventDefault) event.preventDefault();
return false;
}
}
});
};
and it works except for the fact that when I type the next word, the original word is still there, so if i type a long sentence, the copy field will still contain all the words from the paragraph-text field, even though it does clear temporarily with every spacebar press. I would like it to stay cleared so the next word is alone, and so on. There should only ever be 1 word or nothing in the copy field.
I'm not a 100% sure I understand what you actually want, but I think this might be what you're after?
window.onload = function() {
var src = document.getElementById("paragraph-text"),
dst = document.getElementById("copy");
src.addEventListener('input', function() {
dst.value = src.value.split(' ').pop();
});
};
The first input might contain a word, or a sentence containing multiple words separated by whitespaces.
The second input should contain the last word from the first input.
We convert the contents of the first input to an array of words using split(' ') and then pop() to return the last item.

Javascript: Cannot move back in HTML Input

I have a form where a user can enter a URL but I wanted to have it automatically remove spaces.
To do this I have the following jQuery function:
$('#URL').on('change keyup', function() {
var sanitized = $(this).val().replace(' ', '');
$(this).val(sanitized);
});
But the problem with this code is that you cannot use the arrow keys to move in the input. i.e. if I type in http://oogle.com and I want to use arrow keys to fix my spelling mistake, it will automatically keep the cursor on the very last character. On top of this, I cannot use Ctrl+A to select all the text.
Is there a way to have jQuery/Javascript automatically remove spaces while still being able to move around the input or select it all?
Here is my jsFiddle showing my issue.
Use keypress instead of keyup, so only characters are caught. In this case, discard a space if it is pressed.
Also check for a paste event, and use a regular expression to replace all spaces. Change the value within a timeout in order to capture the pasted value:
$('#URL')
.on('keypress', function(e) {
if(e.which === 32) return false;
})
.on('paste', function() {
$self= $(this);
setTimeout(function() {
$self.val($self.val().replace(/\s/g, ''));
});
});
Fiddle
Fiddle
You can:
Record the cursor position
Execute your original code
Then restore the cursor position
Update:
Make sure to change your .replace to .replace(/\ /g, "")
Update 2 (cursor position):
This fixes the cursor position when inserting spaces.
For example copy and pasting the following will now work with any cursor position:
341 10365
34 1 1 03 65
First you need to get the string to the left of the cursor:
var leftString = $(this).val().substring(0, start);
Then you need to count the spaces in that string:
var leftSpaces = (leftString.match(/ /g) || []).length;
Then subtract leftSpaces from the start and end variables.
Javascript
$('#URL').on('change keyup', function() {
// Store cursor position
var start = this.selectionStart;
var end = this.selectionEnd;
// Check for newly inserted spaces
var leftString = $(this).val().substring(0, start);
var leftSpaces = (leftString.match(/ /g) || []).length;
newStart = start - leftSpaces;
newEnd = end - leftSpaces;
// Original Code
var sanitized = $(this).val().replace(/\ /g, "");
$(this).val(sanitized);
// Place cursor in correct position
this.setSelectionRange(newStart, newEnd);
});
Another option would be to add a delay after the keyup event
$('#URL').on('change keyup', function() {
delay(function(){
var sanitized = $('#URL').val().replace(' ', '');
$('#URL').val(sanitized);
}, 1000 );
});
http://jsfiddle.net/xv2e9bLe/
The usual way to adjust user input in a form is done when user finish their input or edit. It's pretty awkward to adjust user input on the fly. So, the onBlur event usually the best event to catch and sanitize a form input.
Based on the answer from adriancarriger, I use the 'blur' event which catch the user input after the user finish the input and do something else.
$('#URL').on('blur', function() {
var start = this.selectionStart,
end = this.selectionEnd;
var sanitized = $(this).val().replace(/\ /g, "");
$(this).val(sanitized);
this.setSelectionRange(start, end);
});
This should work well. If you have a real form submit, you can also catch the user input at onSubmit event of the form as well. Note that onSubmit happens at the form object, not the input object.

Disable button if a string is matched from a line in jquery

I'm trying to build a website using jquery-1.10.2 where I want to block css related strings like <style>, <link> etc. I want to disable the submit button if any of those strings match. So far I've managed to block them using .keyup() function but if I write more than those tags like <link rel="stylesheet" href="css/bootstrap.min.css"> then it won't work. Here are my codes,
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
if (input == "<style>" || input == "</style>" || input == "<link>") {
$('#deactivedivEditor-2').attr("disabled", "disabled");
}else{
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
JSFiddle Demo
How can I disable the button if any of those strings match from any lines? Need this help badly. Thanks.
You can use regex to check if the text contains certain pattern.
$(document).ready(function () {
var regex = /<\/?style.*?>|<link.*?>/;
$('#inputdivEditor-2').keyup(function () {
var val = $(this).val();
$('#deactivedivEditor-2').prop('disabled', regex.test(val));
});
});
Demo: http://fiddle.jshell.net/tusharj/52xd3s11/
Regex
/ : Delimiters of regex
\/?: Matches 0 or 1 /
.*?: Matches any character any no. of times
|: OR in regex
You can use the following regex to match those strings.
var regex = /<(style|link)>/;
To disable update when the elements are present. That however wouldn't solve all cases. If someone wants he can bypass the regex by writing < style > or with using different encoding and so on.
In my opinion a better option is to look at the content from a browser's perspective. In other words take the input and make an element out of it:
var dummyElement = $('<div></div>');
dummyElement.html(input); //contents of the input field
if(dummyElement.find('style').length > 0) {
//you get the point
}
..because there's that one question on SO, which explains why not parse HTML with regexes..
RegEx match open tags except XHTML self-contained tags
Just use regex to check anything between < > like below:
DEMO
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var input = $(this).val();
var regex=/<*>/;
if (regex.test(input)) {
$('#deactivedivEditor-2').attr("disabled", "disabled");
} else {
$('#deactivedivEditor-2').removeAttr("disabled");
}
});
});
You can use .prop('disabled',true) for disable button and .prop('disabled',false) for enable button. Both are used after $('#deactivedivEditor-2').
First of all, you can use regular expressions to check the string with a pattern at any position. The regexp I show below matches on anything between two angular braces - even non html tags too.
Secondly - it is a bit off topic - the best and recommended solution for setting and disabling the "disabled" attribute with jquery is by using the .prop() method
$(document).ready(function () {
$('#inputdivEditor-2').keyup(function () {
var inputValue = $(this).val();
var regexp = /]*?>/;
var isDisabled = regex.test(inputValue);
$('#deactivedivEditor-2').prop("disabled", isDisabled);
});
});

How to remove extra commas from a list

I have a list of checkboxes and if one is checked, I'm appending the checkbox value to a input field elsewhere on the page. If a checkbox is unchecked, I'm removing the value from the hidden input field. What is happening is if the values are being added and removed just fine but they are leaving a series of commas behind when a check box is checked, unchecked, checked, unchecked, etc.
A) should I worry about it
B) if yes, how should I alter my add/append routine (see below) or is there a better way to do what I'm doing? I'd prefer to end up with a clean list like 0_1,0_2,41_4 opposed to 0_1,,,,,,,,,,,,,,,,0_2,,,,41_4,,,,.
<input type="text" value="0_1,0_2,41_4" id="EOStatus_SelLayers" />
// example of dataset: '0_1,0_2,41_4';
if ( xyz.hasClass("icon-check-empty") ) {
var existing_str = $('#EOStatus_SelLayers').val();
if (existing_str==null || existing_str==""){
//add
$('#EOStatus_SelLayers').val(id);
}
else {
//append
$('#EOStatus_SelLayers').val( existing_str + ',' + id);
}
}
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(','+id,'');
var new_str = old_str.replace(id,'');
$('#EOStatus_SelLayers').val(new_str);
}
In the else statement, I could do something like this:
var new_str = old_str.replace(id,'');
var new_str = old_str.replace(',,',',');
You can replace the id with an empty string and then replace any extraneous commas.
There are three places you can end up with an extraneous comma:
A double comma somewhere in the middle (needs to be replaced with a single comma)
A leading comma (needs to be removed)
A trailing comma (needs to be removed)
You can address all three cases with these two replace operations:
.replace(/,,/g, ",").replace(/^,|,$/g, "");
Which in place could look like this:
else {
$(xyz).removeClass("icon-check").addClass("icon-check-empty");
var old_str = $('#EOStatus_SelLayers').val();
var new_str = old_str.replace(id,'').replace(/,,/g, ",").replace(/^,|,$/g, "");
$('#EOStatus_SelLayers').val(new_str);
}
If you're using jQuery - a simpler approach would be simple re-set the input value each time a change was made to checkboxes? Simply concat the ID of each :checked input... If you're using a custom lib to change the appearance of the checkboxes I'm sure there's on-change event triggers that would allow the following to work.
Alternatively you should be able to edit to suit your specific needs.
$('input[type=checkbox]').on('change', function(e) {
var newVal = [];
$('input[type=checkbox]:checked').each(function() {
newVal.push($(this).attr('id'));
});
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Or, in the case you're using images:
$('[class^="icon-check"]').on('click', function(e) {
var newVal = [];
$('.icon-check').each(function() {
newVal.push($(this).attr('id'));
});
$(this).toggleClass('icon-check-empty');
$(this).toggleClass('icon-check');
$('#EOStatus_SelLayers').val(newVal.join(','));
});
Disclaimer: not tested - but looks like it should work.

Add ">" symbol at front of each textarea line using jquery

i don't know how to add this symbol '*' at front of every line of textarea. I have a hidden textarea which is #repmsg, and assume that in that box have 3 line. I want when user click #modquote, the confirm box will appear, and when user click OK, inside the textarea#modrepmsg will display
>line1
>line2
>line3
Here my jquery code
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var regex = /<br\s*[\/]?>/gi;
var repmsg = comment.replace(regex, "")
var quote = '>' + repmsg;
$('textarea#modrepmsg').val(quote);
}
});
Thanks for helping.
Something like:
$('#modrepmsg').val(function() {
return $('#repmsg').val().split('\n').map(function(line) {
return '>'+line;
}).join('\n');
});
Demo: http://jsfiddle.net/cm7d6/
you could replace \r\n or what ever return / linebreak is in the text area and replace with \r>
then preceed the content with >
You want to use a regex that gets the beginning or a text line so ^ should be used
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var repmsg = comment.replace("/^/g", ">")
$('textarea#modrepmsg').val(repmsg );
}
});

Categories

Resources