Need to trim all the elements in the form using javascript - javascript

I need to trim all the trailing white spaces from the text elements of the form. I need to do it in minimal number of steps. As soon as i press onsubmit, it should trim all the white spaces and then perform the further operations. Is there any script available? If not then can you please help me to achieve my Goal. Currently i need to manual identify each element and then perform a trim like.
var username = myform.elements['username'].value;
username.trim();
How to generalize it?

$('input').val(function(_, value) {
return $.trim(value);
});

$("form").children().each(function(){
this.value=$(this).val().trim();
})
will trim all textbox and textarea inside form tag but don't write unnecessary code inside form.

Use
var allInputs = $(":input");
to get all form elements. Iterated using each function and trim it.
It will be something like this (not tested)
var allInputs = $(":input");
allInputs.each(function() {
$(this).val($.trim($(this).val()));
});

$('#yourformid').submit(function(){
$(':input').each(function(){
$(this).val($.trim($(this).val()))
})
return true;
});

$('#formid').find('input:text').each(function(){
                $(this).val($.trim($(this).val()));
 });

Related

How to Restrict to take input in JQuery from a input field Consisting on Alphabets without Space

I want to take an input from a text field and value should be consisting on alphabets and there should not be any space in between? Kindly let me know how to achieve this? Code is as follows;
$("#xxxx").bind("keyup change", function () {
$(this).val($(this).val().replace(/ /g,""));
});
Get to know regexes. They are fun, and you can test them here: https://regex101.com/
Use a regex in the replace that finds all non-alpha characters:
// no-conflict-safe document ready
jQuery(function($) {
// bind using on to a *class* instead of an id.
$(".numbers-only").on("keyup blur", function() {
// use a regex that finds all non-alpha characters
$(this).val($(this).val().replace(/[^a-z]/ig, ''));
});
});
Working fiddle: https://jsfiddle.net/cale_b/602wuwmx/
Notes for improving your code:
1. Use on instead of bind. (Per the bind documentation, bind was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.)
2. Bind to a class rather than an id. In this way, you can make multiple inputs behave this way.
You just check with regex if there is only alphabets:
var value = 'asdasd';
var isValid = value.match(/^[a-zA-Z]$/);
if (isValid) {
// valid
} else {
// not valid
}

Add special character at end of input fields string, jquery automatically adding comma

I am adding % symbol at the end of the string on keyup event, first I get the current value of input field and then split('%') and then I use following code
$('.percent input[type=text]').val(str+'%');
But this also adding comma after newly added character.
jsfiddle
Also Would love to do it by using css but the condition is only that there should not be any image used for it neither positioning used.(Can I use :after or :befor)
IMO the problem was the split function.
Try this:
$('.percent input[type=text]').on('keyup',function(){
var oldstr=$('.percent input[type=text]').val();
var str=oldstr.replace('%','');
$('.percent input[type=text]').val(str+'%');
});
Javascript .split() method returns comma seperated data, that is why your data is comma seperated.
If all you wish to do is remove the first symbol you could use .substr() - read about it here.
$('.percent input[type=text]').on('keyup',function(e){
var oldstr=$('.percent input[type=text]').val();
var tokens = oldstr.split('%');
var suffix = tokens.pop() + '%';
var prefix = tokens.join("");
$('.percent input[type=text]').val(prefix+suffix);
});
JS Fiddle: http://jsfiddle.net/uU8Lf/4/
A little late now, however I couldn't help but notice the constant reuse of the element's class/type throughout both answers. Is it not beneficial/best practice to use 'this' keyword within the '.on' callback function like so:
$('.percent input[type=text]').on('keyup',function(){
var oldstr=$(this).val();
var str=oldstr.replace('%','');
$(this).val(str+'%');
});
Please correct me if I'm wrong, and yes, I'm being picky here :)

How can I convert strings with HTML entities into normalized form?

I want to use jquery to convert text containing strings like 
, etc into a more human-readable form. This works in jsfiddle:
<input id="stupid-approach" type="hidden">
function js_text(theVal) {
$("#stupid-approach").html(theVal);
x = $("#stupid-approach").html();
return x;
}
alert(js_text("é"));
But I'm wondering if there is a way to do it that does not rely on a hidden field in the DOM?
just create an empty element, there's no need to have an actual hidden element in the DOM :
function js_text(theVal) {
return $("<div />", {html: theVal}).text();
}
FIDDLE
in consideration of the feedback about jQuery's .html() method's evaluation of script tags, here is a safer native version that's not tooo unwieldy:
function js_text(theVal) {
var div=document.createElement("div");
div.innerHTML=theVal;
return div.textContent;
}
use it instead of $(xxx).html() when you don't trust the input 100%
No. There's no purely programmatic way to do this that doesn't involve getting the browser to treat the string as HTML, as in your example. (Beware untrusted inputs when doing that, by the way - it's an injection attack waiting to happen.)
You should be able to just do:
return $('<div>'+ theVal + '</div>').html();

How to recognize and make hyper links?

How I can use Jquery to find http:// or www. and ends with .com, .org, .edu store that as a variable and wrap it in like:
<a href="variable"> <a/>
I have a textarea and when people put in links, I would like to then make them into hyperlinks once they are posted.
lets say the text area contains,
http://site1.com/uri/
http://site2.net/uri
http://site3.org/uri
http://site4.co.uk/uri
http://site5.ws/uri
The first thing i would do is bind an even for keyup on the textarea
$('#addLinks').bind('keyup',function(){
var _data = $(this).val();
//Then i would try and split the spaces and carriages
_array = _data.split('\n|\r\n|\s|,'); //Split by returns,new lines,spaces,commas.
var _regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
$(_array).each(function(value){
//Now i will check the URL is valid
if(_regex.test(value))
{
//Valid URL so i will then append it to the links container
//Here you can do e
$('<a></a>').attr('href',value).val(value).appendTo('.linksContainer');
}
})
});
Something along them lines!
Regex borrowed from: http://snippets.dzone.com/posts/show/452
roll your own way:
var foo = $('textarea selector').val();
then use a regular expression to get what you want. then stick it back into the textarea
$('textarea selector').val('http://thenewlink');
easy plugin way:
7 jQuery Plugins to Manipulate TEXTAREAs

Need Pure/jQuery Javascript Solution For Cleaning Word HTML From Text Area

I know this issue has been touched on here but I have not found a viable solution for my situation yet, so I'd like to but the brain trust back to work and see what can be done.
I have a textarea in a form that needs to detect when something is pasted into it, and clean out any hidden HTML & quotation marks. The content of this form is getting emailed to a 3rd party system which is particularly bitchy, so sometimes even encoding it to the html entity characters isn't going to be a safe bet.
I unfortunately cannot use something like FCKEditor, TinyMCE, etc, it's gotta stay a regular textarea in this instance. I have attempted to dissect FCKEditor's paste from word function but have not had luck tracking it down.
I am however able to use the jQuery library if need be, but haven't found a jQuery plugin for this just yet.
I am specifically looking for information geared towards cleaning the information pasted in, not how to monitor the element for change of content.
Any constructive help would be greatly appreciated.
I am looking at David Archer's answer and he pretty much answers it. I have used in the past a solution similar to his:
$("textarea").change( function() {
// convert any opening and closing braces to their HTML encoded equivalent.
var strClean = $(this).val().replace(/</gi, '<').replace(/>/gi, '>');
// Remove any double and single quotation marks.
strClean = strClean.replace(/"/gi, '').replace(/'/gi, '');
// put the data back in.
$(this).val(strClean);
});
If you are looking for a way to completely REMOVE HTML tags
$("textarea").change( function() {
// Completely strips tags. Taken from Prototype library.
var strClean = $(this).val().replace(/<\/?[^>]+>/gi, '');
// Remove any double and single quotation marks.
strClean = strClean.replace(/"/gi, '').replace(/'/gi, '');
// put the data back in.
$(this).val(strClean);
});
You could check out Word HTML Cleaner by Connor McKay. It is a pretty strong cleaner, in that it removes a lot of stuff that you might want to keep, but if that's not a problem it looks pretty decent.
What about something like this:
function cleanHTML(pastedString) {
var cleanString = "";
var insideTag = false;
for (var i = 0, var len = pastedString.length; i < len; i++) {
if (pastedString.charAt(i) == "<") insideTag = true;
if (pastedString.charAt(i) == ">") {
if (pastedString.charAt(i+1) != "<") {
insideTag = false;
i++;
}
}
if (!insideTag) cleanString += pastedString.charAt(i);
}
return cleanString;
}
Then just use the event listener to call this function and pass in the pasted string.
It might be useful to use the blur event which would be triggered less often:
$("textarea").blur(function() {
// check input ($(this).val()) for validity here
});
Edited from the jquery docs..
$("textarea").change( function() {
// check input ($(this).val()) for validity here
});
Thats for detecting the changes. The clean would probably be a regex of sorts
edited above to look for a textarea not a textbox

Categories