I have several inputs in a form, but what I want to achieve is to send only the ones who have at least 1 character (alphanumeric), but for those who have empty or whitespace values must not be sent.
The problem is that when a user sends a whitespace by mistake by pressing the spacebar it serializes a plus sign (+).
So far this is what I do to send serialized non-empty values.
//this will print a query string with the values, but for whitespaces it sends '+' signs.
$('#myform').find('input').not('[value=""]').serialize();
You can use $.trim:
$('#myform').find('input').filter(function() {
return $.trim(this.value) != "";
}).serialize();
This will also take the actual user input (.value property) not the .defaultValue (value attribute) like .not('[value=""]')
You can do following:
var obj = {};
$('#myform').find('input').each(function() {
var value = $(this).val().trim();
var inputName = $(this).attr('name');
if(value.length != 0) {
obj[inputName] = value;
}
});
$(obj).serialize();
By Googling this seems to work pretty fine:
$('#myform').find('input:filled').serialize(),
reference:
http://jqueryvalidation.org/filled-selector/
Related
I have javascript code that will validate alphanumeric and dashes for any field it is assigned to. The regex completes successfully and the error message displays. What I would like to happen is upon hitting a key that would make the regex true it would delete the variable that set it to true (for example if someone where to hit the # key it would only delete the # character). Right now I have it set to erase the entire field.
function validateAlphaNumericField(field) {
var value = field.value;
var reg = /[^A-Za-z0-9-]/;
var newVal = reg.test(value)
if (newVal == true) {
alert("This field must contain only alphanumeric and dashes.");
field.value="";
}
}
you can replace the unexpected characters as following:
var value = field.value;
var reg = /[^A-Za-z0-9-]/;
return value.replace(reg,'');
I want to make custom replacer method for my HTML output. But I can't figure it out. I guess it should be done with String.match and replace somehow.
I have some "error codes" in my string that always start with _err_ and I have a JS object with values.
What I want to achieve:
Find all string parts (error codes) that starts with _err_
Get correct key for my object - error code without _err_
Find value from Lang object
Replace error code with correct Lang value.
Some error codes may appear multiple times.
var content = "Looks like you have _err_no_email or _err_no_code provided";
var Lang = {
'no_email' : "No email",
'no_code' : "No code"
};
I can do it other way around. So I cycle the Lang object and replace those in string.
It would be something like this if using underscore:
function replaceMe() {
_.each(Lang, function(value, key) {
content = content.replace(new RegExp('_err_' + key,'g'), value);
});
console.log(content);
};
But if it can be done faster with my first idea then I want to know how.
A simple regex should do the trick:
var content = content.replace(/\b_err_(.+?)\b/g, function(match, errorName) {
return Lang[errorName] || match;
});
This assumes that you do not want strings like "blah_err_blah" to be replaced, and defaults to not replacing the text if the error cannot be found in your Lang object.
var replace = function(str, object, regexp) { //if property not found string is not replaced
return String(str).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) {
return (object[name] != null) ? object[name] : match;
});
}
This is a format function I've used in several projects thats quite efficient. Matches {prop} by default to {prop:'val'} but you can pass a regex for example maybe in your case /_err_+\S/g so it matches other tokens in your string.
So you can do:
var content ="Looks like you have {no_email} or {no_code} provided";
var Lang = {
'no_email' : "No email",
'no_code' : "No code"
}
var formatted = replace(content, lang);
Or for your original string stealing the other answers regex:
var formatted = replace(content, lang, /_err_([^\s]+)/g)
You can use a callback function, that look if a key matching the error code exists in your Lang object, and if so returns the value of that (and otherwise just the key itself, thereby doing no replacement, like so:
content.replace(/_err_([a-z_]+)/gi, function(fullmatch, key) {
return Lang[key] ? Lang[key] : fullmatch;
});
The first parameter passed to the function will be the full match, and the second parameter key will just be that part grouped by the bracktes.
And then, if Lang contains a (non-falsy) value for key, that’ll be returned, otherwise just the fullmatch value, so that that part of the string gets “replaced” with itself.
See it in action here: http://jsfiddle.net/VZVLt/1/
One more variation with split
content = content
.split('_err_')
.map(function(str, index){
if (index === 0)
return str;
var whitespace = str.indexOf(' '),
key = str.substring(0, whitespace)
return Lang[key] + str.substring(whitespace);
})
.join('')
;
I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.
I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps
I met some trouble with a javascript.
In fact I have in my database many records that are abreviations and ther equivalent,
for example, replace tel => telephone etc...
So I have this function
$('#tags').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
console.log(code);
if (code == 'tel'){
var input = this.value;
input = input.substr(0, input.length -1);
console.log(input);
input += 'tel';
this.value = input;
}
});
Actualy this does not work the trouble is that I do not have aby mistakes
in the console of javascript.
Anykind of help will be much appreciated.
Kind regards.
SP.
This should work:
$('#tags').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
var input = this.value;
if (input.indexOf('tel') != -1) {
this.value = this.value.replace(/\btel\b/gi,'telephone');
}
});
Here is a fiddle
When using keyup() the event handler only returns the keycode of the pressed key. For instance an x results in e = 88.
Use $("#tags").val() to get the value of the input element.
the keyCode or which property doesn't return a string, or even a single char. It returns the key code that represents the key that was struck by the client. If you want to get the corresponding char: String.fromCharCode(e.which || e.keyCode);.If the user hit on the a key, for example, the keycode will be 97, String.fromCharCode(97) returns a.
If you want to know weather or not the current value of the element contains the abreviation: tel, what you'll need to do is this:
$('#tags').keyup(function(e)
{
this.value = this.value.replace(/\btel\b/gi,'telephone');
});
This is untested and very likely to need some more work, but AFAIK, you want to replace all occurrences of tel by telephone. The expression I use /\btel\b/ replaces all substrings tel, provided they are preceded and followed by a word-boundary (to avoid replacing part of a word). Not that the end of a string and a dash are both considered to be word boundaries, too. If I wanted to type television, I'd end up typing telephoneevision. To avoid this, you'll need a slightly more complex expression. here's an example how you can avoid JS from treating a dash as a boundary, just work on it to take string-endings into account, too
Update
Perhaps this expression isn't quite as easy as I thought, so here's what I'd suggest you use:
this.value = this.value.replace(/(?:(\-?\b))tel(?:(\b\-?.))/gi,function(all,b1,b2)
{
if (b1 === '-' || b2.charAt(0) === '-')
{//dash, don't replace
return all;
}//replace
return b1 + 'telephone' + b2;
});
Input: I need a tel, quickly ==> I need a telephone, quickly
I need a tel ==> I need a tel (if the user is still typing, don't replace, he could be typing telescope, replace on submit or on blur)
I want to book a hostel for tonight ==> I want to book a hostel for tonight
Visit Tel-Aviv ==> Visit Tel-Aviv
When using keypress this way the code variable will contain the character code of the pressed character. Not the string of chars like the expected 'tel'. You could use onkeyup / onchange event and check the val() of the input element and use replace() to change the abbreviation to the intended string.
$('#tags').keyup(function(e){
var elem = $(this);
var input = elem.val();
// input = input.substr(0, input.length -1); // This might not be necessary
console.log(input);
// do the replacement
input = input.replace('tel','telephone');
elem.val(input);
}
});
Use replace method for replacing a word in string.
eg:
var str = "This is AIR";
var newstr = str.replace("AIR", "All India Radio");
console.log(newstr);