最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Need to trim all the elements in the form using javascript - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jun 18, 2012 at 9:17 coderslaycoderslay 14.4k32 gold badges80 silver badges122 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 21
$('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()));
 }); 
发布评论

评论列表(0)

  1. 暂无评论