[英]Find and remove text from input value string
我們的表單有一個隱藏的input
,其中包含我們發送到服務器以進行服務器端驗證的所有必需值。 它由逗號分隔的字符串組成:
即<input type="hidden" value="name,address,telephone,email">
現在,在單選按鈕檢查中出現了新的輸入(即網站),我可以成功地將它們添加到value=""
字符串中:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
$('input[name="required"]').val(nowReq + ',website');
}
但是,當不同的無線電被選中,我不能得到它刪除,website
從字符串。
我相信我需要抓住字符串,用逗號將其分割,找到並刪除website
,然后重新加入字符串,但是我不確定如何實現這一點(或者這是否是最好的方法):
if ($('#fax').is(':checked')) {
var splitReq = nowReq.split(',');
// Something goes here?
$('input[name="required"]').val(nowReq2);
}
您可以使用string.indexOf(searchValue);
和string.replace(oldValue, newValue);
搜索和刪除未選擇的元素,或者最好在string.replace(regex, newValue)
的第一個參數中傳遞正 string.replace(regex, newValue)
:
非正則表達式示例:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
nowReq = nowReq + ',website';
}
else {
if(string.indexOf(',website') > -1) // If website is the last element
nowReq = nowReq.replace(',website', '');
else if(string.indexOf('website,') > -1) // If website is not the last element
nowReq = nowReq.replace('website,', '');
}
$('input[name="required"]').val(nowReq);
您只需要刪除數組中的最后一個元素,然后將其與','字符連接:
splitReq.pop();
$('input[name="required"]').val(splitReq.join(','));
嘗試:
var splitReq = nowReq.split(',website').join("");
我建議您避免解析值字符串,而只需在相關input
元素的更改時重新計算值; 以下是一個演示示例,因為問題中缺少信息(如果我們可以看到您的HTML和當前的jQuery,而不是對其的描述,則可以提供一個更具體的示例):
$('input[type="checkbox"]').on('change', function(){
var requiredString = $('input[type="checkbox"]').map(function(){
if (this.checked) {
return this.value;
}
}).get().join(',');
$('input[name="required"]').val(requiredString);
}).change();
JS小提琴演示 。
參考文獻:
在大多數情況下,以下方法將起作用:
var s = "name,address,telephone,email";
s = s.replace(",address", "").replace("address,", "").replace("address", "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.