How to pass viewBag data into Javascript and display in div - javascript

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

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);
});

javascript on page load check if a span (under <tr>) with a specific class exist, if does not exist remove the entire <tr>

I am trying to create my own greasemonkey script for my favorite directory listing site :)
The thing is not everything it list is beneficial to me, I inspected the website code and as it seems, each entry is under
Now, and as it seems, I am only interested with those which have this format:
<tr class="project-description">
<td colspan="6">
<div class="project-desc-inner">
<div class="project-synopsis">
<p class="trunk8">This is an entry</p>
</div>
<div class="project-verification">
<span class="verfied-badge"> <~~~~~~~~~~ THIS SPAN
<span class="currency-symbol">$</span>
<span class="icon-tick"></span>
Verified
</span>
</div>
<div class="project-actions">
<a href="#">
<button class="btn">LOL</button>
</a>
</div>
</div>
</td>
</tr>
As you can see, the existence of <span class="verfied-badge"> triggers it.
I also wish that the javascript process this after the page loads, because the site populates the table via javascript too.
I know I haven't done in my problem yet, but if somebody can just provide an example that can lead me, that is enough.
Thank you very much!
$(document).ready(function(){
$("tr.project-details").each(function(){
var self = $(this);
if(self.find("span.verfied-badge").length==0)
self.remove();
});
});
Filtered selector that calls .remove only once
Since there're other span elements within TR that are unrelated to the problem it's not possible to write a pure CSS filter selector string (so we could either use .has) to sufficiently filter elements. but instead of removing each table row individually we filter them first and remove them all at once.
$("tr.project-description").filter(function() {
return !$("span.verfied-badge", this).length;
}).remove();

Replace particular text message of a div using js or jquery

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");
});

Javascript divs not stacking

I have some div boxes and when you click a link it replaces an existing box rather than stacks a new one below it.
It's probably best to show you rather than explain.
Or at least I would but creating a jsfiddle doesn't replicate what I see on my webpage.
My webpage is intranet so I cannot share.
This is the fiddle: http://jsfiddle.net/GR6pu/
(When trying to post I get asked to accompany a jsfiddle.net link with some code.
Not quite sure what is needed so I'll post this:)
var showed = 'com1';
function com(id) {
if (showed && showed !== id) {
document.getElementById(showed).style.display = 'none';
}
document.getElementById(id).style.display = 'block';
showed = id;
}
What should hopefully happen is:
You start in community box.
When you click 'lam' you get a box below it = 'lam activities'.
If you subsequently click 'dispatch' this 'lam activites' box is replaced with 'dispatch activities'.
This bit works fine on my website with what I have posted in the fiddle.
Then, in 'lam activities' if you click 't45' you should get another box below it, but on my website the 't45' box replaces the 'lam activities' box rather than stacks another below it.
My goal is to have the 't45' box stacked underneath the 'lam activities' box.
From reading other threads on the forum I know you like your posters to detail what they have tried...
My knowledge on all things web based is small.
4 weeks ago I had never created a website and I've managed to teach myself enough HTML and CSS to create a working website but Javascript is still new to me, hence I don't have the knowledge to fiddle about with the js to make it work.
I tried changing none to block but this then creates more boxes than I would like.
Thanks, Kristian
When you click 'lam' you get a box below it = 'lam activities'.
Then, in 'lam activities' if you click 't45' you should get another
box below it, but on my website the 't45' box replaces the 'lam
activities' box rather than stacks another below it.
my goal is to have the 't45' box stacked underneath the 'lam
activities' box.
Overall you got 2 issues, the HTML is invalid as closing tags are missing and your code is not correct, hence it will not show the expected elements.
Fixing your HTML
Your demo fiddle is broken in the first place and does not demonstrate the issue you have.
You cannot show lam1 if the lam1 element is inside the com2 element which you are still hiding display: none, please inspect your HTML after clicking t45:
The reason you end up with incorrect nested HTML like that is due to missing closing tags which creates invalid HTML.
All <a> tags are missing their matching </a> closing tags.
All main divtags, such as <div id="com1"..>, <div id="lam1"..>, etc.. are missing their matching </div> closing tags.
Browsers try a best-guess, adding closing tags where it seems most appropriate, hence you might end up with unexpected HTML, such as sibling elements becoming nested instead.
Edit: The </a> are not required (my bad), only the 3rd </div> was missing in each section. I updated the fiddle and posted code to reflect that
DEMO - Adding missing closing tags fixes the demo and now shows the issue you are having.
Fixing your code
Now that the missing closing tags are added fixing the HTML in the fiddle which now works and shows the issue we can fix your code.
Your second function will always hide the t45 element and then show the task-element, hence it "replaces" it. I'm assuming you want similar functionality whereby the task element is replaced as you click on different "tasks".
In that case you cannot use the showed id but need to keep a separate record of the task-id (or what ever you want to call it)
function lam(id) {
// this removes the t45 element you want to keep
// I'm assuming you want to track clicked lams separately
if (showed && showed !== id) {
document.getElementById(showed).style.display = 'none';
}
document.getElementById(id).style.display = 'block';
showed = id;
}
Change that to the following and both elements are visible.:
var taskId;
function lam(id) {
if (taskId && taskId !== id) {
document.getElementById(taskId).style.display = 'none';
}
document.getElementById(id).style.display = 'block';
taskId = id;
}
DEMO - Fixing the code.
Here is the fixed HTML and code for completeness from the fiddle above.
HTML:
<div class='whitebox'>
<div class='subheader'>community</div>
<div class='links'>
<a onclick="com('com1');"><div class='boxlink'>LAM</div>
<a onclick="com('com2');"><div class='boxlink'>DISPATCH</div>
<a onclick="com('com3');"><div class='boxlink'>PLANNING</div>
</div>
</div> <!-- closing </div> was missing -->
<div id="com1" style="display:none">
<div class='whitebox'>
<div class='subheader'>lam activities</div>
<div class='links'>
<a onclick="lam('lam1');"><div class='boxlink'>T45</div>
<a onclick="lam('lam2');"><div class='boxlink'>SYNC</div>
<a onclick="lam('lam3');"><div class='boxlink'>ESSS</div>
<a onclick="lam('lam4');"><div class='boxlink'>IND</div>
</div>
</div>
</div> <!-- closing </div> was missing -->
<div id="com2" style="display:none">
<div class='whitebox'>
<div class='subheader'>dispatch activities</div>
<div class='links'>
<a onclick="lam('lam2');"><div class='boxlink'>SYNC</div>
<a onclick="lam('lam3');"><div class='boxlink'>ESSS</div>
</div>
</div>
</div> <!-- closing </div> was missing -->
<div id="lam1" style="display:none">
<div class='whitebox'>
<div class='subheader'>t45 tasks</div>
<div class='links'>
<a onclick="t45('t451');"><div class='boxlink'>REMOVAL</div>
<a onclick="t45('t452');"><div class='boxlink'>ADJUST</div>
<a onclick="t45('t453');"><div class='boxlink'>RECEIPT</div>
</div>
</div>
</div> <!-- closing </div> was missing -->
<div id="lam2" style="display:none">
<div class='whitebox'>
<div class='subheader'>sync tasks</div>
<div class='links'>
<a onclick="t45('t451');"><div class='boxlink'>emea</div>
<a onclick="t45('t452');"><div class='boxlink'>namer</div>
<a onclick="t45('t453');"><div class='boxlink'>s asia</div>
<a onclick="t45('t454');"><div class='boxlink'>n asia</div>
</div>
</div>
</div> <!-- closing </div> was missing -->
JavaScript:
var showed = 'com1';
var taskId;
function com(id) {
if (showed && showed !== id) {
document.getElementById(showed).style.display = 'none';
}
document.getElementById(id).style.display = 'block';
showed = id;
}
function lam(id) {
if (taskId && taskId !== id) {
document.getElementById(taskId).style.display = 'none';
}
document.getElementById(id).style.display = 'block';
taskId = id;
}
Lets break this down:
if (showed && showed !== id) {
document.getElementById(showed).style.display='none';
}
If showed is set and is not equal to the new id passed in the function, get the element with the ID of id and set it to display:none;
document.getElementById(id).style.display='block';
Get the element with the ID of id and set it to display:block;
showed=id;
Set the showed variable to be the value of the id passed into the function.
So basically, the function hides the previous element and then shows the element that has the ID you passed into the function. If you don't want to hide the previous element, you just need to remove the part of the function that does that (the if( showed && showed !== id ) { ... } statement block)

Hide/Show div and change class in span with Jquery function

I am using very simple function to hide entire div when clicked and display comments block instead.
Instead of hiding entire div, what I need to do is keep it as it is when clicked, display comment block, but change the class in the span from class="icon expand" to class="icon abate" and hide only "Click here to leave a comment or view what our customers are saying." line so that if it is clicked again it would do the opposite.
here is my script
function myfunc_showComments() {
if ( typeof jQuery != 'undefined' ) {
$('#hidecomments').remove();
}
var commentsParams ={
categoryID: 'Widgets',
streamID: '<?php echo $streamID ?>',
containerID: 'commentsDiv',
}
gigya.services.socialize.showCommentsUI(conf,commentsParams);
}
</script>
<!-- end #review --></div>
<div id="hidecomments">
<div class="button_3" onClick="myfunc_showComments()"><span class="icon expand"></span><h2>Comment & Rate this <span><?php echo $widget_title ?></span></h2><br />Click here to leave a comment or view what our customers are saying.
</div>
</div>
any suggestions or help is highly appriciated
I'd be inclined to put the "Click here..." text that you want to show and hide inside a div of its own:
<div id="hidecomments">
<div class="button_3"><span class="icon expand"></span>
<h2>Comment & Rate this <span><?php echo $widget_title ?></span></h2>
<br />
<div class="instruction">
Click here to leave a comment or view what our customers are saying.</div>
</div>
</div>
...so that it is easier to manipulate from your JavaScript code. Note that I've also removed the inline onClick="myfunc_showComments()" part, because you can just directly bind the handler form your script as follows:
$(document).ready(function() {
$(".button_3").click(function() {
var $this = $(this);
$this.find("span.icon").toggleClass("expand abate");
$this.find("div.instruction").slideToggle();
});
});
The .toggleClass() method adds or removes the specified classes depending on whether they're already there; it can add and remove at the same time so there's no need to manually code an if test to see what the current class is.
The .slideToggle() method is just one of several options that hide an element that is visible or show an element that is not visible. Other options include .toggle() or .fadeToggle().
Working Demo: http://jsfiddle.net/cRjCN/
Note that the document ready wrapper is not needed if the script appears after the elements in question.
use jQuery prop do it like this $(yourselector).prop('class','icon abate');
Edit:
$(".button_3").click(function(e) {
$("span.icon.expand").prop('class','icon abate');
});
just add the code block above inside <script> tags inside your html body tag. preferably before the closing </body> tag.

Categories

Resources