JQuery - clone element and change attributes for multiple attributes - javascript

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

Related

How to output HTML '<div>' element with Javascript

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;

How to display user input data stored in array, using HTML table

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 !

Delete elements from observable array list

i was hoping if you could help me with a small javascript program, my program seems working fine when i add elements(customer and their type) to the array, but i am not sure how to add button next to the observable array elements so the user can delete their desired entries one by one? figure below shows what i want the program to look like:! many thanks!
function addCustomer()
{
var newIndex = customerList.length;
customerList[newIndex] = new Object;
customerList[newIndex].name = document.getElementById('name').value.trim();
customerList[newIndex].childOrAdult = childOrAdult.options[childOrAdult.selectedIndex].value;
displayCustomers();
}
function displayCustomers()
{
var message = '';
var message = '<tr><td><b> CUSTOMER NAME </b></td><td><b> CHILD/ADULT </b></td></tr>\n';
for (var i = 0 ; i < customerList.length ; i++)
{
message += '<br><tr><td> ' + customerList[i].name + ' </td><td> '
+ String(customerList[i].childOrAdult) + ' </br></td></tr>\n';
}
document.getElementById('outputDiv').innerHTML = message;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta charset="utf-8" />
<title>Giant Trampoline Customers</title>
<script src="" type="text/javascript"></script>
</head>
<body onload="displayCustomers();">
<h1 style="text-align: center;">Giant Trampoline Customers</h1>
<div id="outputDiv" style="text-align: center;"></div>
<br>
<div id="inputDiv" style="text-align: center">
<h3>Add A Customer:</h3>
New customer's name: <input type="text" id="name" maxlength="30" value="" size="30">
</select>
<button type="button" onclick="addAndDisplayCustomer();">add</button>
</div>
</body>
</html>
![desired result ][1]
jsFiddle demo (http://jsfiddle.net/json/asdzgst9/)
First, you might want to replace the <div id="outputDiv"> with a <table>, if you want to display the data in a table. So,
<div id="outputDiv" style="text-align: center;"></div>
becomes:
<table id="outputTable" style="text-align: center;"></table>
Second, you need to update the function where you display all elements from the customerList so it renders an extra table column with a button.
function displayCustomers() {
var message = '<tr><td><b> CUSTOMER NAME </b></td><td><b> CHILD/ADULT </b></td><td></td></tr>';
for (var i = 0 ; i < customerList.length ; i++) {
message += '<tr><td> ' + customerList[i].name + ' </td>';
message += '<td>' + customerList[i].childOrAdult + ' </td>';
// Here, create a third column with a button.
message += '<td><button onclick="removeCustomer(' + i + ')">remove this customer</button></td></tr>';
}
// Note: we have replaced the outputDiv with outputTable here!
document.getElementById('outputTable').innerHTML = message;
}
Third, a function that handles a click on the new button and removes an element from the list by the provided index.
function removeCustomer(index) {
// remove 1 element from the array customerList from the given index.
customerList.splice(index, 1);
displayCustomers();
}
Sorting
To sort the array, you can call a build-in method sort. See the updated jsFiddle demo (http://jsfiddle.net/json/asdzgst9/).
Update the function displayCustomers and add the the following snippet before the for loop:
customerList.sort(function (customerA, customerB) {
if (customerA.name < customerB.name) {
return -1;
} else if (customerA.name > customerB.name) {
return 1;
} else {
return 0;
}
});

Input to populate textarea - Javascript

I am making a coupon code page and i am struck in one thing, Maybe its easy for javascript buddies.The problem is
All output links are in one line, I want each link in different text area and able to copy from textarea
HTML Markup
<p>Enter your email or User ID
<input type="text" name="foo" id="foosite" value="" />
</p>
send
<div id="url_value"></div>
Javscript Code
var a = document.getElementById('link')
a.onclick = function(e){
e.preventDefault();
var value = document.getElementById('foosite').value;
var route = "http://www.domain.com/route.php?email=" + value + ', ';
var data = "http://www.domain.com/data.php?email=" + value + ', ';
var form = "http://www.domain.com/form.php?email=" + value;
document.getElementById('url_value').innerHTML = route + data + form
}
From the above code, Its generate all links in one line and looks ugly, I need it to show in 3 different textareas.
Like this Html
<p>Link 1</p>
<textarea name="route"> Output Link</textarea>
<p>Link 2</p>
<textarea name="data"> Output Link</textarea>
<p>Link 3</p>
<textarea name="form"> Output Link</textarea>
The issue with your code is this line:
document.getElementById('url_value').innerHTML = route + data + form;
What you're doing is injecting the DOM with all your links as one single line with no spaces between them.
The solution is to make a view for the results, and then inject them into the DOM afterwards as shown here:
var a = document.getElementById('link')
a.onclick = function(e){
e.preventDefault();
var value = document.getElementById('foosite').value;
var routeLink = "http://www.domain.com/route.php?email=" + value + ', ';
var dataLink = "http://www.domain.com/data.php?email=" + value + ', ';
var formLink = "http://www.domain.com/form.php?email=" + value;
var routeView = '<p>Link 1</p><textarea name="route">'+routeLink+'</textarea>';
var dataView = '<p>Link 2</p><textarea name="data">'+dataLink+'</textarea>';
var formView = '<p>Link 3</p><textarea name="form">'+formLink+'</textarea>';
document.getElementById('url_value').innerHTML = routeView + dataView + formView;
}
UPDATE:
If the HTML already exists, add IDs to your textarea fields.
<p>Link 1</p>
<textarea id="routeValue" name="route"> Output Link</textarea>
<p>Link 2</p>
<textarea id="dataValue" name="data"> Output Link</textarea>
<p>Link 3</p>
<textarea id="formValue" name="form"> Output Link</textarea>
Replace your JS with this code:
var a = document.getElementById('link')
a.onclick = function(e){
e.preventDefault();
var value = document.getElementById('foosite').value;
var routeLink = "http://www.domain.com/route.php?email=" + value + ', ';
var dataLink = "http://www.domain.com/data.php?email=" + value + ', ';
var formLink = "http://www.domain.com/form.php?email=" + value;
document.getElementById('routeValue').innerHTML = routeLink;
document.getElementById('dataValue').innerHTML = dataLink;
document.getElementById('formValue').innerHTML = formLink;
}

jquery toggling elements for editing

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

Categories