jQuery - field entry - how to duplicate and convert to seo friendly url
I have two HTML input fields article
and url
.
How to duplicate field 'article' entry to field 'url' to SEO friendly link!?
url
allowed symbolsa-z
(capital letters converted to lowercase),url
space symbol replace with dash-
,url
other symbols ignored.
required typing just in field article
<input type="text" name="article">
url
field is jquery auto genera开发者_StackOverflow中文版ted and updated by field article
value
<input type="text" name="url">
This should work:
function name_to_url(name) {
name = name.toLowerCase(); // lowercase
name = name.replace(/^\s+|\s+$/g, ''); // remove leading and trailing whitespaces
name = name.replace(/\s+/g, '-'); // convert (continuous) whitespaces to one -
name = name.replace(/[^a-z-]/g, ''); // remove everything that is not [a-z] or -
return name;
}
and then
$('input[name=article]').blur(function() {
$('input[name=url]').val(name_to_url($(this).val())); // set value
});
This sets the value in the url field every time the article field looses focus.
It keeps already existing -
in the name. So if you want to remove them too, you have to change the second last and third last line of name_to_url()
to:
name = name.replace(/[^a-z ]/g, ''); // remove everything that is not [a-z] or whitespace
name = name.replace(/\s+/g, '-'); // convert (continuous) whitespaces to one -
Reference: .blur()
, .val()
, .toLowerCase()
, .replace()
Update:
I would create a new function, lets say, update_URL()
:
function update_URL() {
var value = name_to_url($('input[name=article]').val()) + '-' + $('input[name=year]').val();
$('input[name=url]').val(value)
}
then you can call this function on whatever event, e.g. on keyup()
:
$('input[name=article]').keyup(function() {
update_URL();
});
精彩评论