I have three input boxes that are all linked to each other by some pretty basic rules:
- Editing the page title will copy the contents to menu title
- Unless menu title has been manually edited
- clearing menu title sets it back to automatic
- Editing the menu title will copy the contents as a url slug to slug
- Unless the slug has been manually edited
- clearing the slug sets it back to automatic
- Editing page title counts as editing menu title if it is set to automatic
- The Page Title, and the other two boxes are never visible at the same time!
Here is a demo: http://jsfiddle.net/6VPpj/1/
and here is my rather horrible code, how can I clean this up?
$(function(){
var automatic = true;
var pager = true;
var cache = {};
var slug = $('#slug');
var menu = $('#menu_title');
var page = $('#page_title');
page.on('change', function() {
if (pager) {
menu.val(page.val());
menu.keyup();
}
});
menu.on('keypress keyup keydown change', function() {
if (automatic) {
var n = menu.val();
if (n in cache) {
slug.val(cache[n]);
return;
}
cache[n] = toSlug(n);
slug.val(cache[n]);
return;
}
});
menu.on('change', function() {
if (menu.val() == '') {
pager = true;
page.change();
}
else {
pager = false;
}
});
slug.on('change', function() {
if (slug.val() == '') {
automatic = true;
menu.keyup();
}
else {
automatic = false;
var n = slug.val();
if (n in cache) {
slug.val(cache[n]);
return;
}
cache[n] = toSlug(n);
slug.val(cache[n]);
return;
}
});
function toSlug(Text) {
return Text.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-');
}
});