Reputation: 389
I want to help my users to add a correct string do be used as a meta_key in the database by not allowing illegal characters and replacing bad characters with good ones. I have this and its working great.
$('.custom_field_name').keyup(function () {
var v = this.value.replace(/\W/,'');
if (v!=this.value) this.value = v;
});
But i also want to replace space ' ' with a underline '_', and I have been trying codes like this, not getting anywhere.
$('.custom_field_name').keyup(function () {
var v = this.value.replace(/\W/,'') && (' ','_');
if (v!=this.value) this.value = v;
});
or
$('.custom_field_name').keyup(function () {
var v = this.value.replace(/\W/,'');
var v = this.value.replace(' ','_');
if (v!=this.value) this.value = v;
});
Upvotes: 0
Views: 340
Reputation: 389
I got it to work with this code! Also added toLowerCase(). Problem was not to declare v twice (@GGO) and change the order.
jQuery('.custom_field_name').keyup(function () {
var v = this.value.replace(' ','_');
var vee = v.toLowerCase().replace(/\W/,'');
if (vee!=this.value) this.value = vee;
});
Upvotes: 0
Reputation: 2748
You can't declare v
variable twice, use that :
$('.custom_field_name').keyup(function () {
var v = this.value.replace(/\W/,'');
v = v.replace(' ','_');
this.value = v;
});
Upvotes: 1