I want to replace a particular string in #TextArea1. This happens when a button is clicked.
Trying it out with the below code, but unable to get it work:
$('#TextArea1').text().replace("wef","--");
What is the correct syntax to replace a word in a div?
Pass a function to the text()[docs] method that returns the value you want set:
$('#TextArea1').text(function( i, txt ) {
return txt.replace("wef","--");
});
The function parameters are as follows:
i is the index of the current element in the iteration
txt is the current text content of the current element
The value returned from the function will be set as the new value for the current element.
You are close, try this:
$('#TextArea1').text($('#TextArea1').text().replace(/wef/g,"--"));
Or an optimized one
var $textarea = $('#TextArea1');
$textarea.text($textarea.text().replace(/wef/g,"--"));
If it's a textarea element, you would do:
var $textarea = $('#TextArea1');
$textarea.val($textarea.val().replace(/wef/g,"--"));
You have set the text also:
var text = $('#TextArea1').text().replace("wef","--");
$('#TextArea1').text(text);
or, using a function:
$('#TextArea1').text(function(index, text) {
return text.replace("wef","--");
});
Note: if this is a <textarea>, use val() instead of text().
var text = $('#TextArea1').val().replace("wef","--");
$('#TextArea1').val(text);
replace() creates a new string and returns it, so it's getting returned into thin air. You need to grab the new string and send it back into the textbox. This jsfiddle shows how.
<textarea id="t">
hello
</textarea>
var text = $('#t').text();
text = text.replace('h', 'b');
$('#t').text(text);
Related
I have value that is displayed in span tag. If i want to post the value i have to assign that value to an input. So this is the code i have written to assign value to input and trying to post that value. But when i alert the assigned value its
showing as
[object Object]
Pls check the code and correct me.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);
and i tried this also
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);
Both the above code shows
[object Object]
Because of this i am not able to post values.
That is because the value setter function on an input return the jQuery object of that input element only, it allows you to chain the event.
Try this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Read more about it here http://api.jquery.com/val/#val-value
"lower" is an object. if you want to see the text inside, you need to call lower.val().
e.g.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
jQuery supports chaining objects return.
So, whenever you do an operation on an object (except some like .val() getter, it returns object of that selector element.
So, you can do much more operations in a single statement.
In your statement,
var lower=$("#inputElement").val(value);
alert(lower);,
It is returning the object of element #lower.
You can add more operations to it.
For example:
var lower=$("#inputElement").val(value).css('color', 'red');
You want only plain value.
So, rather you should do this:
var value = $("#spanElement").text();
$("#inputElement").val(value);
var lower=$("#inputElement").val();
alert(lower);
Just do in this way..
var span_text = $("#spanElement").text(); //get span text
$("#inputElement").val(span_text); //set span text to input value
var input_value = $("#inputElement").val(); //get input value
alert(input_value); //alert input value
Hope this will help
This is because it will return a jQuery object . If you want to see the same text which is in the input you can either use .val() like answered previously or use like this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert($("#spanElement").prop('innerHTML'));
WORKING DEMO
You are getting 'Object Object' because lower is an object if you want to get the text you need to perform below actions.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Or
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Hope it helps !
This doesn't seem to be working, I get an Uncaught Type error on the .remove() line:
JS:
var str = $("a").html();
var $html = $.parseHTML(str);
$("i",$html).remove();
$("div").html($html);
HTML:
Hello <i>Bob</i>
<div></div>
How to get this to work?
You can remove the HTML tags by just using the .text() function.
var str = $("a").text();
$("a").text(str);
Which will result in:
Hello Bob
Example: http://jsfiddle.net/3s1c55w2/
How it works:
The $("a").text(); will retrieve only the text of the element, so in your case it will return Hello Bob.
Once you retrieve Hello Bob, simply set the a tags text value using .text(str) again, where the str is the value with no html tags.
You can clone a, change html code of clone and put clone inside div.
Fiddle.
$(document).ready(function()
{
var clone = $("a").clone();
clone.find("i").remove();
$("div").html(clone);
});
Maybe he's trying to remove i tags from every anchor.
http://jsfiddle.net/1fytum86/
$("a").each(function(index) {
var str = $(this).text();
$(this).html(str);
});
Anyway, it's possible that he was getting a type error because parseHTML() parses a string into an array of DOM nodes. Best of luck!
If you are trying to remove the italics and leave the text:
$("a").html($("a").html().replace(/<\/?i>/g, ""));
Otherwise, the other answers using either remove or detach would be appropriate.
JS Fiddle Example
OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.
I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:
function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}
Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?
function splitLastName(){
$('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
var names = v.split(',');
return '<span class="isUppercase">' +names[0] + '</span>,' + names[1];
});
}
Fiddle
.html() docs
The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:
function splitLastName() {
$('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
var names = $(this).text().split(',');
$(this).empty().append($('<span>', {
'class': 'isUppercase',
text: names[0]
}), ',' + names[1]);
});
}
Fiddle
Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.
The problem is you are trying to split a JQuery object.
I have updated your example: See here
function splitLastName(){
var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
var html = element.html();//get the contents of the DIV element
var splitNameArray = html.split(",");//Split the value with comma
var lastName = splitNameArray[0];//store the last name
var firstName = splitNameArray[1];//store the first name
var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
The problem occurs with this line:
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
The notation:
$('< some name >')
is a jQuery selector that selects an element. If you type this into your console (replacing < some name > with your selector) in your browser you'll see that it returns an object not a string. So your code is trying to split an object. I don't know where the string is located (div, span, input box etc.) but you need to pull the string to do the split. If your string is text in a div or span use:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').text()).split(",");
as this will grab the string contained in that selector and then perform the split on it. Likewise, if it is in an input you will need to use the proper handler to get the value:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').val()).split(",");
This will pull the value from an input and then perform the split. If your string is in html then you could alternatively grab it using the following notation:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').html()).split(",");
This will pull the html and perform the respective split operation.
Hope this helps.
I have a String which contains HTML tags:
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
And i also have a form with hidden input:
<input type='hidden' name='id' value=''>
With that String above, i want to get the value inside <p> tag which is 1 and assign that value to hidden input. And after that, i wanted to remove all the HTML tag inside the string which are these <br><p>1</p><em>My First Javascript</em>. So therefore the only value of str will be Hello World.
Is there any way how to do this on Javascript or jquery?
Thanks guys!
So, what you want to be doing is to convert your string into a jQuery object. You can do so like this -
var str = "Hello World <br><p>1</p><em>My First Javascript</em>";
var $holder = $('<div>');
$holder.append(str);
Now we have your string encapsulated within another div element. Next we extract the value within the <p> element -
var value = $holder.find('p').text(); // 1
Now that we have that value we can place it into the hidden input field -
$('input[name="id"]').val(value);
Now to remove all other elements from the original string - we'll use the container we created earlier for this -
$.each($holder.children(),function(index,elem){
$(elem).remove();
});
Now we can take the textual contents of $holder with $holder.text() and it should be just -
Hello World
If you would like to fiddle with this,
you can do so here - http://jsfiddle.net/TVXbw/1/
Ok, a quick and simple way:
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = str;//where str is the html string, obviously...
var pTagValue = tmpDiv.getElementsByTagName('p')[0].innerHTML;//=== '1'
document.getElementById('yourInputId').value = pTagValue;
If I understood correctly, that's what you're after, right?
I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));