Creating a div using JavaScript/Dom and a textarea - javascript

I have this code and it isn't working the way i want. I want it to create a new div under the other one everytime the button is clicked, but it is just changing the content of the div. help
<!DOCTYPE html>
<html>
<head>
<style>
p{
background-color: red;
font-family: arial;
}
</style>
</head>
<body>
Name: <textarea id="myText" value=""></textarea>
<button type="button" onclick="myFunction()">Enviar</button>
<div id="demo"></div>
<script>
function myFunction() {
var x = document.getElementById("myText");
var defaultVal = x.defaultValue;
var textoComentario = x.value;
if (defaultVal == textoComentario) {
alert("Digite um comentário!");
} else {
document.getElementById("demo").innerHTML = "<p>" + textoComentario + "</p>";
x.value = "";
}
}
</script>
</body>
</html>

You can try with jquery more easily:
$('<div/>').html(textoComentario).appendTo('#demo');
EDIT
You can make it with pure-javascript with createElement too:
http://www.w3schools.com/jsref/met_document_createelement.asp
Good luck!

I think you are looking for this:
WORKING:DEMO
HTML
NO CHANGE
CSS
NO CHANGE
JS/JQuery
function myFunction() {
var x = document.getElementById("myText");
var defaultVal = x.defaultValue;
var textoComentario = x.value;
alert(textoComentario);
if (defaultVal == textoComentario) {
alert("Digite um comentário!");
} else {
$("#demo").css("display","block");
$("#demo").append("<p>" + textoComentario + "</p>");
x.value = "";
}
}

Replace your
document.getElementById("demo").innerHTML = "<p>" + textoComentario + "</p>";
into $('#demo').append("<p>" + textoComentario + "</p>");
It will work.......

Related

How To Convert CSV file to HTML table

i have csv file with the content :
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
I create Javascript/HTML code to pick up that file and display the content
<html>
<head>
<title>show csv</title>
</head>
<body>
<input type="file" id="fileinput" multiple />
<div id="result"></div>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
var res = document.getElementById("result");
res.innerHTML = "Got the file<br>"
+"name: " + f.name + "<br>"
+"type: " + f.type + "<br>"
+"size: " + f.size + " bytes</br>"
+ "starts with: " + contents;
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',readMultipleFiles, false);
</script>
</body>
</html>
and the output is like :
output
question : How can i convert the content or the data to array and showing as html table ?
thanks for any help.
You can convert csv data into array and then into html table. I have added \n into your new line. Please add the \n to your code when there is a new line.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
I found Kapila Perera's answer to be very useful. However, the last element of each row was being cropped due to the slice(0,-1) use. Building on Perera's answer, in the example below I've used slice() instead.
I've also separated out the first row lines[0] as a header row and loop from 1 instead (which won't always be the case that csv contains headers but is explicitly called out in the example).
Finally, I've added the tbody tags when the output gets wrapped but this probably isn't required.
<script type="text/javascript"charset="utf-8">
var div = document.getElementById('container');
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"), output = [], i;
/* HEADERS */
output.push("<tr><th>"
+ lines[0].slice().split(",").join("</th><th>")
+ "</th></tr>");
for (i = 1; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice().split(",").join("</td><td>")
+ "</td></tr>");
output = "<table><tbody>"
+ output.join("") + "</tbody></table>";
div.innerHTML = output;
</script>

HTML - JavaScript - Adding and Deleting/Hiding Elements

In my website the user is going to select an image, that image will then be inserted into a div tag. I need it so when the user clicks the image that was inserted into the div then it will be removed (deleted or hidden) from the div. I've tried:
document.getElementById("elementId").style.display = "none";
and other similar things. I really just cant get this to work please help!
HTML + JavaScript code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
var addCard = function(cardName)
{
if("undefined" != document.getElementById("card" + cardNumber).value)
{
if(deck.indexOf(cardName) > -1)
{
}
else
{
if(deck.length != 1)
{
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if(deck.length >= 1)
{
cardNumber = 1;
}
}
}
}
</script>
</head>
<body>
<div id = "card1" class = "cards"></div>
<div id = "1">
<img class = "cardSize" onclick = "addCard('Archer')" src = "Images/Cards/Archer.png">
</div>
</body>
CSS Code:
.cards
{
height:150px;
width:125px;
float:left;
margin-left:6.2%;
margin-bottom:30px;
border:5px solid #ff6666;
background-color:#ff6666;
}
.cardSize
{
height:150px;
width:125px;
float:left;
margin-left:7%;
margin-top:30px;
}
You can delete the img by id.
Also fix the issue with the updateCards function:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = "updateCards(\'' + cardName + '\')" src = "' + cardName + '.png">';
For example,
<div id="card1" class="cards">
<img id="Archer" class="deckCardSize" onclick="updateCards('Archer')" src="Archer.png">
</div>
Then just remove the div with id="Archer":
document.getElementById("Archer").remove();
FYI, I added a simple updateCards function that just hides the img instead of removing it entirely :
var updateCards = function(cardName) {
document.getElementById(cardName).style.display = 'none';
}
You need to attach a click event listener to a class that is applied to all inserted images. the function that the listener fires would then apply css.style.display = "none" to this
First, remove all spaces between attributes and its values (I mean everywhere in your code), that is:
<div id="card1" class="cards"></div><!-- correct -->
<div id = "card1" class = "cards"></div><!-- incorrect -->
Second, you have an error in your code here:
document.getElementById("card" + cardNumber).innerHTML = '<img id = "' + cardName + '" class = "deckCardSize" onclick = updateCards(' + cardName + ') src = "Images/Cards/' + cardName + '.png">';
You have missed double quotes around onclick's value. Replace it with this:
document.getElementById("card" + cardNumber).innerHTML = '<img id="' + cardName + '" class="deckCardSize" onclick="updateCards(' + cardName + ')" src="Images/Cards/' + cardName + '.png">';
Also, you have to define function updateCards(name), it maybe empty, but it must exists. If it doesn't exists, than any javascript code will stops running after you clicked on that image.
Third, <div id = "1"> has an error too. id attribute must starts from a letter.
here is working code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
<script>
var cardNumber = 1;
var deck = [];
function addCard(cardName) {
if ("undefined" != document.getElementById("card" + cardNumber).value) {
if (deck.indexOf(cardName) > -1) {
} else {
if (deck.length != 1) {
deck.push(cardName);
document.getElementById("card" + cardNumber).innerHTML = '<img id="img' + cardName + '" class="deckCardSize" onclick="updateCards(\'' + cardName + '\')" src="Images/Cards/' + cardName + '.png">';
cardNumber += 1;
}
if (deck.length >= 1) {
cardNumber = 1;
}
}
}
}
function updateCards(cardName) {
//some work
document.getElementById("img" + cardName).remove();
}
</script>
</head>
<body>
<div id="card1" class="cards"></div>
<div id="main1">
<img class="cardSize" onclick="addCard('Archer')" src="Images/Cards/Archer.png">
</div>
</body>
Tested and worked!

Jquery append not working outside of function

Hi I want to just add the group ID to the start of the web page, I'm trying to append it to the div "test", and then add a space - allow it to pull data from the yammer API, and then loop through groups with a separation including the group ID. Can anyone tell me why it will print to the webpage in the callback but not outside of the callback? Thanks :)
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
</script>
</head>
<body>
<div id="test">User Emails in Yammer Group IDs</div>
</body>
</html>
because your script is not able to find $('#test') div. As you have not put any .ready() event block for document the script gets executed before $('#test') div appears.
So you need to wrap your code inside doc ready block:
$(function(){
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
});
Edits:
You can move your append in here:
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>"); // <----move it here.
}
});
}
write your script at the bottom of page or put the test div at the top.
you are running your js code before the tag is even rendered ... it wont find div so it wont append anything
IT NOT SHOULD BE LIKE THIS
<script>
$("#test").append("ghgh");
</script>
<div id = "test"> jj </div>
IT SHOULD BE LIKE THIS
<div id = "test"> jj </div>
<script>
$("#test").append("ghgh");
</script>
EDIT 1:
If you really want to run your code first then append all the text in a string type variable and then at the end just add it the to value of div.
EDIT 2:
Like this
<script>
for( condtion counter etc)
{
str_var+= "your text";
}
</script>
and then after running your srcipt
$("#test").text(str_var); or $("#test").val(str_var); or append
Solutions:
1.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function(){
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
});
</script>
</head>
<body>
<div id="test">User Emails in Yammer Group IDs</div>
</body>
2.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="test">User Emails in Yammer Group IDs</div>
<script>
var $ = jQuery;
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
</script>
</body>
</html>

how to check if a string contains substring and color it in javascript?

I have to create:
1 <input type="text">
1 <textarea>
1 <div>
1 <button>
I have to fill the div with the textarea's content but if the content contains the input's string, I have to color it with <span>.
For example:
If the input contains "is" and the textarea contains "this is a beautiful day", I should put the following text in the div "this is a beautiful day" and color every time that the "is" string appears.
I should use indexOf() and a loop.
I have this:
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
if (x > -1)
If you absolutely have to use indexOf
while(b.indexOf(a) != -1) {
b = b.replace(a, '[X]');
}
while(b.indexOf('[X]') != -1) {
b = b.replace('[X]', '<span style="color:yellow;">' + a + '</span>');
}
$("#targetDiv").html(b);
You can also do this with RegExp
var a = $("#inp1").val();
var b = $("#txt").val();
var re = new RegExp(a, 'g');
var divContent = b.replace(re, '<span style="color:yellow;">' + a + '</span>');
$("#targetDiv").html(divContent);
Here is a fiddle with the indexOf
http://jsfiddle.net/eva3ttuL/1/
Here is the code to find and change color of all searched word
$(document).ready(function () {
$("#here").on("keydown keyup", function () {
var mytext = $(this).val();
var find = $("#find").val();
mytext=mytext.replace(new RegExp(find,"g"), "<span class='me'>"+find+"</span>");
$("#output").html(mytext);
});
})
.me{color: #00f;
background-color: #EFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="find" type="text" /><br/>
<textarea id="here"></textarea><br/>
<div id="output"></div>
Use JavaScript substring to split the string inside textarea and form a paragraph with the highlighted text.
HTML code:
<input id="inp1" type="text"/><br>
<textarea id="txt" col="10" row="5"></textarea><br>
<div id="fillarea">
click on check
</div>
<button id="check">check</button>
CSS for highlighting:
.highlight{
background-color:yellow;
}
jQuery code:
$('#check').on('click',function(){
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
var first = b.substring(0,x);
var middle = b.substring(x,x+a.length);
var last = b.substring(x+a.length,b.length);
var to_print = '<p>' + first + '<span class="highlight">' + middle + '</span> ' + last + '</p>';
$('#fillarea').empty();
$('#fillarea').append(to_print);
});
Demo fiddle here
It helps you jsfiddle
$('.submit').click(function(){
var content = $('.textarea').val();
var ans = content.replace($('.input').val(), "<span style='color:red;'>"+$('.input').val()+"</span>");
$('.text').html(ans);
});
var input = $("#inp1").val();
var text = $("#txt").val();
var div = $("#div");
div.val(text.replace(new RegExp(input,'g'), makeSpan(input)));
function makeSpan(str) {
return '<span style="background-color:red">' + str + '</span>';
}
Just try this
<html>
<title></title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var a = "is";
var b = "this is beautiful";
var x = b.indexOf(a);
if (x > -1) {
var re = new RegExp(a, 'g');
res = b.replace(re, "<span style='color:red'>"+a+"</span>" );
$("#result").html(res);
}
})
</script>
</head>
<body>
<div id="result"></div>
</body>
You can use IndexOf Javascript function
var str1 = "ABCDEFGHIJK";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

Categories