I have a list of Questions, and each of those Questions has a list of Answers (which can be any integer from 1-5). I would like to dynamically create a chart for each Question, using the count of all answers that match a specific "rank"; i.e. all the answers that were a '1', '2', '3', etc.
So what I've done is set a for loop that creates an element for each question; this element is used as a placeholder for the chart. (As an aside, I am using flot charts).
The problem I'm having is trying to name the placeholders dynamically; what I really want is to create something that ends up looking like this:
<div id='chart1'/>
<div id='chart2'/>
etc
The closest I've managed is this:
<div id="'chart'#currentQuestion"/>
which of course gives an id like this: 'chart'1
Later, when I try to append the chart to the div I've created, the following doesn't work:
$("#'chart'"+i).append(div); //where i is the current loop counter
If I use
$("#chart"+i).append(div);
it correctly finds the element 'chart1', 'chart2' etc; but I'm struggling to name the div to match.
Can anyone help? It seems trivial unless you know how to solve it :-)
Edit: As requested, here is the relevant HMTL:
<div id="'chart#currentQuestion'">CHART</div>
SOLVED:
Like this: id="chart#(currentQuestion)" (via a colleague) Thanks for your efforts.
You haveen't close your div correctly. try this code
<div id='chart1' style="border:dashed">
</div>
<br />
<div id='chart2' style="border:dotted">
</div>
<script type="text/javascript" src="jquery_library.js">
</script>
<script type="text/javascript">
function fnc(value){
$("#chart"+value).append('1');
}
</script>
<input type="button" onclick="fnc(1)" value="for div1"/>
<input type="button" onclick="fnc(2)"value="for div2" />
You are using razor syntax, so here how it should be.
// Define your counter
#{long i = 0;}
// On document ready dynamically add your items
$("document").ready(function(){
// Create red divs starting by zero
// after 5 divs stop creating red divs
#for (i = 0;i<5;i++){
#:$("#form").append('<div id="chart' + #(i) + '">Red</div>');
}
});
// I made a button for action, you can choose other ways to invoke this function
$("#form>input").click(function(){
// Your counter is at 4 now
// lets change it to 2
#(i = 2;) // Now your counter is at 2
// Put a blue div into 2nd div starting by 0
$("#chart"+#(i)).append('<div class="blue">blue</div>');
});
this is how you use razor syntax with scripts
Related
Trying to make a dynamic div but i don't know how. Wrote a solidity smart contract that accepts an array of struct. In the smart contract i can use a get function to display the data inside. Data in the array is treated like a history, it consists of amount (making a crowdfund site), date, currency used, etc. Since the get function in the smart contract can only extract one part of the array, i thought of putting the get function into the while loop and extract the whole history array..
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
I'm trying to dynamically create another div with the same amount of < a > in the div. If i had 10 sets of data to display in that div, i wish to create only 10 sets of that div. Can createElement() be used to do that? Couldn't find any solution that works. Totally have no idea on how to create it. Can someone please help.
Would it be rational to extract the data from the array using a while loop and putting it in a div to display or would it use too much gas for this to work?
I don't get why would you want to do this, but you can do like this:
$('#set a').each(function(){
$('#set').after( "<div></div>");
});
It selects all of the <a>...</a> inside the <div id="set">...</div> element, and for each one of those inserts a <div></div> element. It inserts the element right next to #set but you can change that to any other element you could select.
I'm supplying jQuery code since you tagged the question as jQuery.
Hope it helps,
You can get the number of anchor tags by using this function getElementsByTagName('a').length from the hosting div. Then use that number to create new divs. This solution is done using vanilla JS.
function createDynamicDivs(){
var newDiv = document.createElement("div");
var noOfAnchors = document.getElementById('set').getElementsByTagName('a').length;
for(var i=0;i<noOfAnchors;i++){
var newContent = document.createElement("a");
newContent.textContent= "Test ";
newDiv.appendChild(newContent);
}
document.getElementById('new').appendChild(newDiv);
}
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
<div id="new"></div>
<button onclick="createDynamicDivs()">Generate</button>
I am trying to make an independently working div which has a form inside of it.
I use jquery to calculate the price of a product depending of the user's selections in the form. However the user is able to add multiple items in his 'cart' so the form is duplicated to another div. The problem is that the calculation pattern can't separate these two divs and the calculation will be incorrect. The form is also interactive so it will be generated by the user's input. This is really complex set and renaming every variable by the 'product number' doesn't sound really efficient to me.
I'm kind of stuck here and i don't really know how to solve this problem. I had an idea that what if I put an iframe inside of the div and load my form and its calculation script inside of it, and then use post command to transfer the price of the product to the 'main page' to calculate the total price of all of the products the user wanted.
However it seems that jQuery scripts doesn't work independently inside of these iframes, they still have connection so they broke each other.
i will appreciate any kind of suggestions and help to solve this matter, thank you!
here's the code so far
Heres the body
var productNumber = 1;
<div id="div_structure">
</div>
<button id="newProduct" >Add new product</button><br \>
add new item
<!-- language: lang-javascript -->
$('#newProduct').click(function ()
{
$('<div id="productNo'+productNumber+'">')
.appendTo('#div_structure')
.html('<label onclick="$(\'#div_productNo'+productNumber+'\').slideToggle()">Product '+productNumber +' </label>'+
'<button onclick="$(\'#product'+productNumber+'\').remove()">Remove</button>');
$('<div id="div_product'+productNumber+'" style="display: none;">').appendTo('#product'+productNumber+'');
$('<iframe src="productform.html" seamless frameborder="0" crolling="no" height="600" width="1000">').appendTo('#div_product'+productNumber+'');
productNumber++;
});
it also has a function that allows the user to remove the inserted div.
Here's just few lines from the productform
$(document).ready(function()
{
$('#productCalculation').change(function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
<form id="productCalculation">
<div id="div_productShape" class="product1">
<h1>Select the shape of the product</h1>
<input type="radio" name="productShape" value="r1">R1</input><br \>
<input type="radio" name="productShape" value="r2">R2</input><br \>
<input type="radio" name="productShape" value="r3">R3</input><br \>
</div>
.
.
.
</form>
I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable
There are two problems with this code: You say somewhere "I translated all of the variables so they may not function correctly since i didn't test the translated version. So the problem is, if i try to make selections in the second generated div it wont even alert() the selected variable". This is because event handlers are attached to elements that are in the DOM at that specific moment. To get it to work for all elements, use event delegation:
$(document).ready(function()
{
$(document).on( 'change', '#productCalculation', function ()
{
shape = $('input[name=productShape]:checked', '#productCalculation').val();
alert(shape);
});
});
Your other question is "My question in a nutshell: Is there a way to restrict jquery to function only in certain div even though i use the same variable names in the second div ". You can use the this variable to access the element the click was invoked on. From this element you can traverse the DOM if needed, for example with .parent().
$('div').on( 'change', function( e ) {
console.log( $(this).val() );
} );
I have been looking with no success to see if I can dynamically apply a css style to JSF component or div using javascript. Is this possible.
This is pseudo code
<div style="myJSStyleFunction("#{myBean.value}")"> stuff </div>
And the function would return something like "position:relative;left:25px;"
I've had no luck and maybe it can't be done but would like a second opinion.
Edit:
I'm trying to see if I can keep a separation / reduce the coupling between the presentation/view and the model/controller. This is for indenting commenting or product reviews (to nest replies to comments or reviews). The most I really want to track is an integer on how deep a reply is. First level = 0 second level = 1, and so on. So a comment or product review would be 0 deep, a reply to the comment or review would be 1 and so on.
Then in the EL I wanted to call a javascript function and do something like
<script>
myJSStyleFunction(depth){
if(depth<=5){
var nest=20*depth;
var style="position:relative;left:" + nest + "px;";
return style;
}
}
</script>
And then then say for a third level comment (a reply to a reply) it would look like this:
<div style="position:relative;left:40px;"> stuff </div>
where
#{myBean.value}
evaluates to 2
I suspect like Daniel says I'll have to tightly couple the view but I'd rather not have to. I'd think there has to be a way. But maybe not.
I don't know where there are cleaner solutions for this. However this is one suggestion.
Assume your page looks like below and myBean.getValue() method returns an integer.
<h:form id="frm">
<div style="#{myBean.value}"> div1 </div>
<div style="#{myBean.value}"> div2 </div>
</h:form>
So you can do something like this at 'window.onload'.
<head>
<script>
window.onload = function() {
var childList = document.forms['frm'].childNodes;
for(var i = 0; i < childList.length; i++) {
if(childList[i].nodeName == 'DIV') {
var _div = childList[i];
var depth = _div.getAttribute('style');
_div.setAttribute('style', 'position:relative;left:' +(depth *20)+ 'px;');
}
}
}
</script>
</head>
Note: 1. In above sample code I assume all the DIVs inside the form should be indented.
2. For IE you may need to use _div.style.setAttribute('cssText','position:relative;left:' +(depth *20)+ 'px;')
3. Another solution for your question is using <script> tags immediately after your divs and putting the js part inside them. In this way you don't have to use fake styling style="#{myBean.value}" or window.onload event because you can directly call #{myBean.value} in your script.
I decided to skip the javascript approach and settled on a simpler and I think cleaner method to create the dynamic css classes for my situation. I already capture/calculate the depth value for each comment when it is entered. So I am just returning that value in EL and concatenating it to a 'base name' for the css class like so:
<div class="indent_#{(comment.commentDepth le 5) ? comment.commentDepth : 5}" >
comment comment blah blah blah
</div>
"indent_" is the base name for the css class. So for a 0 level comment it will have a class="indent_0". A reply to that comment will have class="indent_1".
I use the ternary so that if there are lot of replies under a given comment it doesn't indent right off the right hand side of the page. Even though you can keep going deeper, it will only indent up to 5 levels.
For my case at the moment, this is a simpler and cleaner method of adding some dynamically generated css class names. Right now I have to define 6 classes for this in the css file, but perhaps I'll figure out how to nest the boxes but it isn't a priority this works just fine for me for now.
I have a large page having a lot of divs and all these divs are enclosed in a single div. And I have number links on the top of the page equal to the total enclosed divs I have. Now what I want to do is, on click on a number, I want to show only div corresponding to that number and hide all other.
links--> 1 2 3 4 5 6 7 .....
<div id="all">
<div id="mail1">..........</div>
<div id="mail2">..........</div>
<div id="mail3">..........</div>
<div id="mail4">..........</div>
<div id="mail5">..........</div>
<div id="mail6">..........</div>
.....and so on
</div>
I have to do it inside an HTML and that HTML will be stored and may be viewed offline as well, so cannot use jQuery here. Have to do it using JavaScript itself.
Could anybody help me with the JavaScript code here?.
<script type="text/javascript">
var divIds = ["mail1", "mail2", ..., "mailn"];
function showDiv(showId) {
for(var i = divIds.length; i--; ) {
if(divIds[i] === showId)
document.getElementById(showId).style.display = "block";
else
document.getElementById(divIds[i]).style.display = "none";
}
}
</script>
Then your links at the top will look like this:
1
Haven't tested it, but that's the idea. Downsides are you have to maintain the div in 3 places in code
In the var divIds array.
In the html tag itself.
In the links across the top.
You could write some javascript to generate all 3, taking away the maitenance part of it entirely.
As for using jQuery in an offline doc, the best route would probably be to include the text of the jquery.min.js file in the doc itself inside of <script></script> tags. That way you don't have to worry about paths and what-not.
You may do something like that (don't judge me on js coding style, i'm not a js ninja):
window.onload = function() {
var outer = document.getElementById("all");
for (var i=0; i < outer.childNodes.length; i++) {
outer.childNodes[i].addEventListener("click", doSomething);
}
function doSomething() {
// here you can run loop for changing display style for you divs
console.log(this.id);
}
}
I made an unobtrusive example without knowing the div ids:
http://jsfiddle.net/8pQzx/2/
Its more code but this is what you get if you dont want to use a js lib. ;)
I have a simple if statement in my view that returns x = 0 or 1. Based on this simple result, I want to change the styling of the div that contains the entire section.
<div>
conditional that returns x=1 vs x=0 (and a few displayed items)
based on this loop, restyle the div
</div>
Let's say, if x = 1, I want to make background-color:rgb(210,215,220);
How can I accomplish this? I am not experienced with Javascript but I'm sure any code required would be very simple. Thank you!
Add an ID to your DIV like:
<div ID="colorThis">
conditional that returns x=1 vs x=0 (and a few displayed items)
based on this loop, restyle the div
</div>
Then do this:
if(x==1)
{
document.getElementById('colorThis').style.background = 'rgb(210,215,220)';
}
<script>
if(x==1)
{
$("#divid").css("background-color","rgb(210,215,220)");
}
</script>
Include jQuery, and give the div's id to divid