How to dynamically add ng-readonly attribute - javascript

In my JS code, I want to create an input element with ng-readonly attribute. My code is as follows:
var newClientNameInputBox = document.createElement("input");
newClientNameInputBox.name = "clientNames";
newClientNameInputBox.type = "text";
newClientNameInputBox.className = "form-control";
newClientNameInputBox["ng-readonly"] = "setReadonly";
However, newClientNameInputBox turns out to have only the attributes name, type, and class. The ng-readonly attribute is missing. How should I go about adding an ng-readonly attribute?

You can make use of: Compiler (aka $complie) is an AngularJS service which traverses the DOM looking for attributes. https://docs.angularjs.org/guide/compiler
Something like this should work:
var template = '<input name="clientNames" type="text" class="form-control" ng-readonly="setReadonly" />';
var newClientNameInputBox = angular.element(template);
var $compile = ...; // injected into your code
var scope = ...; // { setReadonly : true }
var parent = ...; // DOM Parent where you want to drop your input
var compiledElement = $compile(newClientNameInputBox)(scope);
parent.appendChild(compiledElement);

Related

From fetch request to DOM: How to convert the response into a walkable DOM structure? [duplicate]

Is there a way to convert HTML like:
<div>
<span></span>
</div>
or any other HTML string into DOM element? (So that I could use appendChild()). I know that I can do .innerHTML and .innerText, but that is not what I want -- I literally want to be capable of converting a dynamic HTML string into a DOM element so that I could pass it in a .appendChild().
Update: There seems to be confusion. I have the HTML contents in a string, as a value of a variable in JavaScript. There is no HTML content in the document.
You can use a DOMParser, like so:
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link
You typically create a temporary parent element to which you can write the innerHTML, then extract the contents:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div><span></span></div>';
var div= wrapper.firstChild;
If the element whose outer-HTML you've got is a simple <div> as here, this is easy. If it might be something else that can't go just anywhere, you might have more problems. For example if it were a <li>, you'd have to have the parent wrapper be a <ul>.
But IE can't write innerHTML on elements like <tr> so if you had a <td> you'd have to wrap the whole HTML string in <table><tbody><tr>...</tr></tbody></table>, write that to innerHTML and extricate the actual <td> you wanted from a couple of levels down.
Why not use insertAdjacentHTML
for example:
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here
Check out John Resig's pure JavaScript HTML parser.
EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
Okay, I realized the answer myself, after I had to think about other people's answers. :P
var htmlContent = ... // a response via AJAX containing HTML
var e = document.createElement('div');
e.setAttribute('style', 'display: none;');
e.innerHTML = htmlContent;
document.body.appendChild(e);
var htmlConvertedIntoDom = e.lastChild.childNodes; // the HTML converted into a DOM element :), now let's remove the
document.body.removeChild(e);
Here is a little code that is useful.
var uiHelper = function () {
var htmls = {};
var getHTML = function (url) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="url" type="string">The url to the file with the HTML</param>
if (!htmls[url])
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
htmls[url] = xmlhttp.responseText;
};
return htmls[url];
};
return {
getHTML: getHTML
};
}();
--Convert the HTML string into a DOM Element
String.prototype.toDomElement = function () {
var wrapper = document.createElement('div');
wrapper.innerHTML = this;
var df= document.createDocumentFragment();
return df.addChilds(wrapper.children);
};
--prototype helper
HTMLElement.prototype.addChilds = function (newChilds) {
/// <summary>Add an array of child elements</summary>
/// <param name="newChilds" type="Array">Array of HTMLElements to add to this HTMLElement</param>
/// <returns type="this" />
for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };
return this;
};
--Usage
thatHTML = uiHelper.getHTML('/Scripts/elevation/ui/add/html/add.txt').toDomElement();
Just give an id to the element and process it normally eg:
<div id="dv">
<span></span>
</div>
Now you can do like:
var div = document.getElementById('dv');
div.appendChild(......);
Or with jQuery:
$('#dv').get(0).appendChild(........);
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
Alternatively, you can also wrap you html while it was getting converted to a string using,
JSON.stringify()
and later when you want to unwrap html from a html string, use
JSON.parse()

get a specific id value from a html string in javascript via jquery

I have this html string in a javascript variable and want to get the id value.
I converted it to pure html and than I tried to get the id value of the div.
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.find('.multiid').attr("id");
The result should be var multiid = 3041 but it does not work.
The attribute id you are looking for is in the jQuery object itself. But find(.multiid) looks for elements with class multiid inside the object (as nested elements) which does not realy exists and the attr() returns undefined.
Try multiidhtml.attr("id");
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.attr("id");
console.log(multiid);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Consider the following example where you can use find() meaningful:
var rowData = "<div id='3041' style='height:100%;' >test <p class='multiid' id='myParagraph'>Nested P</p></div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.find('.multiid').attr("id");
console.log(multiid);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
.find() searches the descendants of the element, it won't match the element itself. You should wrap the HTML in another DIV so it won't be the top-level element.
var multidhtml = $("<div>", {html: rowData});
var multiid = multidhtml.find(".multiid").attr("id");
This is only necessary if .multiid might not be the top-level element. If it's always the top, use the simpler solution in the other answer.
.find() searches the descendants of the element, it won't match the element itself. SO use .closest() so that it searches from the root of selector DOM
var rowData = "<div class='multiid' id='3041' style='height:100%;' >test</div>";
var multiidhtml = $(rowData);
var multiid = multiidhtml.closest('.multiid').attr("id");
if you're sure that id attribute exists in the selected DOM you can directly find like this
multiid = multiidhtml.attr("id");
var rowData = "<div id='3041' style='height:100%;' >test <p class='multiid' id='myParagraph'>Nested P</p></div>";
var multidhtml = $("<div>", {html: rowData});
var multiid = multidhtml.find(".multiid").attr("id");

get innerHTML of the children of the currentTarget

I have this part of my html (more than one of same type):
<div class="this-product">
<img src="images/bag2.jpeg" alt="">
<span class="product-name">iPhone</span>
<span class="product-price">345445</span>
</div>
And this part of my javascript code meant to get the innerHTML of the span tags and assign them values as shown:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
var productName = document.getElementsByClassName('product-name')[0].innerHTML;
var productPrice = document.getElementsByClassName('product-price')[0].innerHTML;
var cartProductname = event.currentTarget.productName;
var cartProductprice = event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
Everything works well and every variable above has its value shown well apart from cartProductname and cartProductprice which display as undefined and also vscode tells me that productName is declared but not read. Where could I be wrong?
If I understand your question correctly, you could call querySelector on each product item element that you are iterating like so:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
// Update these two lines like so:
var productName = element.querySelector('.product-name').innerHTML;
var productPrice = element.querySelector('.product-price').innerHTML;
var cartProductname = productName; // event.currentTarget.productName;
var cartProductprice = productPrice; // event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
You can use event.currentTarget.querySelector('.product-name') to get element inside of another element

A HTML tag to store "javascript's data"?

I need to write some html with placeholder used for javascript.
ex:
<span><placeholder data-id="42" data-value="abc"/><span>
Later on, a script will access those placeholders and put content in (next to?) them.
<span><placeholder data-id="42" data-value="abc"><div class="Google"><input type="text" value="abc"/></div><span>
But the placeholder tag doesn't exist. What tag can be used? Using < input type="hidden" .../> all over feels wrong.
Creating Custom tag
var xFoo = document.createElement('placeholder');
xFoo.innerHTML = "TEST";
document.body.appendChild(xFoo);
Output:
<placeholder>TEST</placeholder>
DEMO
Note: However creating hidden input fields with unique ID is good practice.
give your span element an id like,
<span id="placeToAddItem"><span>
and then in jQuery,
$('#placeToAddItem').html('<div class="Google"><input type="text" value="abc"/></div>');
or else
var cloneDiv = $('.Google');
$('#placeToAddItem').html(cloneDiv);
Example
The best way to do this, is using <input type='hidden' id="someId" value=""> tags.
Then you can easily access them by using jQuery, and recall the variable or change it.
var value = $("#someId").val(); to get variable or $("#someId").val(value) to change it.
This complete, no jQuery solution allows you to specify the placeholder/replacement html as a string within the element that will be replaced.
EG HTML:
<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>
<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>
<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>
<span data-placeholder="<em>Post JS</em>">Pre JS</span>
<br />
<button id="test">click me</button>
JS:
Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)
var placeholders = document.querySelectorAll('[data-placeholder]'); //or by ids, classnames, element type etc
Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list.
NodeList.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i]);
}
return this;//return self to maintain chainability
};
Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string:
Object.prototype.replaceWith = function(htmlString) {
var temp = document.createElement('div');//create a temporary element
temp.innerHTML = htmlString;//set its innerHTML to htmlString
var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
this.parentNode.replaceChild(newChild, this);//replace old node with new
return this;//return self to maintain chainability
};
Put it all together:
placeholders.each(function(self){
self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});
Another example but here we only replace one specific element with some hard-coded html on click:
document.getElementById("test").addEventListener('click', function() {
this.replaceWith("<strong>i was a button before</strong>");
}, false);
DEMO: http://jsfiddle.net/sjbnn68e/
use the code below :
var x = document.createElement('placeholder');
x.innerHTML = "example";
document.body.appendChild(x);

Accessing HTML5 Custom Data Attributes for multiple instances of webpart

I would really appreciate some guidance. This is probably simple to some of you, but i can't figure it out.
Thanks for any input.
THE REQUIREMENT
I have a multi-tabbed control. One each tab, I have a custom reportviewer control.
I have added a custom attribute to the reportviewer in the code behind called "data-report-param".
I need to access the value of custom attribute "data-report-param" on the current tab on the client-side using javascript.
I have tried several ways including the following, but can't get to the value that is being created in the DOM.
MY CODE
//Attempt 1
var reportparamattribute = $('#ReportViewer1');
var reportparametervalue = reportparamattribute.getAttribute('data-report-param');
//Attempt 2
var reportparamattribute = document.getElementById('<%= ReportViewer1.ClientID %>');
var reportparametervalue = reportparamattribute.getAttribute('data-report-param');
//Also tried accessing the dataset
var reportparametervalue = reportparamattribute.dataset.report-param;
WHAT IS BEING PRODUCED IN THE DOM
('ctl00_m_g_66e41117_8ff5_4650_bf4d_7a4a25e326f3_ctl01_ReportViewer1_ctl04').control.HideActiveDropDown();" data-report-param="1068" interactivedeviceinfos="(Collection)">
('ctl00_m_g_9d6a6c3c_11d0_4e03_bbd2_b907172c437d_ctl01_ReportViewer1_ctl04').control.HideActiveDropDown();" data-report-param="1068" interactivedeviceinfos="(Collection)">
UPDATE- WORKING CODE BELOW
The key was passing the custom data attribute from the code behind and then accessing it in the $.cache as #popnoodles below indicated, and passing the clientID of the reportviewer into the javascript function to get to the current instance of the webpart child controls.
<input type="hidden" id="<%= ASP_SSRS.ClientID %>_myDataState"
onchange="compareUnitValues(this.id, this.parentNode.id, '<%= ReportViewer1.ClientID %>', '<%= ASP_SSRS.ClientID %>', '<%= btnSendHiddenField.ClientID %>');" />
<script type ="text/javascript">
function compareUnitValues(elemt, parent, reportviewerID, value1, value2) {
var myDataUnit = $("#" + elemt),
parentObject = $("#" + parent),
reportviewerObject = $("#" + reportviewerID),
ssrs = $("#" + value1),
btnSend = $("#" + value2);
var myDataUnitValue = myDataUnit.val();
var myDataUnitJSON = jQuery.parseJSON(myDataUnitValue);
var currentmyDataUnit = myDataUnitJSON.currentUnit.objectId;
var sessioncurrentObjectId = document.getElementById('<%= hiddenCurrentObjectId.ClientID %>').value;
ssrs.val(myDataUnitValue);
var currentReportViewerParam = $("#" + reportviewerID).attr("data-report-param");
if (currentmyDataUnit != currentReportViewerParam) {
btnSend.trigger("click");
}
}
FROM CODE BEHIND CREATE THE CUSTOM DATA ATTRIBUTE
ReportViewer1.Attributes.Add("data-report-param", parsedObjectId)
getAttribute will only give you the value that was in the generated or modified HTML not what is in the DOM. The data method never updates the HTML.
jQuery creates an empty object $.cache, which is used to store the values you set via the data method. Each DOM element you add data to is assigned a unique ID which is used as a key in the $.cache object.
Setting
$('#ReportViewer1').data('report-param', 1234);
Getting
var id = $('#ReportViewer1').data('report-param');
If you can use jquery why not just:
$("#reportviewer1").data('report-param');

Categories