Replace Text In Html Textarea
I have this script that matches a text on keyup in a textarea if between the minus sign. $('#notes').keyup(function() { // notes is the id of the textarea var regex = /
Solution 1:
Try the below code.
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).val();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/script.php",
data: { "reference" : reference },
success: function(data) {
// I need to replace the text matched by the regex with data in the textarea.
// I need to stop the ajax calling after success or call it only if regex is matched
}
});
}
}, 3000);// Call request in 3 second
});
This is the optimized version of your code. it will wait for users to complete, and in inactivity of 3 seconds, it will generate an Ajax call.
you can change the frequency to 2000 OR 1000 (2 second and 1 second respectively).
Solution 2:
I solved the problem adding contenteditable="true" to the textarea. Below the final jquery code:
var textInput = $("#notes"); // the ID of the textarea
var triggerTime;
$("#notes").keyup(function() { // notes is the id of the textarea
clearTimeout(triggerTime);
var myValue = $(this).text();
triggerTime = setTimeout(function(){
var regex = /\-([^\)]+)\-/gmi; // it gets the text between minus sign. Example: -text-
if(myValue.match(regex)){
var newValue;
var reference = myValue.match(regex);
$.ajax({
async: false,
type: "POST",
url: "scripts/parser.php",
data: { "reference" : reference },
success: function(data) {
newValue = data;
console.log(newValue);
$('.textarea').html(function() {
return $(this).text().replace(reference[0], '<strong>' + newValue + '</strong>');
});
}
});
}
}, 1000);// Call request in 1 second
});
Post a Comment for "Replace Text In Html Textarea"