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