ThickyBlack
ThickyBlack

Reputation: 11

How to replace whitespace with underscore when copy value from form field to another

Someone should be able to find this example for me or give an example..

After hours of searching I found the answer using some bizare search terms in Google only for my 15 month old to close the browser window for me without book marking it! I had private browsing on so it didn't save my history :-(

I have a web form, I need to pass the value of one form field to another form field at the same time replace the white space with underscore using JQuery.

example of what I'm looking for

<input name="PageName" id="PageName" type="text" value="All About Us Page" />
<input name="PageURL" id="PageURL" type="hidden" value="all_about_us_page" />

so when the form is submitted it gives nice formatted URLs to the page(s) I don't know much about JavaScript or JQuery and how to write variable to make it work.

Hope someone can give a working example, so at least I can get it working and in turn help someone searching in vien for the same solution the title of this should rank pretty high in Google for others to follow.

Upvotes: 1

Views: 2640

Answers (2)

jabclab
jabclab

Reputation: 15052

A little jQuery plugin to do something like this (this would put the value of the first matched element into the set of elements matched by the passed in selector):

$.fn.copyTo = function(selector) {
    $(selector).val($(this[0]).val().replace(/\s/g, "_"));
};

Example usage:

$("#source").copyTo("#dest");

Here's a working example.

Upvotes: 4

Adam Rackis
Adam Rackis

Reputation: 83366

To copy the value from source, to dest, while replacing whitespace with an underscore, this should do it.

$("#dest").val($("#source").val().replace(' ', '_'));

Or to get any whitespace

$("#dest").val($("#source").val().replace(/\s/g, '_'));

Upvotes: 2

Related Questions