get values from clicked paragraph with jquery - javascript

Can someone help me get the values of the firstName and the lastName from a paragraph that I click on so I can display them in another div. I only managed to get the whole text from the paragraph that I click on, but i need the values of the firstName and the LastName. Below is the commented code that I need help with. Thanks in advance.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
// $('#contacts').on('click', 'p', function (e) {
// $("#show-contact").show();
// $("#show-contact h2").text(newContact.firstName);
// $(".first-name").text(newContact.firstName);
// $(".last-name").text(newContact.lastName);
// });
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>

Wrap firstName and lastName with anchor tag (or etc) and get it over with this tag:
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
$(document).on('click', '.para',function(){
var fn = $(this).find('.fn').text();
var ln = $(this).find('.ln').text();
$('#show-contact').append('<p>First name: <span class="first-name">'+fn+'</span></p><p>Last name: <span class="last-name">'+ln+'</span></p>'); // Add
//$('#show-contact').html('<p>First name: <span class="first-name">'+fn+'</span></p><p>Last name: <span class="last-name">'+ln+'</span></p>'); // update
//console.log("first name is: " + fn + " last name is: " + ln);
});
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: <a class="fn">' + newContact.firstName + '</a> Last Name: <a class="ln">' + newContact.lastName + "</a></p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
// $('#contacts').on('click', 'p', function (e) {
// $("#show-contact").show();
// $("#show-contact h2").text(newContact.firstName);
// $(".first-name").text(newContact.firstName);
// $(".last-name").text(newContact.lastName);
// });
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
</div>
</div>
</div>
</div>

One possible solution is to extract firstname and lastname using substr as follows.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
$('#contacts').on('click', 'p', function (e) {
// Get current para's text
var txt = $(this).text();
// pre-define labels present in the text
var fnameLabel = 'First Name: ';
var lnameLabel = 'Last Name: ';
// define length of the labels
var fnameLabelLen = fnameLabel.length;
var lnameLabelLen = lnameLabel.length;
// define Index positions of the labels
var fnameLabelIdx = txt.indexOf(fnameLabel);
var lnameLabelIdx = txt.indexOf(lnameLabel);
// Get First Name value by calculating the Index position
// between labels first name and last name
var firstName = txt.substr(fnameLabelIdx+fnameLabelLen, lnameLabelIdx-fnameLabelLen);
// Get Last Name by calculating Index positions
// between lastname label and end of para
var lastName = txt.substr(lnameLabelIdx+lnameLabelLen, txt.length-lnameLabelLen);
$("#show-contact").show();
$("#show-contact h2").text(firstName);
$(".first-name").text(firstName);
$(".last-name").text(lastName);
});
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>

You can do this with regex.
function Contact(first, last) {
this.firstName = first;
this.lastName = last;
}
$(document).ready(function() {
let a_contacts = [];
$("#delBtn").click(function() {
$("li").remove();
});
$("#save").click(function() {
event.preventDefault()
var inputtedFirstName = $("input#new-first-name").val();
var inputtedLastName = $("input#new-last-name").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$("ul#contacts").append("<li class='contact'>" + "<p class='para' >" + 'First Name: ' + newContact.firstName + ' Last Name: ' + newContact.lastName + "</p>" + "<button class='btn del'>del</button>" + "</li>");
a_contacts.push(newContact);
$("input#new-first-name").val("");
$("input#new-last-name").val("");
});
$("#show-contact").hide();
$('#contacts').on('click', 'p', function (e) {
var name = $(this).html();
var fname = name.match(/(?<=First Name: ).*?(?= Last)/);
var lname = name.match(/(?<=Last Name: ).*$/);
$("#show-contact").show();
$("#show-contact .first-name").html(fname);
$("#show-contact .last-name").html(lname);
});
$('#contacts').on('click', '.del', function(event) {
$(event.target).parent().remove()
});
});
#contacts>li:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 id="haha">Address book</h1>
<div class="row">
<div class="col-md-6">
<h2>Add a contact:</h2>
<form id="new-contact">
<!-- form -->
<div class="form-group">
<label for="new-first-name">First name</label>
<input type="text" class="form-control" id="new-first-name">
</div>
<div class="form-group">
<label for="new-last-name">Last name</label>
<input type="text" class="form-control" id="new-last-name">
</div>
<button id="delBtn" class="btn">Add</button>
<button id="save" class="btn">Save</button>
</form>
<!-- form -->
<h2>Contacts:</h2>
<ul id="contacts">
</ul>
</div>
<div class="col-md-6">
<div id="show-contact">
<h2></h2>
<p>First name: <span class="first-name"></span></p>
<p>Last name: <span class="last-name"></span></p>
</div>
</div>
</div>
</div>

Related

how to clone div with event?

when I clone a div, I'd like the event "delete_row_sticker" to be cloned too but this isn't the case, I don't understand why.
html:
<div id="row_sticker_0" class="row mt-10 justify-content-around">
<div class="col-3">
<input type="text" id="width_sticker_0" name="width_sticker_0" class="form-control">
</div>
<div class="col-3">
<input value="foo" type="text" id="length_sticker_0 name="length_sticker_<?= $var?>" class="form-control">
</div>
<div class="col-3">
<input value="foo" type="text" id="quantity_stickers_0" name="quantity_stickers_0" class="form-control">
</div>
<div class="col-3">
<div id="delete_0" value="0" name="delete_0" class="hide delete_row_sticker">RAZ</div>
</div>
</div>
<div id="add_row_sticker" class="col-12">
<div><i class="fa-solid fa-plus"></i></div>
</div>
jquery to clone the div "row_sticker_0":
$(document).ready(function(){
var i = 1;
$("#add_row_sticker").click(function(){
var row_sticker_id = 'row_sticker_' + i;
$("#row_sticker_0").clone().appendTo("#sticker_added").prop('id', row_sticker_id);
$('#'+row_sticker_id +' input').each(function(value) {
value.value = "";
value.id += '_'+ i;
value.name += '_'+ i;
});
$('#'+row_sticker_id +' #delete_0').each(function(value) {
value.id = $('#'+row_sticker_id +' #delete_0').attr('id').slice(0,6);
value.id += '_'+ i;
});
i++;
});
});
jquery to delete a row:
$(document).ready(function(){
$(".delete_row_sticker").on('click', function() {
var index = $(this).attr('id');
index = index.slice(7, 8);
$('#row_sticker_' + index).remove();
});
});

What is preventing jQuery .click() function from executing?

This click function was previously working, until i added another button and some php...curious what's preventing it from executing as before, i've checked issues from other questions:
-jquery is properly loaded before the local script
-all functions are wrapped in .ready() [Why is this jQuery click function not working?
I found an interesting post about delegated event handling here: Jquery button click() function is not working
But i don't understand if or why this would apply to my situation...and if it does can someone explain to me its significance?
Javascript:
jQuery ( document ).ready( function ( $ ) {
function initColorPicker0 () {
for ( x=0; x < 4; x++ ) {
var canvasEl0 = document.getElementById('colorCanvas0');
var canvasContext0 = canvasEl0.getContext('2d');
var image0 = new Image(150, 150);
image0.onload = () => canvasContext0.drawImage(image0, 0, 0, image0.width, image0.height);
image0.src = "../img/color-wheel-opt.jpg";
}
canvasEl0.onclick = function ( mouseEvent0 ) {
var imgData0 = canvasContext0.getImageData(mouseEvent0.offsetX, mouseEvent0.offsetY, 1, 1);
var rgba0 = imgData0.data;
var bannerInput = $ ( '#bannerColor' );
bannerInput.val("rgba(" + rgba0[0] + ", " + rgba0[1] + ", " + rgba0[2] + ", " + rgba0[3] + ")" );
}
}
function demoBanner () {
// set click handler
$( '#demo' ).click( function () {
// store input values
var formObject = {
"prompt": document.getElementById('prompt').value,
"c2a" : document.getElementById('c2a').value,
"bannerColor" : document.getElementById('bannerColor').value,
}
//apply input values to style of new content
var newContent = " <div style='height: auto; padding: 15px 0px; margin: 0px -15px; background-color:" + formObject.bannerColor + ";'> <a href='#'> <p style=' margin-top: 0px; margin-bottom: 0px; text-align: center; color:" + formObject.promptTextColor + ";'>"+ formObject.prompt + " <a style='padding: 5px 12px; border-radius: 7px; background-color:" + formObject.c2aBG + "; color:" + formObject.c2aTextColor + " ' href='#'> <em> " + formObject.c2a + " </em> </a> </p> </a> </div>";
//set input as html content of demo
$( 'div.demo' ).html( newContent );
})
}
// called functions
$ ( function () {
initColorPicker0();
demoBanner();
});
});
HTML:
<div id="demo" class="demo"></div>
<div class="container">
<div class="row">
<div class="col-sm-3 text-center">
<div class="form-group">
<br>
<form action="test.php" method="post" name="form">
<label for="prompt">Prompt:
<input class="form-control" name="prompt" id="prompt" type="text">
</label>
<label for="c2a">Call-to-Action:
<input class="form-control" name="c2a" id="c2a" type="text">
</label>
<label for="bannerColor">Banner Background Color:
<input class="form-control" name="bannerColor" id="bannerColor" type="text">
<canvas style="border-radius:50%;" id="colorCanvas0" class="color-canvas" width="150" height="150"></canvas>
</label>
<input id="demo" type="button" class="btn btn-warning" value="Demo Banner">
<br>
<br>
<input id="submit" type="submit" class="btn btn-success" name="submit" value="Submit Form">
</form>
</div>
</div>
</div>
</div>
<!--jquery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- local JS -->
<script src="http://localhost:8888/vorotech_site/js/banner-tool.js"> </script>
EDIT: $( '#demo' )
First of all, for .click(), it passes an event to the callback. For type="submit", this includes submitting the form. Would advise using .preventDefault().
Here is an example including some jQuery cleanup. Also tried to retain proper object indexes.
$(function() {
function initColorPicker0() {
var canvasEl0, canvasContext0;
for (x = 0; x < 4; x++) {
canvasEl0 = $('#colorCanvas0')[0];
canvasContext0 = canvasEl0.getContext('2d');
var image0 = new Image(150, 150);
image0.onload = () => canvasContext0.drawImage(image0, 0, 0, image0.width, image0.height);
image0.src = "../img/color-wheel-opt.jpg";
}
canvasEl0.onclick = function(mouseEvent0) {
var imgData0 = canvasContext0.getImageData(mouseEvent0.offsetX, mouseEvent0.offsetY, 1, 1);
var rgba0 = imgData0.data;
var bannerInput = $('#bannerColor');
bannerInput.val("rgba(" + rgba0[0] + ", " + rgba0[1] + ", " + rgba0[2] + ", " + rgba0[3] + ")");
};
}
function demoBanner() {
// set click handler
$('#demo').click(function(e) {
e.preventDefault();
// store input values
var formObject = {
prompt: $('#prompt').val(),
c2a: $('#c2a').val(),
bannerColor: $('#bannerColor').val(),
};
//apply input values to style of new content
var newContent = $("<div>").css({
height: "auto",
padding: "15px 0px",
margin: "0px -15px",
"background-color": formObject.bannerColor,
});
$("<a>", {
href: "#"
}).appendTo(newContent);
$("<p>")
.css({
"margin": "0",
"text-align": "center ",
color: formObject.prompt
})
.html(formObject.prompt)
.appendTo($("a", newContent));
$("<a>", {
href: "#"
}).css({
padding: "5px 12px",
"border-radius": "7px",
"background-color": formObject.c2a,
color: formObject.c2a
}).html("<em>" + formObject.c2a + "</em>").appendTo("p", newContent);
//set input as html content of demo
$('div.demo').html(newContent);
});
}
// called functions
initColorPicker0();
demoBanner();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo" class="demo">DEMO</div>
<div class="container">
<div class="row">
<div class="col-sm-3 text-center">
<div class="form-group">
<br>
<form action="test.php" method="post" name="form">
<label for="prompt">Prompt:
<input class="form-control" name="prompt" id="prompt" type="text">
</label>
<label for="c2a">Call-to-Action:
<input class="form-control" name="c2a" id="c2a" type="text">
</label>
<label for="bannerColor">Banner Background Color:
<input class="form-control" name="bannerColor" id="bannerColor" type="text">
<canvas style="border-radius:50%;" id="colorCanvas0" class="color-canvas" width="150" height="150"></canvas>
</label>
<input id="demo" type="button" class="btn btn-warning" value="Demo Banner">
<br>
<br>
<input id="submit" type="submit" class="btn btn-success" name="submit" value="Submit Form">
</form>
</div>
</div>
</div>
</div>

Cannot display edit form when clicked on edit button?

I have made contact list app which displays contact details. By Default it shows 2 contact details.
In index.html I have made 2 functions called showContacts() and editContact(id).
I am dynamically populating div tags i.e editcontact & contactlist in index.html
When I click on edit button it should show 3 input elements to take input from user and one submit button I tried to implement it (see code below) but only search bar disappear's and only default contacts are shown which should not be shown and it should display editing form.
var array = [];
function Person(fullName, number, group) {
this.fullName = fullName;
this.number = number;
this.group = group;
array.push(this);
}
Person.prototype.getFullName = function() {
return this.fullName + ' ' + this.number + ' ' + this.group;
}
var p1 = new Person("Jonathan Buell", 5804337551, "family");
var p2 = new Person("Patrick Daniel", 8186934432, "work");
console.log(array);
document.getElementById("contactlist").innerHTML = '';
function showContacts() {
for (var i in array) {
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: ` + p1.fullName + `</p>
<p>Number: ` + p1.number + `</p>
<p>Group: ` + p1.group + `</p>
<button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactList").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`<div>
<input type="text" placeholder="Name here" id="nameInput2" value="` + array[id].fullName + `">
<input type="tel" placeholder="Number here" id="numberInput2" value="` + array[id].number + `">
<input type="text" placeholder="Group Here" id="groupInput2" value="` + array[id].group + `">
<button type="button" class="btn btn-success">Submit</button>
</div>`;
}
<div class="header">
<div id="dropdown">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Sort by Group
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>All</li>
<li>Work</li>
<li>Family</li>
</ul>
</div>
</div>
<div class="title">
<h2>All Contacts</h2>
</div>
<div class="button" id="addButton">
<p>
<a href="#">
<span class="glyphicon glyphicon-plus-sign"></span>
</a>
</p>
</div>
</div>
<div id="search">
<form>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
</div>
<div id="contactlist">
</div>
<div id="editcontact">
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
screenshots :
1) Before on click editContact :
2) After onclick editContact :
Live demo can be seen here :
https://jsfiddle.net/w2hoqmts/
A couple of things.
You made a typo with your contactlist in your html (should be contactList).
In your loop for showContacts you are setting id as index and should be like
function showContacts() {
for (var i in array) {
var id = array[i].number;
document.getElementById("contactList").innerHTML +=
'<ul><div><p>Name: ' + array[i].fullName + '</p><p>Number: ' + array[i].number + '</p><p>Group: ' + array[i].group + '</p>' +
'<button type="button" class="btn btn-warning" onclick="editContact(' + id + ')">Edit</button>' +
'<button type="button" class="btn btn-danger">Delete</button>' +
'</div>';
}
}
Your editContact method is using the id as an index (as previous), which is wrong. You could do something like this instead (see code below). I filter the array with people based on the unique id provided from the link when you click edit.
function editContact(id) {
var obj = array.filter(function (ele) {
console.dir(ele);
if (ele.number === id) return ele;
});
console.dir(obj);
document.getElementById("search").style.display = 'none';
document.getElementById("contactList").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
'<div>'+
'<input type="text" placeholder="Name here" id="nameInput2" value="'+ obj[0].fullName + '">'+
'<input type="tel" placeholder="Number here" id="numberInput2" value="' + obj[0].number + '">' +
'<input type="text" placeholder="Group Here" id="groupInput2" value="' + obj[0].group + '">' +
'<button type="button" class="btn btn-success">Submit</button>'+
'</div>';
}
I've made a updated fiddle based on your own
https://jsfiddle.net/w2hoqmts/3/
Following changes should be made in editContact() and showContacts() function.
function showContacts(){
for(var i in array){
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: `+ p1.fullName +`</p>
<p>Number: `+ p1.number +`</p>
<p>Group: `+ p1.group +`</p>
<button type="button" class="btn btn-warning" onclick="editContact(`+ id +`)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function editContact(id) {
document.getElementById("search").style.display = 'none';
document.getElementById("contactlist").style.display = 'none';
document.getElementById("editcontact").style.display = '';
document.getElementById("editcontact").innerHTML =
`<div>
<input type="text" placeholder="Name here" id="nameInput2" value="`+array[id].fullName+`">
<input type="tel" placeholder="Number here" id="numberInput2" value="`+array[id].number+`">
<input type="text" placeholder="Group Here" id="groupInput2" value="`+array[id].group+`">
<button type="button" class="btn btn-success">Submit</button>
</div>`;
}

set value of input vield without showing it

when i click on span remove address it removes it from ui but not from the list and the printed value of removeItem is an empty string "".
and how can i pass the stringList to input value="" with id clientAdd without showing it on the input .
var stringList = [];
$("#clientAdd").keypress(function(e) {
if (e.which === 13) {
$(".target").append("<a href='#' class='tag'>" + "<span class='removeAddress'>" + '+' + "</span>" + this.value + "</a>");
stringList.push(this.value);
this.value = "";
console.log(stringList);
$(document).on("click", ".removeAddress", function() {
var removeItem = $(this).parent().parent().val();
console.log(removeItem);
stringList.splice($.inArray(removeItem, stringList), 1);
$(this).parent().remove();
console.log(stringList);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label>Address *</label>
<div class="target"></div>
<input type="text" id="clientAdd" name="address" value="" class="form-control required">
</div>
</div>
</div>
Try this
Its parent text not a parent of parent .so you need get the text value of the parent use with $(this).parent().clone().children().remove().end().text() .It will get the parent text only .end() documentation
After removing clicked element .you are create the array using remaining removeddress via map function
var stringList = [];
$("#clientAdd").keypress(function(e) {
if (e.which === 13) {
$(".target").append("<a href='#' class='tag'>" + "<span class='removeAddress'>" + '+' + "</span>" + this.value + "</a><br>");
stringList.push(this.value);
this.value = "";
console.log(stringList);
$(document).on("click", ".removeAddress", function() {
var removeItem = $(this).parent().clone().children().remove().end().text();
console.log(removeItem);
stringList = $('.removeAddress').map(function(){
return $(this).parent().clone().children().remove().end().text()
}).get()
$(this).parent().remove();
console.log(stringList);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label>Address *</label>
<div class="target"></div>
<input type="text" id="clientAdd" name="address" value="" class="form-control required">
</div>
</div>
</div>
you can hide whole input or you can use input type="hidden". Usually you have one input displayed for humans as a event trigger and input hidden for the value which is processed on the server side
<div class="row">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label>Address *</label>
<div class="target"></div>
<input type="text" id="clientAdd" name="address" value="" class="form-control required">
<input type="hidden" id="clientAddCode" name="addressCode">
</div>
</div>
</div>
var stringList = [];
$("#clientAdd").keypress(function (e) {
if (e.which === 13) {
$(".target").append("<a href='#' class='tag'>" +"<span class='removeAddress'>"+'+'+"</span>"+ this.value + "</a>");
stringList.push(this.value);
this.value = "";
console.log(stringList);
$("#clientAddCode").val(stringList);
$(document).on("click", ".removeAddress", function() {
var removeItem = $(this).parent().parent().val();
console.log(removeItem);
stringList.splice( $.inArray(removeItem, stringList ) ,1 );
$(this).parent().remove();
console.log(stringList);
$("#clientAddCode").val(stringList);
});
}
});

Adding lines in a form an autocomplete function breaks

In a form I have 2 inputs. In the 1st input I use a datalist which I load it through JSON and the 2nd input is autocomplete it when the 1st input is changed.
Till here all works!
Then I added an add button where I add the same lines. The problem is that because I use id to select the input, when I add the new line I have the same id.. So the autocomplete doesn't work..
How can I solve this? Here the jssFiddle.
counter = 0;
var dataList = document.getElementById('products');
var jsonOptions = [{
"product": "11111",
"description": "description 1"
}, {
"product": "22222",
"description": "description 2"
}, {
"product": "33333",
"description": "description 3"
}];
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.value = item.product;
option.text = item.description;
dataList.appendChild(option);
$(function() {
$('#product').on('change keyup', function() {
var i = this.value;
var description = "";
var productsInBox = 0;
jsonOptions.forEach(function(a) {
if (a.product == i) {
description = a.description;
productsInBox = a.productsInBox;
}
});
$('#description').val(description);
});
});
});
$('#form1')
// Add button click handler
.on('click', '.addButtonDED', function() {
counter++;
var $template = $('#addLineInDed'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-index', counter)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="product"]').attr('name', 'product-' + counter).end()
.find('[name="description"]').attr('name', 'description-' + counter).end()
})
// Remove button click handler
.on('click', '.removeButtonDED', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-index');
counter--;
// Remove element containing the fields
$row.remove();
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" class="form-horizontal" role="form">
<fieldset>
<div class="form-group">
<div class="col-xs-2">
<input type="text" id="product" list="products" class="form-control" name="product-0" />
<datalist id="products"></datalist>
</div>
<div class="col-xs-4">
<input id="description" type="text" class="form-control" name="description-0" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default addButtonDED"><i class="fa fa-plus"></i></button>
</div>
</div>
<div id="addLineInDed" class="form-group hide">
<div class="form-group">
<div class="col-xs-2">
<input type="text" id="product" list="products" class="form-control" name="product-0" />
<datalist id="products"></datalist>
</div>
<div class="col-xs-4">
<input id="description" type="text" class="form-control" name="description-0" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default removeButtonDED"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<div class="col-md-10 ">
<button type="submit" name="formAction" value="next" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
Use classes, rename your selecs to array values:
counter = 0;
var dataList = $('.products');
var jsonOptions = [{
"product": "11111",
"description": "description 1"
}, {
"product": "22222",
"description": "description 2"
}, {
"product": "33333",
"description": "description 3"
}];
jsonOptions.forEach(function(item) {
var option = '<option value="' + item.product + '">' + item.description + '</option>';
dataList.append(option);
});
$(function() {
$('body').on('input', '.product,.products', function() {
var i = this.value;
var description = "";
var productsInBox = 0;
jsonOptions.forEach(function(a) {
if (a.product == i) {
description = a.description;
productsInBox = a.productsInBox;
}
});
$(this).closest('.form-group').find('.description').val(description);
});
});
$('#form1').on('click', '.addButtonDED', function() {
var $template = $('.form-group:last').clone(true, true).find('input').val('').end()
.find('.addButtonDED').removeClass('addButtonDED').addClass('removeButtonDED').end()
.find('i').removeClass('fa-plus').addClass('fa-minus').end();
$template.insertAfter('.form-group:last');
})
// Remove button click handler
.on('click', '.removeButtonDED', function() {
var $row = $(this).closest('.form-group');
$row.remove();
});
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" class="form-horizontal" role="form">
<fieldset>
<div class="form-group">
<div class="col-md-2">
<input type="text" list="products" class="form-control product" name="product[]" />
<datalist id="products" class="products"></datalist>
</div>
<div class="col-md-4">
<input id="" type="text" class="form-control description" name=" description[]" />
</div>
<div class="col-md-1">
<button type="button" class="btn btn-default addButtonDED"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="col-md-10 ">
<button type="submit" name="formAction" value="next" class="btn btn-primary">sUBMIT</button>
</div>
</fieldset>
</form>
</fieldset>
</form>
to read the values do a loop:
foreach($_POST['product'] as $product) {
//do stuf
}
Seeing as you said you've tried to use classes,
How about encapsulating your code so that you'll have a function like so:
function FilldatalistOptions(element,options)
You can then have the 2 datalists with different id's (products1 and products2 perhaps).
And just call the function like so:
var dataList1 = document.getElementById('products1');
var dataList2 = document.getElementById('products2');
FilldatalistOptions(datalist1, jsonOptions);
FilldatalistOptions(datalist2, jsonOptions);

Categories