Our form has a hidden input
that contains all the required values we send to the server for server-side validation. This is formed of a comma-separated string:
ie <input type="hidden" value="name,address,telephone,email">
We now have new inputs (ie website) that appear on a radio button check and I can successfully add these to the value=""
string:
var nowReq = $('input[name="required"]').val();
if ($('#website').is(':checked')) {
$('input[name="required"]').val(nowReq + ',website');
}
But when a different radio is checked, I can't get it to remove ,website
from the string.
I believe I need to grab the string, split it by comma, find and remove website
and then re-join the string, but I'm not sure how to implement this (or if this is even the best way):
if ($('#fax').is(':checked')) {
var splitReq = nowReq.split(',');
// Something goes here?
$('input[name="required"]').val(nowReq2);
}
You can use string.indexOf(searchValue);
and string.replace(oldValue, newValue);
to search and remove non-selected elements or better pass Regular expression in the first parameter of string.replace(regex, newValue)
:
Non-regex Example:
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);
You simply need to remove the last element in your array and join it with the ',' character :
splitReq.pop();
$('input[name="required"]').val(splitReq.join(','));
尝试:
var splitReq = nowReq.split(',website').join("");
I'd suggest that you avoid parsing the value string, and simply recalculate the value on the change of the relevant input
elements; the following is a demonstrative example because of the lack of information presented in the question (a more specific example could be provided if we can see your HTML, and current jQuery, rather than a description of it):
$('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();
References:
the following would work in most cases:
var s = "name,address,telephone,email";
s = s.replace(",address", "").replace("address,", "").replace("address", "");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.