0

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;
});

2 Answers 2

1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

That did not work, but you pointed me in the right direction! I had to make the space to _ first and the rest after.
0

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.