[英]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.