jQuery find and replace text - javascript

I have a text contained on a <textarea> like this:
Hi {nom},
We are glad to accept your invitation.
I need it to become
Hi Dolly Parton,
We are glad to accept your invitation.
I don't want to use any plugin, but I have tried developing this simple functionality with no possitive result:
prevContent=$('textarea').val(); //alerts correctly textarea content
content = prevContent.replace('{nom}','Dolly Parton');
In this case, no replacement is made and content has the same value as prevContent.
This is not meant to make a real time replacemet, it has to be replaced before submitting form:
$(document).on('click','.submitMessage', function(){
prevContent=$('textarea').val();
content = prevContent.replace('{nom}','Dolly Parton');
$.post('../actions/newMessage.php',{ms_content:content}).success(
function(data){
alert("yikes");}
);}
});
SOLVED: This was due to a spell mistake on variable. It was sent like {nom1}, not {nom}. Sorry for the inconvenience.

You need use RegExp with g flag, because in your example only first {nom} will be replaced:
var prevContent = $('textarea').val();
var content = prevContent.replace(/\{nom\}/g, 'Dolly Parton');
and to update textarea you can use .val, like so
$('textarea').val(content);
Example

You will just need to assign value of "content" to textarea, as :
$('textarea').val(content);

Related

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

How to remove/change an input value using javascript

How do I remove the value 'Anonymous' in this input that I have and replace it with a placeholder text 'Your name' using javascript/jquery? I don't have access to the HTML code.
This is what I have so far, but don't really know where to go from there.
document.getElementById('txtYourName').placeholder =' Your Name ';
HTML
<input id="txtYourName" type="text" value="Anonymous" name="txtYourName"></input>
Add this second line here...
A placeholder is only seen when the value happens to be blank. With the code below, you can set the placeholder, as well as erase the default value in your field.
document.getElementById('txtYourName').placeholder =' Your Name ';
document.getElementById('txtYourName').value = "";
Demo: http://jsfiddle.net/723vL/
You can use .val():
$('#txtYourName').val('');
or pure javascript using:
document.getElementById('txtYourName').value = ""
If you want to set new value then just put your value inside "", like:
$('#txtYourName').val('new value');
With jQuery, your final code should look like:
$('#txtYourName').attr('placeholder','Your name');
$('#txtYourName').val('');
Fiddle Demo
With pure JS, you final code should look like:
document.getElementById('txtYourName').placeholder ='Your name';
document.getElementById('txtYourName').value = "";
Fiddle Demo
That should do it, so long as you are running that script either on an onload event, jquery's ready event or at the very bottom of the page, once the DOM has been rendered.
Are you getting an error in your console?
try this
returns value:
$('#txtYourName').attr("value");
sets value
$('#txtYourName').attr("value", "");
use
document.getElementById('txtYourName').value ='some vaue';
if you are using jQuery then you can use
$("#txtYourName").val('some value');

How to append text to '<textarea>'?

I have <textarea> where user can type in his message to the world! Below, there are upload buttons... I would love to add link to uploaded file (don't worry, I have it); right next to the text that he was typing in.
Like, he types in 'Hello, world!', then uploads the file (its done via AJAX), and the link to that file is added in next line to the content of <textarea>. Attention! Is it possible to keep cursor (place where he left to type) in the same place?
All that may be done with jQuery... Any ideas? I know that there are method 'append()', but it won't be for this situation, right?
Try
var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');
This took me a while, but the following jQuery will do exactly what you want -- it not only appends text, but also keeps the cursor in the exact same spot by storing it and then resetting it:
var selectionStart = $('#your_textarea')[0].selectionStart;
var selectionEnd = $('#your_textarea')[0].selectionEnd;
$('#your_textarea').val($('#your_textarea').val() + 'The text you want to append');
$('#your_textarea')[0].selectionStart = selectionStart;
$('#your_textarea')[0].selectionEnd = selectionEnd;
You should probably wrap this in a function though.
You may take a look at the following answer which presents a nice plugin for inserting text at the caret position in a <textarea>.
You can use any of the available caret plugins for jQuery and basically:
Store the current caret position
Append the text to the textarea
Use the plugin to replace the caret position
If you want an "append" function in jQuery, one is easy enough to make:
(function($){
$.fn.extend({
valAppend: function(text){
return this.each(function(i,e){
var $e = $(e);
$e.val($e.val() + text);
});
}
});
})(jQuery);
Then you can use it by making a call to .valAppend(), referencing the input field(s).
You could use my Rangy inputs jQuery plugin for this, which works in all major browsers.
var $textarea = $("your_textarea_id");
var sel = $textarea.getSelection();
$textarea.insertText("\nSome text", sel.end).setSelection(sel.start, sel.end);

javascript: extracting text from html

I am getting html content as below:
var test='<div id="test">Raj</div>';
How can i retrieve value Raj from above html content using javascript.
It sounds like you're trying to extract the text "Raj" from that HTML snippet?
To get the browser's HTML parser to do your dirty work for you:
// create an empty div
var div = document.createElement("div");
// fill it with your HTML
div.innerHTML = test;
// find the element whose text you want
test = div.getElementById("test");
// extract the text (innerText for IE, textContent for everyone else)
test = test.innerText || test.textContent;
Or in jQuery:
test = $(test).text();
If you use jQuery (I cannot believe I just said that ;)) you can get at the content immediately you wrap it in $(test).html
Someone else will tell you how to get at the innerHTML using a selector since everybody here are jQuery gurus but me
Update: somebody just did while I was editing: javascript: extracting text from html - see comments or updates to that
var test = getElementById('test')
try that

how to highlight part of textarea html code

I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight match values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com,but i was a newbie on js,i didn't understand his code meaning.
any advice is appreciated
To save time you should consider using an existing library for this requirement.
Quote from here:
As textarea elements can’t render HTML, this plugin allows you to highlight text inside textarea elements.
jQuery highlightTextarea.
Demo: Codepen
Usage:
$context.highlightTextarea(options);
There is a pre element over the textarea. So when you type anything it is copying the input on the pre element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code it is copying the value, applying filters and adding the HTML to the #view.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex would be a method to match the regex and return some parsed content to the pre, allowing you to customize the appearance of the textarea (that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}
#BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:
http://garysieling.github.io/jquery-highlighttextarea/

Categories

Resources