隐藏表单提交的输入无线电
HTML : hiding input radios on form submit
我有一个HTML表单,有两种可能的类型("id"或"profile")
<form action="process.php">
<input type="radio" name="type" value="id">
<input type="radio" name="type" value="profile">
<input type="text" name="value" value="input">
</form>
结果URL是
/process.php?type=id&value=input
(或者type=profile,取决于用户的选择)
我希望我的url看起来像
/process.php?id=input
或
/process.php?profile=input
我有两个问题:
1)是以下jQuery/JavaScript代码"不好的做法"?我真的不觉得我做的是正确的,如果我这样做(即使它工作):
<input type="submit" onclick="formSubmit()">
<script>
function formSubmit() {
// if the first radio (id) is selected, set value name to "id", else "profile"
$("form input:text")[0].name = $("form input:radio")[0].checked ? "id" : "profile";
// disable radio buttons (i.e. do not submit)
$("form input:radio")[0].disabled = true;
$("form input:radio")[1].disabled = true;
}
</script>
2)有没有办法做到这一点,而不使用htaccess规则或JavaScript?
谢谢!
至于你的第一个问题,我会这样写我的jQuery:
// store your form into a variable for reuse in the rest of the code
var form = $('form');
// bind a function to your form's submit. this way you
// don't have to add an onclick attribute to your html
// in an attempt to separate your pre-submit logic from
// the content on the page
form.submit(function() {
// text holds our text input
var text = $('input:text', form),
// radio holds all of our radio buttons
radio = $('input:radio', form),
// checked holds our radio button that is currently checked
checked = $('input:radio:checked', form);
// checking to see if checked exists (since the user can
// skip checking radio buttons)
if (checked) {
// setting the name of our text input to our checked
// radio button's value
text.prop('name', checked.val());
}
// disabling our radio buttons (not sure why because the form
// is about to submit which will take us to another page)
radio.prop('disabled', true);
});
对于你的第二个问题,你总是可以把这个逻辑移到服务器端。这取决于您是希望由客户端还是服务器来完成预处理逻辑。无论哪种方式,服务器上都应该有逻辑来验证表单。如果你的js出错了,它可以发送原始表单数据。就我个人而言,我将这个逻辑放在服务器上,以避免检查的开销,以确保它首先被预处理。你还可以减少你的js使用,这将节省你一些宝贵的带宽。
你可以尝试这样做:
<input type="radio" name="type" value="id" onclick="getElementById('textValue').setAttribute('name','id');">
<input type="radio" name="type" value="profile" onclick="getElementById('textValue').setAttribute('name','profile');">
<form action="process.php">
<input type="text" id="textValue" name="value" value="input">
<input type="submit">
</form>
把单选输入放在表单外面,用id标识文本输入,这样就可以使用getElementById
函数(仍然需要检查浏览器是否支持它)。这可以避免加载jQuery,如果你不需要它在这个页面上。
结果是你所期望的。
但. .我将使用服务器端处理表单
相关文章:
- 无线电输入更改的jQuery事件未启动
- 通过单击链接(兄弟姐妹?)从无线电输入中获取id
- 角度双向绑定无线电输入
- 检查了多个无线电输入
- 如何更改无线电输入字段中文本的颜色
- 使用 JavaScript 和无线电输入更改 HTML 中的背景颜色有什么错误
- 单击时更改无线电输入值(实际上将其更改回来)
- 为什么我的无线电输入值是 NaN
- 如何为每个无线电输入组分配不同的名称
- 如何使用 JavaScript 在 Firefox 中使所需的无线电输入可选
- 将对象的键绑定到 AngularJS 中的无线电输入值
- 我的 JavaScript 无法正确检查表单的无线电输入
- 取消选择较低的无线电输入
- 根据选中的无线电输入更改表单操作和文本输入名称
- 环通并验证多个无线电输入
- 无线电输入点击功能不会运行
- 如何在页面刷新时保留无线电输入状态
- 根据无线电输入条件禁用和启用按钮提交
- 反应无线电输入不检查
- 我应该如何根据所选的无线电输入重新组织查询的控制流