Reputation: 1318
I'm running a small javascript replace to replace text on a button click and I can't see why it's not working. Could anybody tell me what i'm doing wrong?
$("#button").click(function() {
$("#editme").value = replaceLinks($("#editme").val());
})
function replaceLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"[url=$1]$1[/url]");
}
Upvotes: 0
Views: 99
Reputation: 339786
.value
is usually the direct property of a DOM Input element. The jQuery function to access or change an element's value is .val()
Usefully, .val()
allows you to pass a function to mutate the current value. That function is passed the element's index and current value, and the function's return value replaces the original value. All you need to do is change the signature of your replaceLinks
function to allow for the index
parameter (which you can then safely ignore).
$("#button").click(function() {
$('#editme').val(replaceLinks); // calls `replaceLinks` to mutate its value
});
function replaceLinks(index, text) {
...
}
See http://jsfiddle.net/alnitak/XzrHP/
Upvotes: 2
Reputation: 191729
A couple problems: .value =
should be .val(
. It's used both to set and get the value. You also had the button ID as #button
, but it should just be button
.
You could also do $("#editme").val(replaceLinks);
if you change the arguments of replaceLinks
to function replaceLinks(_, text) {
http://jsfiddle.net/ExplosionPIlls/zg4VB/5/
$("#button").click(function() {
$("#editme").val(replaceLinks);
})
function replaceLinks(_, text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"[url=$1]$1[/url]");
}
If you want to use replaceLinks
on strings as well, you could check arguments
in replaceLinks
as well: text = arguments[arguments.length - 1]
Upvotes: 1
Reputation: 207861
Two issues. First, $("#editme").value = replaceLinks($("#editme").val());
should be $("#editme").val(replaceLinks($("#editme").val()));
Second, your button ID was id="#button"
and should be id="button"
Upvotes: 3