Changing text color using replace method - javascript

I am using the following code inside my click handler (shown in JSFiddle below) to replace a text when a user clicks on a cell value:
var value = event.args.value;
var color = "#FF0000";
var highlighted = text.replace(
' ' + value + ' ',
"<span style='color:" + color + ";'</span> "
);
panel.jqxPanel('clearcontent');
panel.jqxPanel('append', highlighted);
Q1:
It is behaving in a different manner. I mean when I click on the first cell value, it converts everything to red color, clicking on other values makes it behave in different manner as can be seen in my JSFiddle here
Q2. What can I use to preserve the html formatting? I mean using var text = panel.html(); instead of var text = panel.text(); didn't work for me.

You are missing the closing > on your span tag, and you are omitting the value that you obtained from var value = event.args.value; so the word goes missing.
var highlighted = text.replace(
' ' + value + ' ',
' <span style="color:' + color + ';">' + value + '</span> '
// ^ ^^^^^
Note I also changed the quote characters used so the HTML can have the double-quotes " which are more commonly used in markup, and javascript doesn't care about single or double quotes for strings — use whichever you like, just be consistent, for your own sanity.
Try the updated fiddle I created, changing only that line, and you will see the word you click on get highlighted.
That said, it is generally better to avoid inline styles like color="#FF0000" and use classes and CSS styles for them instead. You could instead have simpler code that doesn't have to work the var color into it:
var highlighted = text.replace(
' ' + value + ' ',
' <span class="selected">' + value + '</span> '
Your CSS would have a rule span.selected { color: #FF0000; } ... then, restyling your highlight color from red to something else you just change the CSS instead of having to change your javascript code.

Related

How to remove div if its text is identical to another div?

I have a d3 area chart with a tooltip that displays the same text in two different divs. The first div, .tooltip.headline.record, displays the selected value in bold. Another div class, .record-label, displays the all of the values at a given point on the x-axis — for both the selected and non-selected paths. Here's a Plunker of the problem.
To illustrate, it currently looks like this:
I've been trying to achieve a result like this:
... or like this:
I've tried the following methods of hiding or removing the duplicative .record-label div, without success — and without error messages to assist in further diagnosis.
function getRecordContent(obj, pos) {
if ( $(".tooltip-headline-record").text() == $(".record-label").text() ) {
$(".record-label").hide();
//$(".record-label").remove();
//console.log("same");
}
return '<li><div class="record-label">' + obj.state + " " + obj.record.toLowerCase() + " " + numFormat(obj.values[pos].y) + '</div></li>'
}
Here, again, is a Plunker that demonstrates the problem I'm trying to solve (see, specifically, the code beginning at line 480:
http://plnkr.co/edit/NfMeTpXzXGTxgNFKPFJe?p=preview
Is this what you're looking for?
Plunkr
Relevant code changes:
The whole dataset was being passed to the getRecordContent function. So I changed that: when hovered over "admissions", pass "transfers" and "codependents". (line: 435)
var filtered_dataset = dataset.filter(function(row){return row.record !== d.record; });
for (var i = 0; i < filtered_dataset.length; i++) {
content += getRecordContent(filtered_dataset[i], idx);
}
Seems like you need to specify the state name as well along with the record. (line 480)
return '<li><span class="record-label">' + obj.state + ' ' + obj.record.toLowerCase() + '</span><span class="record-value">' + numFormat(obj.values[pos].y) + '</span></li>'
Edit:
Changes made for the tooltip to adapt to the main chart as well:
var filtered_dataset = dataset.filter(function(row){return row.record !== d.record && row.state === d.state; });
Changed z-index for the tooltip in main.css (try removing it and hovering close to the jquery slider)
z-index: 2;
Hope this helps. :)

show and hide doesn't the opposite of it

I have function show and hide,I want to show 300 line and when you press on more it should show the rest of the text but it doesn't the opposite of it, meaning it show all the text and when you click on more it show less.
You need to assign "showcontent" class an initial style of "display:none;", then every thing should work as expected.
var html = firstcontent + '<p class="showcontent" style="display:none;">' + secondcontent + '</p>' + show_more + '</p>';
Working demo:
https://jsfiddle.net/48r998f6/

set character limit for editable div [duplicate]

This question already has answers here:
textarea character limit
(10 answers)
Closed 8 years ago.
I have a div element .userbio , which is used to display "About me". When you click on the element, it becomes a textarea, where i can edit the information. But it should stop, when the character limit reaches 180. A plugin is being used for editing the "about me" section https://code.google.com/p/jquery-in-place-editor/
On clicking the .userbio element, .editInPlace class of the plugin gets attached to the .userbio element. So i've tried setting css .editInPlace textarea { maxlength:180 }, it doesn't work.
What happens now is that, i can type in as many characters i can and it overflows the entire page. I want the editing to stop, when it reaches the limit of 180 characters. Even tried some Jquery code snippets, but it doesn't work. Thank You
I would consider adding the code for maxlength to the jquery plugin. From what I can see this is controlled in the function createEditorElement so just add that
createEditorElement: function() {
if (-1 === $.inArray(this.settings.field_type, ['text', 'textarea', 'select']))
throw "Unknown field_type <fnord>, supported are 'text', 'textarea' and 'select'";
var editor = null;
if ("select" === this.settings.field_type)
editor = this.createSelectEditor();
else if ("text" === this.settings.field_type)
editor = $('<input type="text" ' + this.inputNameAndClass()
+ ' size="' + this.settings.text_size + '" maxlength="' + this.settings.text_max + '" />');
else if ("textarea" === this.settings.field_type)
editor = $('<textarea ' + this.inputNameAndClass()
+ ' rows="' + this.settings.textarea_rows + '" '
+ ' cols="' + this.settings.textarea_cols + '" maxlength="' + this.settings.textarea_max + '"/>');
return editor;
}
Then add the default values for text_max and textarea_max to the top default settings object
$.fn.editInPlace.defaults = {
text_max: 180,
textarea_max: 180,
.... rest of defaults ....
}
You could bind a keyup event and substring the text if it exceeds the character count limit...
var limit = 180;
$("textarea").on("keyup", function() {
var val = $("textarea").val();
if(val.length > limit)
$("textarea").val(val.substr(0, limit));
});
textarea {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<textarea>text</textarea>
We have to find a way to add :
$(".editInPlace").attr("maxLength", 180);
Somewhere.
So we have to find a "hook" to set this attribute to the textarea when it pops out. I tried to look for this kind of hook in the documentation of the plugin but did not find one.
If nobody finds a better way to solve your problem, you can change the library's source code directly.
createEditorElement: function() {
if (-1 === $.inArray(this.settings.field_type, ['text', 'textarea', 'select']))
throw "Unknown field_type <fnord>, supported are 'text', 'textarea' and 'select'";
var editor = null;
if ("select" === this.settings.field_type)
editor = this.createSelectEditor();
else if ("text" === this.settings.field_type)
editor = $('<input type="text" ' + this.inputNameAndClass()
+ ' size="' + this.settings.text_size + '" />');
else if ("textarea" === this.settings.field_type)
editor = $('<textarea ' + this.inputNameAndClass()
+ ' rows="' + this.settings.textarea_rows + '" '
+ ' cols="' + this.settings.textarea_cols + '" />');
return editor;
},
And before returning "editor", add something like this:
if(this.settings.textarea_maxLength) {
editor.attr("maxLength", this.settings.textarea_maxLength);
}
Then you'll have to set the "maxLength" attribute as an option field when you instantiate the editInPlace:
$("#editme1").editInPlace({
/* the options you had before */
textarea_maxLength: 180
});
But it seems a bit tricky and I didn't test it, maybe you should consider asking the plugin's developer directly.
oops I didn't refresh the page before posting, sorry. This is basically the same solution as #pln
In jQuery, you can achieve the effect by disabling the input when the length of the inner text exceeds 179 characters:
if ( $('.userbio').text().length > 179 ) {
$('.userbio').prop('disabled', true);
}
Alternatively, HTML5 supports a maxlength property on textarea elements: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea

Jquery appending text to an element

The aim is to append a line of text into the element below.
anchorElement = "<a id='anchor" + countWide + "' class=\"boxOPT oneplustwo\" alt=\'"+ image_website +"' style=\"cursor:pointer;width:"+ itemWidth + "px"+";height:"+anchorHeight+";position:absolute;left:"+ locationLeft + "px"+";top:0.3%;\" ><p class=\"popupDynamic\"> " + popupImageTitles[i] + "</p>";
this code is contained within a loop so each time a new anchor is created and given an incremented ID (countwide) for for example 'anchor1' 'anchor2'
What I need is to be able to append this variable below as part of the p element inside this anchor
image_price
I have tried this with no progress.
$("#anchor1").append(image_price);
obviously we need the id in the line above to increment in line with the loop.
Thanks.
Try:
$("#anchor" + countWide + " .popupDynamic").append(image_price);
Explanation:
I have just updated the selector so that it would pick up the child of the #anchor + countWide(this means anchor plus the dynamic ID) with the class of .popupDynamic and append the price to it.
You can use the countWide variable in your selector, this way :
$("#anchor"+countWide+" .popupDynamic").append(image_price);

Cannot Select div's after insert via JavaScript / jQuery

I have a descriptions for each layer of a map , being generated via JSON objects. I generate all html for these containers, which contains maps , legends, and descriptions.
html_description += '<div ' + hide + ' id="'+ map_div_id + '_description_' + id + '">' + layer_info.description + '</div>';
// Set the description from the layer info
$('#' + map_div_id + '_description').html(html_description);
Then I want to only show certain descrptions (depending on which layer is showing). So below should work , (as it works in my console debugger) .
// Hide Descriptions
$('#' + map_div_id + '_description div').hide();
$('#' + map_div_id + '_description_' + visible).show();
// Show Proper Description
console.log('#' + map_div_id + '_description_' + visible);
console.log($('#' + map_div_id + '_description_' + visible));
Also the odd thing is I can manipulate the heading contanier :
// THIS WORKS?!
$('#' + map_div_id + '_description').hide();
Any ideas?
http://jsfiddle.net/PazSs/2/
Thanks for the jsFiddle.
I modified it to investigate, and here's my copy:
http://jsfiddle.net/PazSs/8/
I do believe your problem is in your dynamic_layer array. I stepped through the code in jsFiddle and that array has zero elements.
The result is when you call
dynamic_layer[map_div_id].setVisibleLayers(layer_id);
It crashes, as you're dereferencing an undefined result (null).
I see you're populating the dynamic_layer further above:
if (typeof geo_server != 'undefined' && geo_server != null) {
gp_server = gis_server + '/' + geo_server;
gp = new esri.tasks.Geoprocessor(gp_server);
} else {
// Adds a dynamic layer
dynamic_layer[map_div_id] = new esri.layers.ArcGISDynamicMapServiceLayer(full_map_server);
map[map_div_id].addLayers([dynamic_layer[map_div_id]]);
}
This seems to be the only place you stuff objects into the dynamic_layer array, so I'd start there. Check out your logic and ensure that you always put the layer in when required.
Let me know if it works!
that selector:
$('#' + map_div_id + '_description div')
would look for a div inside your description div.
assumed the value of 'map_div_id' is 'test' your markup after insert should look like this:
<div id="test_description">
<div> ...your description here </div>
</div>
when i see how your build your html_descriptions string, it does not look like it is doing that... (it only would be like that if 'layer_info.description' would contain '...'
thats a lot of assuming, it's probably easier you show us some generated markup, and complete script. use jsfiddle
I can see your logic:
HIDE ALL layer descriptions
and then SHOW only the layers you want to see
What does "visible" mean? Is that an id? The name implies a boolean.
If it's a boolean, your selector
$('#' + map_div_id + '_description_' + visible).show();
doesn't look like it'll work properly.
Can you describe what visible is a bit more, please, and give examples of the actual markup?
Thanks.

Categories