隐藏表单提交的输入无线电

HTML : hiding input radios on form submit

本文关键字:无线电 输入 表单提交 隐藏      更新时间:2023-09-26

我有一个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,如果你不需要它在这个页面上。

结果是你所期望的。

但. .我将使用服务器端处理表单