Replace particular text message of a div using js or jquery - javascript

I need to replace the text "Form+validation+failed.+You+cannot+submit+this+record." inside <div class="alert alert-error"> with "You are not eligible to make this purchase."
<div class="alert alert-error">
<button class="close" data-dismiss="alert">×</button>
Form+validation+failed.+You+cannot+submit+this+record.
</div>
Its a dynamic code and I want to replace only that text not other text inside that class because the error text will be different according to behavior of the page.Is there any way I can find only this string "Form+validation+failed.+You+cannot+submit+this+record." and replace it with customized text message using either jquery or java script.

You can get all the alert alert-error classes using getElementsByClassName. You can then iterate over the HTMLCollection returned by getElementsByClassName. Using replace to update the message, see below:
window.onload = function() {
var errors = document.getElementsByClassName("alert alert-error")
for (var i = 0; i < errors.length; i++) {
var div = errors.item(i)
div.innerHTML = div.innerHTML.replace("Form+validation+failed.+You+cannot+submit+this+record.", "User Authentication failed.")
}
}
<div class="alert alert-error">
<button class="close" data-dismiss="alert">×</button>
Form+validation+failed.+You+cannot+submit+this+record.
</div>

This one is a dirty thing to do but this does what you need.
$('div[class="alert alert-error"]:contains("Form+validation+failed.+You+cannot+submit+this+record.")')
.html('<button class="close" data-dismiss="alert">×</button>You are not eligible to make this purchase.');
TIP: You can also simply use $(.alert-error:contains("Form+validation+failed.+You+cannot+submit+this+record.")) to select your div if you think that won't conflict with another DOM element
The code will first select a <div class="alert alert-error"> and the check for the given content. If a match is found, it will replace the complete HTML inside the selected div with whatever is passed inside .html(). Now, you will have to pass the HTML for the button next to your text because there is no way(none that I know of) to select just the string you wanted within the div. Had the string been in a wrapper, it would have been much easier and nicer to select and replace it using .replace().
FIDDLE
Probably, you should take a look at the code that is giving this "dynamic content". You can easily add a wrapper like <span id="dynamic"></span> around your "dynamic content" before passing it here. If you could do that, you could easily do something like
$('#dynamic:contains("Form+validation+failed.+You+cannot+submit+this+record.")').text('You are not eligible to make this purchase.');
FIDDLE

If you wrap your text with span tag then you can easily accomplish the replacement. Try like:
<div class="alert alert-error">
<button class="close" data-dismiss="alert">×</button>
<span id="text_to_replace">Form+validation+failed.+You+cannot+submit+this+record.</span>
</div>
To replace the existing text with the new one you should use this:
$('#text_to_replace').html('You are not eligible to make this purchase.');

Render your alert in span or other control.
Because put your text in div is bed practice of programming.
Here is working Fiddle.
Check Fiddle you will got your answer.
$( ".close" ).click(function() {
$(".message").html("Your Alert Message");
});

Related

How to print the content of a div that changes based on a foreach statement?

I have an ArrayList named conversations_client, I want to be able to get the value of conversation[6] for each div.
Each one the the media div represent a conversation.
Here is a part of my code :
<c:forEach var="conversation" items="${conversations_client}" >
<div class="media">
<div class="media-left">
<input class="checkbox" type="checkbox" name="selected-conv">
</div>
<div class="media-body">
<h4 class="media-heading">${conversation[0]}</h4>
<span class="hidden">${conversation[6]}</span>
......
I had first tried to use this code :
<script type="text/javascript">
$('.media').click(function(){
var text = $(this).text();
alert(text);
});
</script>
But it would print not only conversation[6] but others as well since they're all inside the div with class media.
Then I tried this :
<script type="text/javascript">
$('.media').click(function(){
var text = $('.hidden').text();
alert(text);
});
</script>
But it would print the same id for all divs, which is the id of the first one.
How can I do that? and would it be better to wrap those media divs with tags to be able to use a specific action for each one of them? because I am displaying all conversations, then once the user will click on one them I'll have to recover its id to be able to display the messages of that specific conversation and it isn't advisable to write Java code inside of jsp.
Thank you :)
Use find from current element.
$('.media').click(function()
{
var text = $(this).find('#hidden').text();
alert(text);
});
UPDATE:
You are using loop to repeat the markup. It's not good to use ID hidden multiple times as per W3C standards. ID should be unique and should be used once in the page.
Use class instead of id for multiple usages. In this case class="hidden"
Better change <span id="hidden">${conversation[6]}</span> to <span class="hidden">${conversation[6]}</span>
Also change JS to find .hidden
$('.media').click(function()
{
var text = $(this).find('.hidden').text();
alert(text);
});

How to pass viewBag data into Javascript and display in div

I am always leery of asking dumb questions here but I need to move on and create a few more active pages but this is a lingering issue in my way ...The chtml in razor contains a switch ,,, in one of the cases there's three if statements.. THIS IS JUST ONE OF THEM depending on the if statements a different string in viewdata is to be fed into a div and the div class "hidden" is removed and the supplied text displayed....
I have over the past few hours regained my briefly lost ability to remove that hidden class (I hate css) but I have never been able to update the content of the div.
PLEASE Advise Thank you !!
<div id="divUnUsableEvent" class="hidden">
<div class="row clearfix">
<div class="col-md-1"></div>
<div id="systemExceptionLbl" style="font-size: 2em; color: red;"
class="text-danger:focus">
Please contact IS support
</div>
</div>
</div>
//alphascores Not present AND BetaSCores Not Present Ready for xxxxx //alphascores Not present AND BetaSCores Not Present Ready for xxxxx Scoring
if (!Convert.ToBoolean(#ViewData["alphaPresent"])
&& !Convert.ToBoolean(#ViewData["betaPresent"]))
{
<script type="text/javascript">
$(function() {
$('#UnUseableEvent').addClass("hidden");
var txtMsg = #Html.Raw(Json.Encode(ViewData["beforeAlpha"]));
$('#divUnUsableEvent').removeClass("hidden");
$('#systemExceptionLbl').removeClass("hidden");
$('#systemExceptionLbl').innerText = txtMsg;
});
</script>
<a id="XXXReScoreEvent"
href="#Url.Action("Readyforxxxxxx", "Exception", new { Id = (int)#ViewData["Id"] })"
class="btn btn-primary btn-default btn-too-large pull-left margin"
aria-label="XXXReScoreEvent">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Ready for xxxxxx Scoring
</a>
}
break;
I know its hitting the javascript, as that html element (a button) named '#UnUseableEvent' is correctly being hidden in this case. I of course would want the javascript out of this html page and just have function calls in the razor but baby steps
Specifically regarding the ('#systemExceptionLbl').innerText = txtMsg; I have tried
.text
.value
.innerHTML
all to no avail. I can see the correctly formatted Json.Encoded text reach the variable txtMsg, but again I cant get it into the div ..
I am having success now with displaying the div (remove class hidden) I was attempting to affect the wrong div name and the line removing the hidden class from the element $('#systemExceptionLbl') is not needed.
I even tried to skip the JQuery reference and go old school document.getElementById('systemExceptionLbl').innerHTML = txtMsg;
Ever tried :
$('#systemExceptionLbl').text( txtMsg );
or
$('#systemExceptionLbl').html( txtMsg );
as innerText is not a jquery function. Instead use .html() or .text() to insert data into it

Hiding text using Javascript / JQuery

I am developing a Chrome extension and trying to hide part of a page. I am fairly new to this stuff so apologies in advance if I am using the wrong terms or the question seems obvious!
The page format appears as below:
<div class="wrapper">
<span class="loud" style="text-decoration: none;">...</span>
<div class="leave-gap">...</div>
<quote>...</quote>
"*** I can't figure how to hide this ***"
<p></p>
<span id="id_12345" class="none">...</span>
<div class="block-footer">...</div>
<div class="leave-gap">...</div>
</div>
As the snippet suggests, I cannot figure out how to hide the bit highlighted with stars.
I have a function that takes as an input a variable that is the first element in class "wrapper":
function processComment(commentStart)
{
$element = commentStart;
while($element)
{
if(some condition)
{
$element.hide();
}
$element.next();
}
Because this text is sitting by itself outside any tags, it is not being picked up. I can't just hide the whole of the wrapper class because there are some bits inside it that I need to show.
Any suggestions gratefully received.
Thanks,
Richard
Set visibility propery or wrapper as collapse and set visibility of childrens to visible for overriding visibility property. That it will only hide the text node.
$('.wrapper').css('visibility', 'collapse').find('*').css('visibility', 'visible');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper">
<span class="loud" style="text-decoration: none;">...</span>
<div class="leave-gap">...</div>
<quote>...</quote>
"*** I can't figure how to hide this ***"
<p></p>
<span id="id_12345" class="none">...</span>
<div class="block-footer">...</div>
<div class="leave-gap">...</div>
</div>
Your best bet might be to place the content you want hidden into a span of its own.
If I well understand, your if (some condition) is regarding the text content by itself, so it's a regex stuff or something like.
So what you can do is, having located the involved text part, wrap it between <span> tags: then you can address this <span> element the usual way.
It may look like this (here assuming your meta-example meant $elements are successive words):
function processComment(comment) {
// (comment is supposed to be the HTML element to process)
var words = $(comment).html().split(' ');
for (var i in words) {
var word = words|i];
if(some condition on word) {
words[i] = '<span class="hidden-word">' + word + '</span>';
}
}
$(comment).html(words.join(' '));
}

hide all duplicate div on page load using jquery/javascript

My page is showing Exception message several times Like this:
So, what i want is on page load if this below div is showing more than once then discard other & show only one message at a time...
<div style="width: 70%;text-align: left;margin-left: 15%;" class="alert alert-warning text-center alert-dismissible server-side-msg text-capitalize" role="alert">
<span class="glyphicon glyphicon-warning-sign"></span>
<strong>We apologize for the inconvenience,An exception occured,We will solve this issue asap...
</strong>
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
</div>
so how to hide/remove all duplicates div for showing only one message at a time using jquery?
Try this : select all div with role="alert" and hide them all but first one. You can use class selector also like $('div[class="alert"]')
$(function(){
// hide all alert but the first one
$('div[role="alert"]').not(':first').hide();
});
please try this code :
$(document).ready(function()
{
$("divID").hide();
});
var duplicated = {}, classname;
$('div').each(function() {
classname = $(this).attr('class');
duplicated[classname] = (duplicated[classname] | 0) + 1
})
for (var key in duplicated) {
if (duplicated.hasOwnProperty(key) && duplicated[key] > 1) {
$('div.' + key).slice(1).hide()
}
}
Demo
PS: The above method removes duplicate div based on class, you can modify it to include id also.
It is pretty obvious that the all alerts are bootstrap's alert-dialogs, so the javascript( jQuery ) solution looks like this:
$(function() {
//find all !visible! alert dialogs except the !last!! one and hide them..
$('.alert:visible').not(':last').hide();
//..you can also completely remove them from page, to avoid unnecessary DOM polution
// please notice, that you will select ALL alerts, not only the visible ones...
// $('.alert').not(':last').remove();
});
but you also should find out, why the server renders more then one alert on the page.
more efficient solution would be one with the context, like this:
$('#some-elem-with-all-alerts').find('.alert:visible').not(':last').hide();

updating div with jQuery and Knockout.js with .html() not working

This should be a simple matter of updating some simple modal controls with .html() but for some reason, I'm having issues. This is the modal code...
<div id="answerTaskQuestionModal" class=" modal-dialog" data-bind="with: currentQuestion">
<div id="answerTaskQuestionValidation" class="validation"></div>
<span data-bind="text: html"></span>
<div id="taskQuestionAnswer"></div>
</div>
And here is the JavaScript inside my working view model...
self.answerTaskQuestion = function (question) {
$('#answerTaskQuestionValidation').html('');
var $taskQuestionAnswer = $('#taskQuestionAnswer');
$taskQuestionAnswer.html(' \* {my html with bindings} *\ ');
$answerTaskQuestionModal.dialog('open');
self.currentQuestion(question);
};
Basically, I'm trying to dynamically change the ways one can answer a question as a proof of concept. If I just paste the html inside the target div, they work. However, when I check the value of .html(), this is what happens...
first run: $taskQuestionAnswer.html() returns undefined
second run: $taskQuestionAnswer.html() returns the proper HTML but the div won't update.
Replacing the bindings with just simple HTML doesn't help either. What am I missing here?
I think after $taskQuestionAnswer.html(' \* {my html with bindings} *\ ');
you should call ko.applyBindings(myViewModel) again to apply view model to new html.

Categories

Resources