How to use Templates on javascript? - javascript

I Have A function that add html to a div.
var user = $("#ddlUser").val();
var role = $("#ddlUserRole").val();
var html = '<div class="calendaruser">';
html += '<span>' + user + '</span> <button type="button" class="btn btn-default btn-xs">הסר משתמש</button>';
html += '<div>' + role + '</div>';
html += '</div>';
$("#divCalendarUsers").append(html);
i'm looking for a better way to use the template.

You can use the template literal:
A little sample:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Array2Table</title>
</head>
<body>
<div id="tableContent"></div>
<script>
var country = ["Country1", "Country2", "Country3"];
var capital = ["City1", "City2" , "City3"];
const tmpl = (country,capital) => `
<table><thead>
<tr><th>Country<th>Capital<tbody>
${country.map( (cell, index) => `
<tr><td>${cell}<td>${capital[index]}</tr>
`).join('')}
</table>`;
tableContent.innerHTML=tmpl(country, capital);
</script>
</body>
</html>

To use template in javascript, try handlebarsjs.

I male a function that creates the element taking two arguments (role and user).The return of this function you can bind it in every DOM element you want
function createTemplate(user,role){
var divCalendar=$('<div class="calendaruser"></div>');
var buttonElm=$('<button type="button" class="btn btn-default btn-xs">הסר משתמש</button>');
var spanElm=$('<span>'+user+'</span>');
var divELm=$('<div>'+role+'</div>');
divCalendar.append(buttonElm).append(spanElm).append(divELm);
return divCalendar;
}
//Example below:
$('body').append(createTemplate('user_value', 'role_value'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to hide previous data?

Im doing some basic programming of Javascript and jquery.. Please run the snippet first to see the output.(cant post image :()
When i click 'saga' it append the information of saga.. later, if i click persona it append persona below of the existed data. I want it to be like this-When i click persona the previous data will vanish and replaced with new one.
my code:
Javascript
function myCar(carName, carPlate, carColor) {
this.carName = carName;
this.carPlate = carPlate;
this.carColor = carColor;
};
var Saga = new myCar('Saga', 'BLM2222', 'blue'),
Persona = new myCar('Persona', 'JKQ2390', 'red'),
Wira = new myCar('Wira','GVB3450','violet');
myCar.prototype.details = function($div){
$div.append('Car Name: ' + this.carName + '<br>' + 'Car Plate: ' + this.carPlate + '<br>' + 'Car Color:' + this.carColor + '<br>' + '<br>');
};
$(document).ready(function() {
$('#cars').click(function(e) {
var cars = $(e.target);
switch(cars[0].id) {
case 'sagabtn':
Saga.details($('#bigdiv'));
break;
case 'sonabtn':
Persona.details($('#bigdiv'));
break;
case 'wirabtn':
Wira.details($('#bigdiv'));
break;
}
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Proton</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="app.js"></script>
<!--<link rel="stylesheet" type="text/css" href="stylesheet.css"/>-->
</head>
<body>
<h1>Proton Cars</h1>
<div id="cars">
<button id="sagabtn">Saga</button>
<br><br>
<button id="sonabtn">Persona</button>
<br><br>
<button id="wirabtn">Wira</button>
<br><br>
</div>
<div id="bigdiv"></div>
</body>
</html>
Instead of using .append you can use .html. .append will add to the DOM. .html will replace the html.
Read these articles: http://api.jquery.com/html/ http://api.jquery.com/append/
function myCar(carName, carPlate, carColor) {
this.carName = carName;
this.carPlate = carPlate;
this.carColor = carColor;
};
var Saga = new myCar('Saga', 'BLM2222', 'blue'),
Persona = new myCar('Persona', 'JKQ2390', 'red'),
Wira = new myCar('Wira','GVB3450','violet');
myCar.prototype.details = function($div){
$div.html('Car Name: ' + this.carName + '<br>' + 'Car Plate: ' + this.carPlate + '<br>' + 'Car Color:' + this.carColor + '<br>' + '<br>');
};
$(document).ready(function() {
$('#cars').click(function(e) {
var cars = $(e.target);
switch(cars[0].id) {
case 'sagabtn':
Saga.details($('#bigdiv'));
break;
case 'sonabtn':
Persona.details($('#bigdiv'));
break;
case 'wirabtn':
Wira.details($('#bigdiv'));
break;
}
});
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Proton</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="app.js"></script>
<!--<link rel="stylesheet" type="text/css" href="stylesheet.css"/>-->
</head>
<body>
<h1>Proton Cars</h1>
<div id="cars">
<button id="sagabtn">Saga</button>
<br><br>
<button id="sonabtn">Persona</button>
<br><br>
<button id="wirabtn">Wira</button>
<br><br>
</div>
<div id="bigdiv"></div>
</body>
</html>
You can use document.getElementById("bigdiv").textContent = ""; to clear on each button press

Displaying multiple user outputs using JavaScript

I am trying to display multiple user outputs, so that when something is entered in the text field, it is captured and displayed in the div.
At the moment it keeps overwriting with the new result rather than adding to what is already displayed.
Can anyone help with this?
HTML:
<!DOCTYPE HTML>
<html lang="en">
<!-- more meta data needs to go in here -->
<head>
<script type="text/javascript" src="main_app_javascript.js"></script>
<link rel="stylesheet" type="text/css" href="">
<meta charset="UTF-8">
<title>List Check</title>
</head>
<body>
<input type="text" id="enter_box">
<button onclick="output_function()"> Add To List </button>
<div id="list_output"></div>
</body>
JavaScript:
function output_function() {
var user_input = document.getElementById("enter_box").value;
document.getElementById("list_output").innerHTML = user_input;
}
Do
document.getElementById("list_output").innerHTML += user_input + '<br />';
instead.
This will concatenate your value and add a line break at the end of the text, to create a "list". Notice the =+ and + '<br /> differences.
You could also try this
function output_function() {
'use strict';
var user_input = document.getElementById("enter_box").value;
var list_output = document.getElementById("list_output");
if( list_output.innerHTML === '' ) {
list_output.innerHTML = '<p>' + user_input + '</p>';
} else {
list_output.innerHTML += '<p>' + user_input + '</p>';
}
}

Bootstrap table pagination and searching is not working

I am new to bootstrap and working in D3.js, crossfilter.js to generate the table contents. I like to get the dataTable as in the following URL with some pagination and searching with in the datatable using bootstrap.
In that example the table is statically defined with id and class. I am able to run the html page with the desired output as in the example page source code.
But in my case I am generating a table from function and not able to get the pagination and searchBox on top of the table. I added all the supported files such as js and css files.
Here is my code and I just reduced the code to avoid more spaces in this portal. May I know where I am doing mistake.
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=us-ascii">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>DataTables example - Bootstrap</title>
<link rel="shortcut icon" type="image/png" href="/media/images/favicon.png">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/380cb78f450/integration/bootstrap/3/dataTables.bootstrap.js"></script>
</head>
<body>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/d3/2.10.0/d3.v2.min.js"></script>
<script type='text/javascript' src="crossfilter.js"></script>
<div id="Default" class="default"></div>
<script>
$(document).ready(function () {
$('#example').dataTable();
$('#Default').show();
});
d3.json("myJson.json", function (desing) {
var data = desing;
var ndx = crossfilter(data);
var state1 = ndx.dimension(function (d) {return d.region;});
var dist1 = ndx.dimension(function (d) { return d.cluster;});
var taluk1 = ndx.dimension(function (d) { return d.center;});
var village1 = ndx.dimension(function (d) { return d.loan_type_id;});
cfds = ndx.dimension(function (d) {return d.region; });
$("#Default").html(totable(cfds.top(Infinity)));
cfds.filterAll();
});
function totable(json) {
var html = "";
html += "<thead>"
html += "<tr>"
html += "<th>REGION</th>"
html += "<th>CLUSTER</th>"
html += "<th>CENTER</th>"
html += "<th>GLP MONTH</th>"
html += "<th>LOAN AMT DISBURSED</th>"
html += "<th>NEW MEMBERS</th>"
html += "<th>DEMAND</th>"
html += "<th>PRINCIPAL</th>"
html += "<th>INTEREST</th>"
html += "<th>WRITTEN OFF</th>"
html += "<th>HM-PROCESSED</th>"
html += "<th>HM-ELIGIBLE</th>"
html += "<th>Eligible %</th>"
html += "<th>LOAN TYPE</th>"
html += "</tr>"
html += "</thead>"
json.forEach(function (row) {
html += "<tr role='row'>";
for (key in row) {
html += "<td>" + row[key] + "</td>";
};
html += "</tr>";
});
return "<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%' role='grid' aria-describedby='example_info'>" + html + "</table>";
}
</script>
</body>
</html>
It is working after I put the supported js files has been defined upon the end of the body tag.Also I initiate the dataTable under d3 function. All goes well now.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://cdn.datatables.net/1.10.3/js/jquery.dataTables.min.js"></script>
</body>
</html>
Hope its useful for someone..

Reading <input> values from an iframe and sending it to another as HTML

How should I read values from iframe1 and send it to iframe2 as HTML? Either JavaScript or jQuery is acceptable - it does not matter. I'm new to javascript. I already found code like the one below, maybe this will help.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function getIframeText() {
var iframe0 = document.getElementById("iframe0");
var iframe0document=iframe0.contentDocument||iframe0.contentWindow.document;
var inputIframe = iframe0document.getElementById("frame_text");
alert(inputIframe.value);
}
</script>
</head>
<body>
<div>
<button onclick="getIframeText()">get iframe text</button>
<iframe id="iframe0" src="test.html" >
<input type=text id="parent_text">
</div>
</body>
</html>
Take a look to this: http://jsfiddle.net/nick_craver/c5JeU/2/
$('button').click(function(){
var fjq = $('#frame')[0].contentWindow.$;
var f = $('#frame').contents().find('#data');
f.append( '----------<br>');
f.append( 'test1: ' + fjq.data(f[0], 'test1') + '<br>test2: ' + fjq.data(f[0], 'test2') + '<br>' );
f.append( 'test3: ' + typeof (fjq.data(f[0], 'test3')) + '<br>' );
})
I found it on: Access jQuery data from iframe element

Save variable number of answers to single textbox with Java Script

I am learning JS and I am not yet familiar with internal workings. Can someone point out the error in my thinking?
The basic idea is to ask a complex question, construct the answer with JS (to a CSV syntax) and feed it to a textbox. (From here it will be processed to a db.) Example included below: How many children do you have? What is their names and age?
Perhaps, the new element generated by the first button is not added to the document? How to do this, or how to address the value in it?
How can I make the values submitted to previous lines stick in the event of adding a new line. For example 'Jack' and '10' is written to the first line, the user pressed the add new line, than this information should stay in the first line.
Incorrectly working example: The save button stops working if the code in the loop is added.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines = 0;
function addNew() {
lines++;
document.getElementById("qchildren-answer-wrapper").innerHTML += 'Gyermek neve:<input type="text" id="qchildrenname' + window.lines + '" /> Gyermek eletkora:<input type="text" id="qchildrenage' + window.lines + '" /><br/>';
}
function save() {
var answer = '';
for (var ii = 0; ii < window.lines; ii++) {
answer += document.getElementById('qchildrenname' + ii.toString()).value.toString() + ',' + document.getElementById('qchildrenage' + ii.toString()).value.toString() + ';';
}
document.getElementById("qchildren").value = answer;
}
< /script>
</body>
</html>
=Below code should work (AddNew function changed):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<p>How many children do you have? What is their names and age?</p>
<input type="text" id="qchildren" />
<div id="qchildren-answer-wrapper"></div>
<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>
<script>
var lines=0;
function addNew()
{
lines++;
var newElement = document.createElement("span");
newElement.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(newElement);
}
function save()
{
var answer='';
for (var ii=1;ii<=window.lines;ii++)
{
answer+=document.getElementById('qchildrenname'+ii.toString()).value.toString()+','+document.getElementById('qchildrenage'+ii.toString()).value.toString()+';';
}
document.getElementById("qchildren").value=answer;
}
</script>
</body>
</html>​
Try code like this:
function addNew()
{
var div = document.createElement('div');
div.innerHTML = 'Gyermek neve:<input type="text" id="qchildrenname'+window.lines+'" /> Gyermek eletkora:<input type="text" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(div );
lines++;
}
Demo: http://jsfiddle.net/JByVg/8/
What happens in your case is that all previously created elements are recreated again because element.innerHTML += "some_html" is equal to element.innerHTML = element.innerHTML + "some_html" or, more clear, I suppose, var oldHtml = element.innerHTML;element.innerHTML = ""; element.innerHTML = oldHtml + "some_html"
Browser does not populate value="..." entered by user when you do var oldHtml = element.innerHTML and after += you have old elements recreated without values entered by user. At the same time, appendChild does not recreate old elements.
This example demonstrates how .innerHTML returns only initial HTML (I've added value="test" to your qchildrenname element code)

Categories