提交表单之前,请从表单的参数中删除空值 [英] Delete empty values from form's params before submitting it

查看:91
本文介绍了提交表单之前,请从表单的参数中删除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JavaScript,可以捕获对表单的更改,然后调用表单的常规提交功能.表单是GET表单(用于搜索),我在参数中有很多空属性.我想做的是在提交之前删除所有空属性,以获得更整洁的网址:例如,如果有人将主题"选择更改为英语",我希望他们的搜索网址为

I have some javascript which catches changes to a form then calls the form's regular submit function. The form is a GET form (for a search) and i have lots of empty attributes come through in the params. What i'd like to do is to delete any empty attributes before submitting, to get a cleaner url: for example, if someone changes the 'subject' select to 'english' i want their search url to be

http://localhost:3000/quizzes?subject=English

而不是

http://localhost:3000/quizzes?term=&subject=English&topic=&age_group_id=&difficulty_id=&made_by=&order=&style=

目前是这样.这纯粹是为了有一个更干净,更有意义的url链接到人的书签以及供人们使用的书签等.所以,我需要的是这些方面的东西,但这是不正确的,因为我没有编辑实际的表单而是一个由表单参数制成的js对象:

as it is at the moment. This is just purely for the purpose of having a cleaner and more meaningful url to link to and for people's bookmarks etc. So, what i need is something along these lines, but this isn't right as i'm not editing the actual form but a js object made from the form's params:

  quizSearchForm = jQuery("#searchForm");
  formParams = quizSearchForm.serializeArray();
  //remove any empty fields from the form params before submitting, for a cleaner url
  //this won't work as we're not changing the form, just an object made from it.
  for (i in formParams) {
    if (formParams[i] === null || formParams[i] === "") {
      delete formParams[i];
    }
  }
  //submit the form

我认为我对此很满意,但是我错过了如何编辑实际表单的属性而不是创建另一个对象并对其进行编辑的步骤.

I think i'm close with this, but i'm missing the step of how to edit the actual form's attributes rather than make another object and edit that.

感谢任何建议-最高

编辑-已解决-感谢发布此内容的许多人.这就是我所拥有的,看起来很正常.

EDIT - SOLVED - thanks to the many people who posted about this. Here's what i have, which seems to work perfectly.

function submitSearchForm(){
  quizSearchForm = jQuery("#searchForm");
  //disable empty fields so they don't clutter up the url
  quizSearchForm.find(':input[value=""]').attr('disabled', true);
  quizSearchForm.submit();
}

推荐答案

属性为 disabled 设置为 true 的输入将不会与表单一起提交.因此,在一条jQuery行中:

The inputs with attribute disabled set to true won't be submitted with the form. So in one jQuery line:

$(':input[value=""]').attr('disabled', true);

这篇关于提交表单之前,请从表单的参数中删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆