I want to send variable into onclick function, but I did not succeed to get the suitable code.
this is the java code :
for (int i = 0; i < projetList.size(); i++) {
contenuTableHTML.append("<tr>");
contenuTableHTML.append("<td class='width1'><div class='coupe'>" + projetList.get(i).getProjectAbr() + "</div></td>");
contenuTableHTML.append("<td class='width3'><div class='coupe'>" + projetList.get(i).getProjectTkt() + "</div></td>");
List<String> objList = projetList.get(i).getObjectList();
contenuTableHTML.append("<div id='objList' name='objList' value='objList'>");
contenuTableHTML.append("<td class='width3'><div class='coupe'> <a href='#' **onclick='popupFunction(objList)**'>" + projetList.get(i).getObjectList().size() + "</div></td>");
contenuTableHTML.append("</div>");
contenuTableHTML.append("<td class='tableTicketsSummaryTd width3'><div class='coupe'>" + projetList.get(i).getProjectDomain() + "</div></td>");
contenuTableHTML.append("</tr>");
}
As below the javascript code:
function popupFunction(obj) {
objList = document.getElementById(obj);
console.log("objList ",objList);
console.log("obj: ", obj);
var w = window.open("", "", "width=600,height=300");
w.document.write(obj);
w.document.close();
w.focus();
}
I always get objList and obj as null.
The onclick template in html, should be dynamic to send an actual argument (objList) to the javascript function.
You can make use of template literals or dynamic strings while creating your HTML in the following way by adding (template literal) and accessing dynamic elements using ${element} inside the template literal``:
contenuTableHTML.append(`<div id=${objList} name=${objList} value=$[objList}>`);
contenuTableHTML.append(`<td class='width3'><div class='coupe'> <a href='#' onclick='popupFunction(${objList})'>` + projetList.get(i).getObjectList().size() + "</div></td>");
This will allow you to access objList and obj in your javascript function.
Related
I have this script that gets all the attributes and its values and outputs them on the page. The problem I am having is it's currently working with document.write but I want to put the results inside a p tag. When I try to do that it only shows one attribute and its value. How can I output all the attributes and its values inside the targeted p tag?
My code
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
document.write(attr.name + '="' + attr.value + '"');
/*document.querySelector('p').innerHTML= attr.name + '="' + attr.value + '"'; <-- This method only shows one attribute and its value :(*/
}
<div id="foo" class="bar baz" style="margin-left: 2px; height: 10px;"></div>
<p></p>
You should construct whole string and write to <p> once.
var content = [];
while (i--)
{
attr = attrs[i];
content.push(attr.name + '="' + attr.value + '"');
}
document.querySelector("p").innerHTML = content.join(" ")
You have to build a string inside the while loop and assign that string to innerHTML after the loop.
I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);
There are times that I need to assign a html snippet to a javascript var, such as,
var homePage =
'<div>' +
'<div class="header"><h1>Page Slider</h1></div>' +
'<div class="scroller">' +
'<ul class="list">' +
'<li><strong>Build Bot</strong></li>' +
'<li><strong>Medi Bot</strong></li>' +
'<li><strong>Ripple Bot</strong></li>' +
'</ul>' +
'</div>' +
'</div>';
This can work good, but it makes editing a bit hard. May I know any framework can do this elegantly?
Use handlebars.js this is how is works:
Server side:
Send a JSON object back to javascript. I usually use something like this:
echo json_encode(array('object_name'=>$obj));
HTML
Create a container on your page.
<div id="#my_template_container"></div>
Javascript:
usually in your AJAX success function:
Parse your data into a JSON object:
var my_obj= JSON.parse(data);
Create a reference to the template:
var tmpl = $("#my_layout").html();
Use the Handlebars engine to compile the template:
var theTemplate = Handlebars.compile(tmpl);
Append the template to the HTML
$('#my_template_container').html(theTemplate(my_obj));
Template
Access your object in the template by it's name, in this example it would be : object_name the variable I assigned in my echo json_encode(array('object_name'=>$obj)) statement from PHP.
Access properties of the object using {{Property_Name}}.
To access properties of object children use the nested path operator: {{Propert_Name.ID}}
<script id="my_layout" type="text/x-handlebars-template">
{{#object_name}}
'<div>' +
'<div class="header"><h1>Page Slider</h1></div>' +
'<div class="scroller">' +
'<ul class="list">' +
'<li><strong>{{property1}}</strong></li>' +
'<li><strong>{{property2}}</strong></li>' +
'<li><strong>{{property3}}</strong></li>' +
'</ul>' +
'</div>' +
'</div>';
{{/object_name}}
</script>
I created a very light plugin, just for the times, when you just want to use some html inside js, and do not require a lot of options provided my templating frameworks and thus want to avoid heavy js.
Coffee script
(($) ->
utCache = {}
$.fn.ut = (tmplID, obj) ->
_tmpl = (str) ->
fn = "var p=[]; p.push('" + str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^%]*%>)/g, "\t").split("'").join("\\'").split("\t").join("'").replace(/<%=(.+?)%>/g, "',$1,'").split("<%").join("');").split("%>").join("p.push('") + "'); return p.join('');"
new Function("o", fn)
_getData = (ele) ->
$(ele).html utCache[tmplID](obj)
#each ->
ele = this
utCache[tmplID] = _tmpl($(tmplID).html()) unless utCache[tmplID]
_getData ele
) jQuery
Javascript
(function($) {
var utCache;
utCache = {};
return $.fn.ut = function(tmplID, obj) {
var _getData, _tmpl;
_tmpl = function(str) {
var fn;
fn = "var p=[]; p.push('" + str.replace(/[\r\t\n]/g, " ").replace(/'(?=[^%]*%>)/g, "\t").split("'").join("\\'").split("\t").join("'").replace(/<%=(.+?)%>/g, "',$1,'").split("<%").join("');").split("%>").join("p.push('") + "'); return p.join('');";
return new Function("o", fn);
};
_getData = function(ele) {
return $(ele).html(utCache[tmplID](obj));
};
return this.each(function() {
var ele;
ele = this;
if (!utCache[tmplID]) {
utCache[tmplID] = _tmpl($(tmplID).html());
}
return _getData(ele);
});
};
})(jQuery);
You can use it simply like,
$('#my-div').ut("#my-template", { name: 'jashwant'});
when we have following HTML:
<div id='my-div'></div>
<script type='javascript' id='my-template'>
<p><%=o.name %> welcomes you !</p>
</script>
Do it with Javascript's document methods.
var topdiv = document.createElement('div');
var headerDiv = document.createElement('header');
var header = document.createElement('h1');
header.innerHTML = 'Page Slider';
headerDiv.appendChild(header);
// etc....
Or use templating.
Just use backslashes to escape line breaks.
Eg:
var homePage =
'<div> \
<div class="header"><h1>Page Slider</h1></div> \
<div class="scroller"> \
<ul class="list"> \
<li><strong>Build Bot</strong></li> \
<li><strong>Medi Bot</strong></li> \
<li><strong>Ripple Bot</strong></li> \
</ul> \
</div> \
</div>';
Use \n\ instead of \ if you want to include the line breaks in the string.
I am generating dynamic HTML and want to pass an array to the calling function. The array is also being dynamically generated.
The contents of pinfoarray are somewhat like this "Ice Hockey","Junior Basketball","Ladies Soccer"
var theHost = "<a href='#someDialog' onclick='chnghost(' + pinfoarray + ');' data-toggle='modal' class='button'>Change</a>";
How can make it send the array to the calling function without an error.
How about making it like this:
var anchor = document.createElement('a');
anchor.href = '#someDialog';
anchor.setAttribute('data-toggle','modal');
anchor.className='button';
anchor.onclick = function(){
chnghost(pinfoarray);
}
You need to properly terminate the string and encode the parameter. You also need to guard against reserved characters in your data (escapeHtml).
var theHost = "<a href='#someDialog' onclick='chnghost(" + escapeHtml(JSON.stringify(pinfoarray)) + ");' data-toggle='modal' class='button'>Change</a>";
If you're using jQuery, you can implement escapeHtml like so:
function escapeHtml(text) {
return $("<div/>").text(text).html();
}
You need to close the string double quote to put a javascript variable:
var theHost = "<a href='#someDialog' onclick='chnghost('" + pinfoarray + "');' data-toggle='modal' class='button'>Change</a>";