I need to fetch an HTML element from an ExtJS panel and replace it with another HTML element.
I have a normal ExtJS panel -> rptPanel, whose innerHTML is copied to another panel -> outputDataPanel.
Please refer the code below.
var html = rptPanel.body.dom.innerHTML;
me.outputDataPanel.insert(me.itemIndex,{
html : html,
border : 0,
cls : 'htmlView_font_higher htmlView_font',
style : 'margin: 10px 0px 20px 0px; width: 100%;'
});
Now, I need to fetch an HTML element inside outputDataPanel (something like getElementById('table_data') on outputDataPanel ) and replace it with another HTML element.
Can anyone please help?
Try this (I suppose this is not Sencha's best practice):
outputDataPanel.getEl().down('#table_data')
You can set an ID to that element and get it like so:
// by id
var el = Ext.get("myDivId");
// by DOM element reference
var el = Ext.get(myDivElement);
// by id
var el = Ext.getDom('myDivId');
// by DOM element reference
var el = Ext.getDom(myDivElement);
Alternative way would be:
set an item-id to that element, lets say it's an item in the panel:
{
'text': 'myBTN',
iconCls: 'sprite',
disabled: true,
itemId: 'btn1',
handler: function(btn,e){
self.myFunction();
}
}
later on the code look for it by
this.down("#btn1")
Related
I have a Partial view with Markdown Editor i reference this Partial View in Main view along with the id attribute.
#Html.Partial("_MarkdownEditor", new { id = "executivesummary" })
#Html.Partial("_MarkdownEditor", new { id = "editorsection" })
Here trying to set id attribute dynamically like this..
<div id="#ViewData.Eval("id")">
</div>
This all works fine, My problem is i need to capture and set id dynamically to display the editor... here is the editor code. Here i have hard coded the querySelector with #exectuivesummary. I want to set it dynamically based on the id parameter passed to Partial view, so that i can i have different instances of the editor! How can this be done ?
<script type="text/javascript">
var editor = new tui.Editor({
el: document.querySelector('#executivesummary'),
previewStyle: 'vertical',
height: '300px',
initialEditType: 'wysiwyg'
//hideModeSwitch:true
});
function saveContent(e) {
var content = editor.getValue();
console.log(content)
e.preventDefault();
}
You must want to use a variable in the querySelector.
You can do it like this:
var id = 'executivesummary';
var matched = document.querySelector('#' + id);
console.log(matched);
<div id="executivesummary"></div>
In your case, you may do this: el: document.querySelector('#' + #ViewData.Eval("id"));
Hope it helps.
I am transitioning my code to ExtJs4.1.1.
In one part of the code I have used Javascript's appendChild() method to add new div elements to an existing div container.
I want this to be done in ExtJs now.
Existing code:
var container = document.getElementById('treeContainer');
var nodeDiv = document.createElement("div");
// nodeDiv related code... setting properties and attributes
nodeDiv.innerHTML = "<div class='NodeContent'>" + node.displayText + "</div>";
nodeDiv.className = "Node";
//... more such code...
//add div to the container
container.appendChild(nodeDiv);
This code works perfectly fine.
But now I am using an ExtJs Panel wherein I want to display the same content.
How do I do it?
I tried doing:
xtype: 'panel',
autoScroll: true,
border: 10,
bodyStyle:{"background-color":"white"},
height: Ext.getBody().getViewSize().height *0.80,
id: 'treeContainer'
Ext.getCmp('treeContainer').update(nodeDiv); //this didnt work
Ext.getCmp('treeContainer').addChildEls(nodeDiv); //no success
I get this output on firing the below command in debugger:
Ext.getElementById('treeContainer')
<div class="x-panel x-panel-default" style="height:553.6px;" id="treeContainer">
[object HTMLDivElement]
</div>
Any help!?
The panel's update function expects a HTML string instead of a DOM object:
// using a HTML string
Ext.getCmp('treeContainer').update("<div class='NodeContent'>" + node.displayText + "</div>");
// using a DOM object
Ext.getCmp('treeContainer').update(nodeDiv.outerHTML);
Note, that using this function will always replace all existing HTML content in the panel.
If you really want to append HTML (i.e. preserve existing HTML content), you need to get a target element to append your HTML/DOM node to.
This could be the panel's default render target element:
var panel = Ext.getCmp('treeContainer'),
renderEl = panel.isContainer ? panel.layout.getRenderTarget() : panel.getTargetEl();
// using a DOM node
renderEl.appendChild(nodeDiv);
// using a HTML string
renderEl.insertHtml('beforeEnd', "<div class='NodeContent'>" + node.displayText + "</div>");
Or - as this may change depending on your panel's layout - you just create a containg element in your initial html config:
{
xtype: 'panel',
id: 'treeContainer',
html: '<div class="html-content"></div>'
}
and append your content there:
Ext.getCmp('treeContainer').getEl().down('.html-content').appendChild(nodeDiv);
In any of the latter two cases, you should update the panel's layout afterwards, as you changed it's content manually:
Ext.getCmp('treeContainer').updateLayout();
I'm generating a div dynamically and I've to check whether a dynamically generated div exists or not ? How can I do that?
Currently I'm using the following which does not detects the div generated dynamically. It only detects if there is already an element with the id contained in the HTML template.
$(function() {
var $mydiv = $("#liveGraph_id");
if ($mydiv.length){
alert("HHH");
}
});
How can I detect the dynamically generated div?
If mutation observes aren't an option due to their browser compatibility, you'll have to involve the code that's actually inserting the <div> into the document.
One options is to use a custom event as a pub/sub.
$(document).on('document_change', function () {
if (document.getElementById('liveGraph_id')) {
// do what you need here
}
});
// without a snippet to go on, assuming `.load()` for an example
$('#container').load('/path/to/content', function () {
$(this).trigger('document_change');
});
If it is added dinamically, you have to test again. Let's say, a click event
$("#element").click(function()
{
if($("#liveGraph_id").length)
alert("HHH");
});
How you inserting your dynamic generated div?
It works if you do it in following way:
var div = document.createElement('div');
div.id = 'liveGraph_id';
div.innerHTML = "i'm dynamic";
document.getElementsByTagName('body')[0].appendChild(div);
if ($(div).length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id').length > 0) {
alert('exists'); //will give alert
}
if ($('#liveGraph_id_extra').length > 0) {
alert('exists'); //wont give alert because it doesn't exist.
}
jsfiddle.
Just for interest, you can also use a live collection for this (they are provided as part of the DOM). You can setup a collection of all divs in the page (this can be done in the head even before the body is loaded):
var allDivs = document.getElementsByTagName('div');
Any div with an id is available as a named property of the collection, so you can do:
if (allDivs.someId) {
// div with someId exists
}
If the ID isn't a valid identifier, or it's held in a variable, use square bracket notation. Some play code:
<button onclick="
alert(!!allDivs.newDiv);
">Check for div</button>
<button onclick="
var div = document.createElement('div');
div.id = 'newDiv';
document.body.appendChild(div);
">Add div</button>
Click the Check for div button and you'll get false. Add the div by clicking the Add div button and check again—you'll get true.
is very simple as that
if(document.getElementById("idname")){
//div exists
}
or
if(!document.getElementById("idname")){
// don't exists
}
How can I locate the tag which calls a JQuery script, when
the tag is dynamically loaded, so won't be the last
tag on the page?
I'm using the MagicSuggest autosuggest library. I want to give certain suggested items a different background color depending on their contents, which I'm currently doing by adding JQuery inside a tag, which I'm adding on to the String which is returned to be rendered inside the selection div. Then, to get the div the item is suggested in, I need to essentially get the parent() of the tag, and change it's css() properties. How can I get this current script tag however?
I'm currently assigned each new tag an id generated from incrementing a JS variable - which works, but isn't very 'nice'! Is there anyway I can directly target the tag with JQuery?
If it perhaps makes it clearer, here is my current selectionRenderer function.
selectionRenderer: function(a){
var toRet = a.english;
var blueBgScript = "<script id=ft" + freeTextFieldID + ">$('#ft" + freeTextFieldID + "').parent().css('background', 'blue');</script>"
if(a.id==a.english){
toRet += blueBgScript;
freeTextFieldID++;
}
return toRet;
},
Why don't you add some code at afterrender event instead? Add some tag to flag the options that need a different background, then detect the parents and add a class (or edit the bg property) or whatever you like:
var newMS = $('#idStr').magicSuggest({
data: 'states.php',
displayField: 'english',
valueField: 'id',
selectionRenderer: function(a){
var toRet = a.english;
if(a.id==a.english) toRet = "<span class='freetext'>" + toRet + "</span>";
return toRet;
},
});
$(newMS).on('selectionchange', function(event,combo,selection){
var selDivs = $(event.target._valueContainer[0].parentNode).children('div'); //Get all the divs in the selction
$.each(selDivs,function(index,value){ //For each selected item
var span = $(value).children('.freetext'); //It if contains a span of class freetext
if(span.length == 1) $(value).css('background','blue'); //Turn the background blue
});
If I want to append a button with my pic to the document, I would write:
$('#story_pages').append('<div><button value="'+window_value+'" onclick="reload_to_canvas(this.value)" > <img id= "w'+window_value+'", src="../pic/white_img.png", width="110px", height="110px"/> </button></div>');
It's too long and hard to debug. But how can I create an img tag, then wrapping it with a button tag and div tag...
Please suggest any clear and simple method with jQuery's help.
UPDATE:
story_pages is the jQuery UI dialog's id. I don't know if it affects or not.
UPDATE:
I found the problem. I want the image shown above on the button instead of a button and a image.
The script you give me will result this:
<div>
<button value="1"></button>
<img ......./>
</div>
The img tag has to be wrapped by button tag like:
<button>
<img.../>
</button>
So the image will attach on the button.
How about this:
var $button = $('<button>', {
value: window_value,
click: function() { reload_to_canvas(this.value); }
});
var $img = $('<img>', {
id : 'w'+ window_value,
src: '../pic/white_img.png'
})
.css({ height: '100px', width: '100px'});
$('#story_pages').append($('<div>').append($button, $img));
If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements.
try this
var div=$('<div>'); // creates new div element
//updated here
var img = $('<img />') .attr({ // create new img elementand adds the mentioned attr
id:'w'+window_value ,
src:"../pic/white_img.png",
width:"110px",
height:"110px"});
var button= $('<button/>', //creates new button
{
value: window_value, //add text to button
click: function(){ reload_to_canvas(this.value)} //and the click event
}).html(img); /// and <-- here... pushed the created img to buttons html
div.append(button); //append button ,img to div
$('#story_pages').append(div); //finally appends div to the selector
updated example fiddle
$('#story_pages').append(
$('<div>').append(
$('<button>', {
value : window_value
}).click(function() {
reload_to_canvas(this.value);
}).append(
$('<img>', {
id : 'w' + window_value,
src : '../pic/white_img.png'
}).width(110)
.height(110)
)
)
);