views:

147

answers:

1

I have two HTML input fields article and url.

How to duplicate field 'article' entry to field 'url' to SEO friendly link!?

  • url allowed symbols a-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 generated and updated by field article value

<input type="text" name="url">
+1  A: 

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();
});
Felix Kling
Thanks, Felix Kling! It works grate! Could it be able to make 'url' field update after any change in 'article'? Not just when it looses focus.
Binyamin
@Binyamin: Sure, you have to use the `keyup()` method instead of `blur()` : http://api.jquery.com/keyup/ | Btw of course you can chain the methods in `name_to_url`, like `return name.toLowerCase().replace().replace().replace()` but I split it up for explanation... Also if you don't want the url field to be editable, add the HTML attribute `readonly="readonly"` to the field. JS will still work.
Felix Kling
@Felix Kling: Thank you very much! I add number and few more language supporting '[^a-z0-9א-תа-яā-ž-]'. It works fine, and hopefully it is coded fine too. Do you know how to show in field 'url' two field combine 'article'+"-"+'year' (it does not work in this way - $('input[name=article + name=year]')!?
Binyamin
@Binyamin: See my updated answer...
Felix Kling
@Felix Kling: Thanks again! I change `keyup()` to `keypress()` so it does not show Firebug warning "The 'charCode' property of a keyup event should not be used. The value is meaningless."
Binyamin
`keyup` works better than `keypress`
Binyamin