I want a user to be able to enter specific values into an input field and would like to be able to output the values WITH HTML "markup" such as '< div >' and '< p >' as text only. I have tried outputting it as a string as well but i cannot figure it out. Please help!
I would like it to operate like this:
Input value = x
Output = x
does it have to be output as a string so the browser doesnt only output = x? All insight helps!
Please See My Example Here:
<html>
<head>
<title>Markup Generator</title>
</head>
<body>
First name: <input id="first_name">
Last name: <input id="last_name">
<button id="say">Say hi!</button>
<hr>
<div id="result"></div>
<script>
function say_hi() {
var fname = document.getElementById('first_name').value;
var lname = document.getElementById('last_name').value;
var html = 'Hello <b>' + fname + '</b> ' + lname;
document.getElementById('result').innerHTML = html;
}
document.getElementById('say').addEventListener('click', say_hi);
</script>
<html>
<head>
<title>Markup Generator</title>
</head>
<body>
First name: <input id="first_name">
Last name: <input id="last_name">
<button id="say">Say hi!</button>
<hr>
<div id="result"></div>
<script>
function say_hi() {
var fname = document.getElementById('first_name').value;
var lname = document.getElementById('last_name').value;
var html = 'Hello <b>' + fname + '</b> ' + lname;
document.getElementById('result').innerText = html;
}
document.getElementById('say').addEventListener('click', say_hi);
</script>
You can use innerText instead of innerHTML
like this
document.getElementById('result').innerText = html;
Related
I'm kinda new to html/javascript. I wanted to store the user input value in array (already done this part) and display it into HTML table(I'm stuck at this one). When user press the button, the table will show up at the bottom.
Here's my code so far:
HTML
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<form>
<h1>Please enter data</h1>
<input id="title" type="text" placeholder="Title" />
<input id="name" type="text" placeholder="Name" />
<input id="tickets" type="text" placeholder="Tickets" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
</html>
This is my Javascript code:
var titles = [];
var names = [];
var tickets = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<tr>Titles</tr>" + titles.join(" ") + "<td></td>";
messageBox.innerHTML += "<tr>Name</tr> <td>" + names.join(" ") + "</td>";
messageBox.innerHTML += "<tr>tickets</tr> <td>" + tickets.join(" ")+ "</td>";
}
I can't display the array into the tables. I'm quite new to Javascript/HTML so any help would be appreciated. :D
As I have already commented, you will have to loop over array and compute html and set it. Your function clearAndShow will set last value only.
I have taken liberty to update your code. You should not save data in different arrays. Its better to use one array with proper constructed object.
JSFiddle
var data = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert() {
var title, name, ticket;
title = titleInput.value;
name = nameInput.value;
ticket = ticketInput.value;
data.push({
title: title,
name: name,
ticket: ticket
});
clearAndShow();
}
function clearAndShow() {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = computeHTML();
}
function computeHTML() {
var html = "<table>";
console.log(data)
data.forEach(function(item) {
html += "<tr>";
html += "<td>" + item.title + "</td>"
html += "<td>" + item.name + "</td>"
html += "<td>" + item.ticket + "</td>"
html += "</tr>";
});
html += "</table>"
return html;
}
article,
aside,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<head>
<script class="jsbin" src=""></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<body>
<form>
<h1>Please enter data</h1>
<input id="title" type="text" placeholder="Title" />
<input id="name" type="text" placeholder="Name" />
<input id="tickets" type="text" placeholder="Tickets" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
Please try and change your js code like below, not the most elegant but a start:
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>Titles</td>";
messageBox.innerHTML += "<td>Name</td>";
messageBox.innerHTML += "<td>Tickets</td>";
messageBox.innerHTML += "</tr>";
for(i = 0; i <= titles.length - 1; i++)
{
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>" + titles[i]+ "</td>";
messageBox.innerHTML += "<td>" + names[i] + "</td>";
messageBox.innerHTML += "<td>" + tickets[i]+ "</td>";
messageBox.innerHTML += "</tr>";
}
}
and your display html like so:
<table id="display"></table>
have a look at fiddle over here https://jsfiddle.net/gvanderberg/cwmzyjf4/
The data array in Rajesh's example is the better option to go for.
you deleted your last question about the numbering of authors, but I wrote a big answer to you for it. Just for you to have it :
Wow, man you have several problems in your logic.
First, you have to specify to your form not to submit when you click on one or the other submit buttons (Add a book, or Display book) :
<form onsubmit="return false;">
Second, you have to define your numbering var to 0 and use it when you want to assign a number to a book :
var numbering = 0;
Then, in your addBook function, you have to use that global numbering variable to set you no variable :
function addBook() {
numbering++; // increments the number for the books (1, 2, 3, etc)
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
...
}
Then you have all kind of mistakes like double ";" on certain lines etc.
A huge mistake is also done on your code when you use "forEach". Notice this function only works when you use jQuery library ! You have to include it before you use it :
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
An other huge mistake you do is that your "Display" button has the id "display" and your messageBox also has this id. This is forbidden because when you want to use the element which has this ID, Javascript won't know which of the two is the good one. So rename your button id in displayAuthors :
<input type="submit" id="displayAuthors" value="Display" onclick="displayBook()" />
Now, what you also can do, is to call your displayBooks function everytime you add a new book like this :
function addBook() {
numbering++;
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
data.push({
book: book,
author: author,
no: no
});
displayBook();
}
So I did all these things here on CodePen : https://codepen.io/liorchamla/pen/JMpoxM
The JQuery solution
Here you used the basics of Javascript (called Vanilla JS) which is very cool because you have to learn it, but I also wrote you a CodePen to show you how you could have done this with jQuery :-)
Here it is : http://codepen.io/liorchamla/pen/oxwNwd
Basicly, the javascript changed to this :
$(document).ready(function(){
var data = []; // data is an empty array
// binding the addBook button with the action :
$('#addBook').on('click', function(){
var book = {
title: $('#bookname').val(),
author: $('#authors').val(),
// note we won't use a numbering variable
};
data.push(book);
// let's automaticly trigger the display button ?
$('#displayBooks').trigger('click');
});
// binding the displayBooks button with the action :
$('#displayBooks').on('click', function(){
$('#display').html(computeHTML());
});
function computeHTML(){
// creating the table
html = "<table><tr><th>No</th><th>Book</th><th>Author</th></tr>";
// for each book in the data array, we take the element (book) and the index (number)
data.forEach(function(element, index){
// building the table row, note that index starts at 0, so we increment it to have a start at 1 if it is 0, 2 if it is 1 etc.
html += "<tr><td>" + parseInt(index++) + "</td><td>" + element.title + "</td><td>" + element.author + "</td></tr>";
})
html += "</table>";
// returning the table
return html;
}
})
You might find it complicated, but with time you will see that jQuery helps a lot !
They are lot of things we could enpower in this script but this is a good starting, don't you think ?
Cheers from Marseille, France !
<!DOCTYPE html>
<html>
<body onload="test();">
<script>
var number=1;
var input='<div><input type="text"><div>'+
'<div>'+number+'</div>'+
'<input type="text">';
function test(){
var div = document.getElementById('result');
div.innerHTML = div.innerHTML + input;
}
</script>
<div id="result"></div>
</body>
</html>
Can someone help me with code above? For some reason my first input box has size of 100 even should be 1.
You can't access JavaScript variables like number in php.
If you want to use number you need to do it in JavaScript like this:
<!DOCTYPE html>
<html>
<body onload="test();">
<script>
var number = 1;
var input = '<div><input type="text";';
input += number == 1 ? ' size="1" ' : ' size="100" ';
input += '><div>';
input += '<div>' + number + '</div>';
input += '<input type="text" ';
input += 1 == 1 ? ' size="1" ' : ' size="100" ';
input += '>';
function test() {
var div = document.getElementById('result');
div.innerHTML = div.innerHTML + input;
}
</script>
<div id="result"></div>
</body>
</html>
It is because php code is executed before js code. While php is executed it tries to check '+number+' is 1 which it is not. It is a string.
Php code is executed in server and js code in browser. That is huge difference.
Hi im trying to create an edit script in jquery that changes p content to input fields, and lets people edit them and then revert back to content.
my code:
<div class="addressblock">
<div class="data">
<p name="bedrijfsnaam">company name</p>
<p name="tav">to whom</p>
<p name="adres">street and number</p>
<p name="postcode">1234AB</p>
<p name="woonplaats">city</p>
<p name="land2" >Land</p>
</div>
Edit
</div>
Jquery =
$(document).ready(function () {
$(".editinv").click(function() {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if(edit_or_text == "edit"){
$(this).closest('div').find('p').each(function(){
var el_naam = $(this).attr("name");
var el_content = $(this).text();
$(this).replaceWith( "<input type='text' name='"+el_naam+"' id='" + el_id + "' value='"+el_content+"' />" );
});
$(".editinv").replaceWith( "<a href='#_' class='editinv' name='done' id='"+editid+"'>Done</a>" );
}
if(edit_or_text == "done"){
$(this).closest('div').find('input').each(function(){
var el_naam = $(this).attr("name");
var el_content = $(this).attr("value");
$(this).replaceWith( "<p name='"+el_naam+"' id='" + el_id + "'>'"+el_content+"' </p>" );
});
$(".editinv").replaceWith( "<a href='#_' class='editinv' name='edit' id='"+editid+"'>Bewerken</a>" );
}
});
});
When clicking on edit it changes perfectly to input fields and changes the edit button to a done button. A click on the done button is never registered though, while the class is the same.
Anyone got any ideas?
Thanks in advance!
EDIT: I created a JSfiddle of the problem http://jsfiddle.net/hBJ5a/
ITs quite simple, why doesn't the element accept a second click and revert back after already being changed?
Note that if you change the name of all the <p> tags to the same name, and try to revert them back, there is no way that javascript will know which value should go where.
You should add an additional parameter to your <p> tags that will indicate the type.
e.g.
<p data-type="text" name="bedrijfsnaam">compname</p>
when changed will turn into:
<input type="text" name="bedrijfsnaam" data-type="edit" value="compname" />
when you click the button to change back, you should simply use the same function you are currently using to change the <p>'s into <input>'s, but then reverse the order.
e.g.
function inputToParagraph() {
var inputs = $('input[data-type="edit"]');
inputs.each(function() {
$(this).replaceWith('<p data-type="text" name="'+$(this).attr('name')+'">'+$(this).attr('value')+'</p>');
});
}
ofcourse you should have other actions linked to your submit, an ajax request probably to update the database as well.
NOTE
Not tested, but do know that the function above, if all the attr's are specified will work.
It will directly replace the inputs with P tags with given attributes.
You will have to make sure when you make the <p>'s into <input>'s, you will have to make sure the inputs get the correct attributes as well.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var clickHandler = function() {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function() {
var el_id = $(this).attr("id");
var el_naam = el_id; //$(this).attr("name");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editinv").replaceWith("<a href='#_' class='editinv' name='done' id='" + editid + "'>Done</a>");
}
else /* if (edit_or_text == "done") */ {
$(this).closest('div').find('input').each(function() {
var el_id = $(this).attr("id");
//var el_naam = el_$(this).attr("name");
var el_content = document.getElementById(el_id).value;
// Attribute "name" not allowed on element "p" at this point
//$(this).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>'" + el_content + "' </p>");
$(this).replaceWith("<p id='" + el_id + "'>" + el_content + "</p>");
});
$(".editinv").replaceWith("<a href='#_' class='editinv' name='edit' id='" + editid + "'>Bewerken</a>");
}
document.getElementById("00001").onclick = clickHandler;
}
$(document).ready(function() {
document.getElementById("00001").onclick = clickHandler;
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div class="addressblock">
<div class="data">
<!-- Attribute "name" not allowed on element "p" at this point -->
<p id="bedrijfsnaam">company name</p>
<p id="tav">to whom</p>
<p id="adres">street and number</p>
<p id="postcode">1234AB</p>
<p id="woonplaats">city</p>
<p id="land2">Land</p>
</div>
Edit
</div>
</body>
</html>
Tested with Firefox 24.0 / Linux
try out jquery editable plugin
demo: http://www.appelsiini.net/projects/jeditable/default.html
<script type="text/javascript">
function Msg1(){
var a="noida";
id=1;
document.getElementById('myText').innerHTML = '<p onclick="nice(id)">'+a+'</p>';
}
function Msg2(){
document.getElementById('myText').innerHTML = 'Try message 1 again...';
}
</script>
<input type="button" onclick="Msg1()" value="Show Message 1" />
<input type="button" onclick="Msg2()" value="Show Message 2" />
<p id="myText"></p>
when i click on Show Message 1 it send id as a charecter not 1 i want to it send me 1
Thanks
You could do something like:
'<p onclick="nice(\"' + id + '\")">'+a+'</p>';
Or:
'<p onclick="nice(' + escape(JSON.stringify(id)) + ')">'+a+'</p>';
But this gets very unreadable very quickly.
Using this method you can't send things that aren't easily serializable. A more robust, and involved, solution would use the DOM API and EventListener API.
Example:
var id = { foo: "bar" };
var p = document.createElement("p");
p.addEventListener("click", function () {
nice(id);
});
p.innerText = "ipsum lorem";
document.body.appendChild(p);
You already have concatenation right near where you need it:
'<p onclick="nice('+id+')">'+a+'</p>';
make your innerHTML as
'<p onclick="nice(\"' + id + '\")">'+a+'</p>'
Replace your Msg1() Javascript function as below
function Msg1(){
var a="noida";
var id = 1;
document.getElementById('myText').innerHTML = '<p onclick="nice(\"' + id + '\")">'+a+'</p>';
}
I have several elements like this:
<div class="image_insert clearfix">
<label for="userfile3">Image 3</label>
<input type="file" name="userfile3" id="userfile3">
<label for="slika_naziv_eng3">Image Title</label>
<input type="text" name="slika_naziv_eng3" id="slika_naziv_eng3"/>
</div>
And JS for cloning:
var img_add = $('.img_add');
img_add.on('click', function(){
var img_ins = $('.image_insert'),
i = img_ins.length,
clon = img_ins.first().clone().attr({'class' : 'image_insert clearfix', 'name' : 'userfile' + i}).insertAfter(img_ins.last());
});
I need to change all attributes where there is a number. Every time new element is added, it needs to count number of elements and the new number will be number of elements + 1. How can I do this?
I've grabbed this from something similar id written in the past
$("#containerDiv").find("div").each(function(){
lastVersionNumber = jQuery(this).attr("id").replace(/\D/g, "")/1;
});
newVersionNumber = lastVersionNumber + 1;
# build the new version HTML string
var sHTML = "<div name='mydiv'>";
sHTML += jQuery("#templateCode").html()
sHTML = sHTML.replace(/<input/i, "<input name='v"+newVersionNumber+"_name'");
sHTML += "</div>";
$("#containerDiv").append(sHTML);
try this: clon contains the new element, so, you need to find your element
<!DOCTYPE html>
<html>
<head>
<title>Clone Elements with Jquery by #MaoAiz + Sasha</title>
</head>
<body>
<button class="img_add">New</button>
<div class="image_insert clearfix">
<label for="userfile1" class="img-label">Image 1</label>
<input type="file" name="userfile1" id="userfile1">
<label for="slika_naziv_eng1">Image Title</label>
<input type="text" name="slika_naziv_eng1" id="slika_naziv_eng1"/>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
var img_add = $('.img_add');
img_add.on('click', function(){
var img_ins = $('.image_insert'),
i = img_ins.length + 1;
clon = img_ins.first().clone().insertAfter(img_ins.last());
// clon contains the new element, so, you need to find your element
clon.find("input").first().attr({
'name' : 'userfile' + i,
'id' : 'userfile' + i
});
clon.find("input").last().attr({
'name' : 'slika_naziv_eng' + i,
'id' : 'slika_naziv_eng' + i
});
//plus:
clon.find(".img-label").text("Image " + i)
// view you cosole in Chrome Ctrl + Shift + j
console.log("Elements: " + i)
});
</script>
</body>
</html>
I have a demo in github. https://github.com/MaoAiz/Formulario-Dinamico-JQuery