jquery Clone and with remove button of newly cloned item [duplicate] - javascript

All,
I need to add a "delete" link to the end of all of my cloned sections, but not the source of the cloned material. This is what I have so far
Need something like this:
Step One:
Step Two:(The cloned material does not get a delete link)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Demo</title>
<script type="text/javascript">
var uniqueId = 1;
$(function() {
$('.addRow').click(function() {
var copy = $("#cosponsors").clone(true).appendTo("#myForm");
var cosponsorDivId = 'cosponsors_' + uniqueId;
copy.attr('id', cosponsorDivId );
$('#myForm div:last').find('input').each(function(){
$(this).attr('id', $(this).attr('id') + '_'+ uniqueId);
$(this).attr('name', $(this).attr('name') + '_'+ uniqueId);
});
uniqueId++;
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div id="container">
<h3>Sponsors</h3>
<form action="" id="myForm">
<div id="cosponsors" style="padding:12px;">
<label>Sponsor Info:</label> <input type="text" id="cosponsorcontact" name="cosponsorcontact" placeholder="Name" title="Co-sponsor contact" />
<input type="text" id="cosponsoremail" name="cosponsoremail" placeholder="Email" title="Co-sponsor email" />
<input type="text" id="cosponsorphone" name="cosponsorphone" placeholder="Phone" title="Co-sponsor phone" />
</div>
</form>
<input type="button" class="addRow" value="Add Sponsor" />
</div>
</body>
</html>

Try this:
var deleteLink = $("<a>delete</a>");
deleteLink.appendTo(copy);
deleteLink.click(function(){
copy.remove();
});
Note that you'll need to style the delete link appropriately since it doesn't have an href.
JSFiddle: http://jsfiddle.net/5QBLB/

Related

javascript - jQuery functions not working on cloned

I have a problem with j query function calculate date after clone,
i need to auto calculate how many days after user select check in and check out date and put it in textbox , its working for first row but not working with cloned rows
DEMO
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal(){
if(document.getElementById("drop_date")){
document.getElementById("numdays2").value=GetDays();
}
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var genroomid = 2;
$( ".add-row" ).click(function(){
var $clone = $( "ul.personal-details" ).first().clone();
var $input = $clone.find('#roomid');
$input.val(genroomid).attr('genroomid' , +genroomid)
$clone.append( "<button type='button' class='remove-row'>-</button>" );
$clone.insertBefore( ".add-row" );
genroomid++; // increase id by 1
});
$( ".form-style-9" ).on("click", ".remove-row", function(){
$(this).parent().remove();
genroomid--;
});
});
</script>
</head>
<body>
<form name="form_reservations" method="post" action="add.php">
<span class="form-style-9">
<ul class="personal-details">
<label for="roomid">RoomID</label>
<input name="roomid[]" type="text" class="stretchnights" id="roomid" readonly="readonly" value="1">
<label for="chkin">Check IN</label>
<input class="stretchdate" size="15" width="15" id="pick_date" type="date" name="chkin[]" onchange="cal()" required/>
<label for="chkout">Check Out</label>
<input class="stretchdate" id="drop_date" type="date" name="chkout[]" onchange="cal()" required/>
<label for="nights">Nights
<input class="stretchnights" type="text" id="numdays2" name="nights[]" readonly /></label>
</ul>
<button type="button" class="add-row">+ New Client</button>
</span>
</form>
</body>
There are lot of issues in the snippet you shared, you are trying to using ID in the original element and cloning it, this is a bad idea for your use case. What you can do is convert it to class, and pass the target element in cal(). by doing that you can find the element. And your label for nights is not closed properly
replace your exiting script block
<script type="text/javascript">
function GetDays(target){
var dropdt = new Date($(target).find(".drop_date").val());
var pickdt = new Date($(target).find(".pick_date").val());
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal(target){
console.log($(target).parent(), $(target).parent().find('numdays2'));
$(target).parent().find('.numdays2').val(GetDays($(target).parent()));
}
</script>
and replace your .personal-details html block with this
<ul class="personal-details">
<label for="roomid">RoomID</label>
<input name="roomid[]" type="text" class="stretchnights" id="roomid" readonly="readonly" value="1">
<label for="chkin">Check IN</label>
<input size="15" width="15" id="pick_date" class="pick_date" type="date" name="chkin[]" onchange="cal(this)" required/>
<label for="chkout">Check Out</label>
<input id="drop_date" type="date" name="chkout[]" class="drop_date" onchange="cal(this)" required/>
<label for="nights">Nights </label>
<input class="numdays2" type="text" id="numdays2" name="nights[]" readonly />
This should solve the problem
You are using the same id in function call for the clones.

How do I add/remove text boxes with JQuery changing the variable name to keep the name attributes different?

I want to make a book catalog with JQuery to add books to a author. In the code That I have I am trying to add a author and have his books be in a array with his number only. Separated by other authors and their own arrays of books.
For example, when I press the button to add a author a input box appears so that I can add the authors name also a button to add a book that when I press that button I get an input box to add a books name.
When I press the add author again I want to be able to add another author with the same input boxes as before (adding more books to that author).
Also to add multiple books assigned to that author.
I have already done this in the pics but I get an array of everything. I want it to be separated by author.
author1 has an array of {book1, book2, book3...}
author2 has an array of {book13, book14, book15}
(i'm a beginner at JQuery)
This is the code that I have so far:
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script type="text/javascript" src="//code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<form role="form" method="post">
<p class="all_fields">
<button class="add_author">Add Author</button>
<div id="commonPart" class="commonPart">
<label for="author1">Author <span class="author-number">1</span></label>
<br/>
<input type="text" name="author" value="" id="author1" />
<br/>
<button class="add_book">Add book</button>
<div>
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function($){
var wrapper = $(".all_fields"); //Fields wrapper
var commonPart = $("#commonPart");
var add_author = $(".add_author"); //Add button ID
var add_subButton = $(".add_book"); //Add sub button ID
$('.my-form .add-box').click(function(){
var n = $('.all_fields').length + 1;
if( 15 < n ) {
alert('Stop it!');
return false;
}
$(add_author).click(function(e){
e.preventDefault();
var htmlToAdd = $('<label for="author' + n + '">Author <span class="author-number">' + n + '</span></label><br/><input type="text" name="author' + n + '" value="" id="author' + n + '" /><br/><button class="add_book">Add book</button><a class="add-book" href="#">Add Book</a><div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
htmlToAdd.hide();
$('.my-form p.all_fields:last').after(htmlToAdd);
box_html.fadeIn('slow');
return false;
});
$(add_book).click(function(e){
e.preventDefault();
var htmlToAdd = $('<div><input type="text" class="bookName" name="authBook' + n + '[]"/></div>');
htmlToAdd.hide();
$('.my-form p.all_fields:last').after(htmlToAdd);
box_html.fadeIn('slow');
return false;
});
$('.my-form').on('click', '.remove-box', function(){
$(this).parent().css( 'background-color', '#FF6C6C' );
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.box-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
</body>
</html>
updated code(fixed some bugs..), try this....
<!DOCTYPE html>
<html>
<head>
<title>Add or Remove text boxes with jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
<!--
#main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<button onclick="addAuthor()" >Add Author</button><br><br>
<div id="addAuth"></div>
<br><br>
<button onclick="submit()" >Submit</button>
</div>
<div id="result" ></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor(){
authors++;
var str = '<div id="auth'+authors+'"><input type="text" name="author" id="author'+authors+'" />'
+'<button onclick="addMore(\'auth'+authors+'\')" >Add Book</button>'
+'</div>';
$("#addAuth").append(str);
}
var count=0;
function addMore(id){
count++;
var str = '<div id="bookDiv'+count+'">'
+'<input class="'+id+'" type="text" name="book'+id+'" />'
+'<span onclick="addMore(\''+id+'\')" style="font-size: 20px; background-color: green; cursor:pointer;">+</span>'
+'<span onclick="removeDiv(\'bookDiv'+count+'\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">-</span>'
+'</div>';
$("#"+id).append(str);
}
function removeDiv(id){
var val = confirm("Are you sure ..?");
if(val){
$("#"+id).slideUp(function(){$("#"+id).remove();});
}
}
function submit(){
var arr = [];
for(i=1; i<=authors; i++){
var obj = {};
obj.name = $("#author"+i).val();
obj.books = [];
$(".auth"+i).each(function(){
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Please try this code and include jquery min js :
<div class="my-form">
<form role="form" method="post">
<p class="all_fields">
<div id="commonPart" class="commonPart">
<label for="author1">Author <span class="author-number"></span></label>
<input type="text" name="author" value="" id="author1" />
<br/>
<div>
<label for="author1">book <span class="author-number"></span></label>
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
<button type="button" class="add_author" onclick="AddCustomMOre();">Add More</button>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
</div>
<script> function AddCustomMOre(){
$(".all_fields ").append('<div id="commonPart" class="commonPart"><label for="author1">Author <span class="author-number"></span></label> <input type="text" name="author" value="" id="author1" /> <br/> <div><label for="author1">book <span class="author-number"></span></label> <input type="text" class="bookName" name="authBook[]"/></div> Remove</div>');
} </script>
You can try this....
<p class="all_fields">
<button class="add_author">Add Author</button>
<div class="commonPart">
<label for="author1">Author <span class="author-number">1</span></label>
<br/>
<input type="text" name="author1" value="" id="author1" />
<br/>
<button div-id="1" class="add_book">Add book</button>
<div id="books1">
<input type="text" class="bookName" name="authBook[]"/>
</div>
</div>
</p>
<script>
var c=1;
$(".add_author").on("click",function(){
c++;
$(".all_fields").append('<div class="commonPart"><label for="author'+c+'">Author <span class="author-number">'+c+'</span></label><br/><input type="text" name="author'+c+'" value="" id="author'+c+'" /><br/><button class="add_book" div-id="'+c+'">Add book</button><div id="books'+c+'"><input type="text" class="bookName" name="authBook[]"/></div></div>');
});
$(".add_book").on("click",function(){
var id=$(this).attr("div-id");
$("#books"+id).append('<input type="text" class="bookName" name="authBook[]"/>');
});
</script>

Calling a JS function with HTML form data

I'm having trouble getting a javascript function to run on the data from an html form.
I have this form in HTML:
<form id = "form1" onSubmit="getFormObj('form1')">
First name: <input type="text" name="FirstName" value="First"><br>
Last name: <input type="text" name="LastName" value="Last"><br>
Email: <input type="text" name="email" value="johndoe#email.com"><br>
Phone Number: <input type="text" name="phonenumber" value="Phone Number"><br>
<input id="button1" type="submit" value="Create Patient">
</form>
<script type="text/javascript">
document.write(PatientLabel);
</script>
The submit button is hooked up to a JavaScript function in JQuery:
$('#button1').click(function() {
createpatient(this);
});
The Javascript function I'm trying to run stores the form data to an object and then sets PatientLabel to one of the object's values:
var patientdata = {};
var PatientLabel = "";
function createpatient(formId) {
//Turn form data into array data.
var inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
patientdata[input.name] = input.value;
});
//If we got this far, print an example
patientLabel = patientdata["FirstName"];
}
However, when I run this code, the HTML Script that's supposed to print patientLabel doesn't show anything! Where did I go wrong?
Final Example:
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Change As You Like</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='rename.js'></script>
</head>
<body>
<form id='form1' name='form1'>
<label id='firstNameLabel' for='firstName'>First Name: </label><input type='text' id='FirstName' name='firstName' value='First' />
<label id='lastNameLabel' for='lastName'>Last Name: </label><input type='text' id='lastName' name='lastName' value='Last' />
<label id='emailLabel' for='email'>email: </label><input type='text' id='email' name='email' value='johndoe#email.com' />
<label id='phoneNumberLabel' for='phoneNumber'>phone: </label><input type='text' id='phoneNumber' name='phoneNumber' value='(555)555-5555' />
<input type='submit' id='button1' name='button1' value='Create Patient' />
</form>
</body>
</html>
Now on rename.js:
$(function(){
function createPatient(formElement) {
var patientData = {}, inputs = formElement.serializeArray();
$.each(inputs, function(i, o){
patientData[o.name] = o.value;
});
console.log(patientData.firstName);
// in FireBug could see Object like: console.log(patientData);
}
$('#form1').submit(function(){
// run other functions here
createPatient($(this));
return false;
});
});
You might change the way you call your function. Try this code if this will help createpatient($(this).attr('id'));

Button redirecting to new jsp page not working

I was trying to redirect to a n ew jsp page on click of a button like this :
<script type="text/javascript">
$(document).ready(function() {
$("input[type=button]").click(function () {
var x=$(this).siblings("input[type=text]").val();
$('#selectedempids').val(x);
alert("Would submit: " + x);
loaction.href='ProjectAssigning.jsp';
});
});
</script>
And in html I have something like :
<div>
<h1 align="center">ASSIGN PROJECTS</h1>
Assign Project To : <input type="text" id="demo-input-facebook-theme" name="blah2"></input>
<br></br>
<input type="hidden" name="selectedempids" id="selectedempids"></input>
Project Name : <input type="text" name="projecttitle" id="projecttitle"></input>
<br></br>
Project Description : <input type="file" name="description" id="description"></input>
<br></br>
<input type="button" value="Submit" />
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-facebook-theme").tokenInput("ValidEmployeeList.jsp", {
theme: "facebook"
});
});
</script>
</div>
But its not getting redirected.Please help me know the reason.
Instead of:
loaction.href = 'ProjectAssigning.jsp';
Use this:
window.location.assign('ProjectAssigning.jsp');

How to specify a dynamically created object

Hi I'm trying to create a family tree of some sort. I have a drop down box that's it options are being dynamically added when I make a new family and prompts the user to add a child of the selected family.
I'm trying to append the child after the table of the selected family but I have no idea what kind of ID are being generated when they're dynamically made
code is below
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
//To Create Familes
$('#submit').on('click', function() {
var table = $('<table></table>').addClass('table');
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each( function() {
str = '<td>' + $(this).val() + '</td>';
$(this).val('');
table.append( str );
});
$('#container').append(table);
$('#select').append($('<option />', { text: family } ) );
});
//To Create child to right family
$('#submit2').on('click', function() {
var child = prompt("Enter the name of the child you wanna put to the selected family ");
something.after(child);
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id = "child">
<select id ="select"></select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id = "container">
</div>
</body>
</html>
any idea's of how to append after the selected families? or is there a better of doing this
the best way is to actually add elements rather than HTML for example:
var test = document.createElement('table');
test.setAttribute('id', 'test_id');
document.body.appendChild(test);
console.log(document.getElementById('test_id'));
to reference it, be sure to add an id and/or a class using the setAttribute javascript call or the .attr() or .prop() methods in jquery.
That's not very clear as to exactly what you're trying to do, but here's a tidier version that adds the child as a new row after the family's row:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script>
$(function() {
var cur_id = 0;
//To Create Familes
$('#submit').on("click", function(ev) {
var id = "family" + cur_id++,
$row = $('<tr id="' + id + '"></tr>');
$('#select').append('<option value="' + id + '">' + $("#famname").val() + '</option>');
$('#family :text')
.each(function() {
$row.append('<td>' + $(this).val() + '</td>');
})
.val("");
$('#container table').append($row);
});
//To Create child to right family
$('#submit2').click(function(ev) {
var child = prompt("Enter the name of the child you wanna put to the selected family "),
id = $("#select").val();
$("#" + id)
.after("<tr><td>" + child + "</td></tr>");
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
<label>Enter Family Name <input type="text" name="famname" id="famname"></label><br>
<label>Enter Address <input type="text" name="address"></label><br>
<label>Enter Father's name <input type = "text" name="dad"></label><br>
<label>Enter Mother's name <input type="text" name="mom"></label><br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id="child">
<select id="select"></select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id="container">
<table class="table"></table>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
//To Create Familes
$('#submit').on('click',function(){
var table = $('<table></table>').addClass('table');
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each(function() {
str = '<td>' + $(this).val() + '</td>';
$(this).val('');
table.append(str);
table.addClass(family);
});
$('#container').append(table);
$('#select').append($('<option />', {text: family, value:family}));
});
//To Create child to right family
var fam, child, str;
$(document).on('change', '#select', function(){
$('#submit2').show();
$('#child_name').show();
fam = $(this).children('#select :selected').val();
});
$(document).on('click', '#submit2', function(){
child = $('#child_name').val();
$('#submit2').hide();
$('#child_name').hide();
str = '<td>' + child + '</td>'
$('.'+fam).append(str);
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<select id ="select">
</select>
<input type="text" id="child_name" style="display:none;">
<input id="submit2" type="submit" value="button" name="submit" style="display:none;">
<div id = "container">
</div>
</body>
</html>
this should do, I tested this already...hope this helps

Categories

Resources