javascript - HTML : hiding input radios on form submit

标签 javascript jquery html forms

我有一个 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 的使用,这将为您节省一些宝贵的带宽。

关于javascript - HTML : hiding input radios on form submit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467692/

相关文章:

javascript - 动态更改 JavaScript 函数

javascript - Console.log javascript 在网络浏览器中不起作用

javascript - 根据特定值按顺序显示数组中的对象

javascript双击问题

html - Django 脆皮表格仅部分加载 css

css - 视口(viewport)禁用缩放并显示所有页面

javascript - $(this).val() 上的 parseFloat 返回一个对象

javascript - 如何从另一个文本框当前文本框填充+一年日期

html - 我可以在 BEM CSS 中嵌套 block 或元素内部修饰符吗?

javascript - Zombie.js错误: Timeout: did not get to load all resources on this page