[英]HTML : hiding input radios on form submit
我有一个具有两种可能类型(“ id”或“ profile”)的HTML表单
<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,取决于用户选择的内容)
我想要的是我的网址看起来像
/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。
结果是您期望的结果。
但是..我将使用服务器端处理表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.