adding and deleting input fiel dynamically - javascript

I have a form in which I have add and minus buttons. On click event it should add a new input field and delete the selected input field correspondingly. Add button functions well in my case but deleting selected input field is not working.
I hope I explained my question properly if not let me know.
Thanks in advance.
.multivaluebox {
border: 1px solid #ccc;
background-color: white;
padding: 10px;
width: 60%;
}
.form-multivaluebox-textbox {
border: 1px solid #ccc;
border-radius: 0;
width: 100%;
}
.btncontainer {
width: 6%;
padding-left: 1%;
margin: 0;
}
.subbutton {
margin-top: 2px;
width: 34px;
height: 34px;
padding: 1%;
background-color: #0098ff;
color: white;
border: none;
font-weight: bold;
}
.addbutton {
width: 34px;
height: 34px;
padding: 1%;
background-color: #0098ff;
color: white;
border: none;
font-weight: bold;
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="multivaluebox ">
<input asp-for="#Model" class=" form-multivaluebox-textbox" value="hello" />
</div>
<div class="btncontainer col-sm-1">
<input type="button" class="addbutton " onclick="addtextbox(); " value="+" />
<br />
<input type="button" class=" subbutton" onclick="deletetextbox();" value="-" />
<script>
function addtextbox() {
var newdiv = document.createElement('div');
$(newdiv).addClass('multivaluebox');
newdiv.innerHTML = ' <input asp-for="#Model" class=" form-multivaluebox-textbox" value="#(Model?.Count >= 3 ? Model[2] : null)" id="Labels" />';
document.getElementById('wrapper').appendChild(newdiv);
 
}
function deletetextbox() {
var inputlist = document.getElementsByClassName('form-multivaluebox-textbox');
for (i = 0; i < inputlist.length; i++) {
if (document.getElementsByClassName('form-multivaluebox-textbox').isActive) {
$(this).remove();
}
}
 
}

I've put this together but it's not perfect.
It will allow you to add items to the wrapper and remove a selected item. However I'd suggest having a remove button at the end of each textbox to be more precise and user friendly.
var currentSelection;
function makeCurrentSelection(element){
currentSelection = element;
}
function addtextbox() {
var newdiv = document.createElement('div');
$(newdiv).addClass('multivaluebox');
newdiv.innerHTML = ' <input asp-for="#Model" class=" form-multivaluebox-textbox" value="#(Model?.Count >= 3 ? Model[2] : null)" id="Labels" onfocus="makeCurrentSelection(this)"/>';
document.getElementById('wrapper').appendChild(newdiv);
}
function deletetextbox() {
currentSelection.remove();
}
.multivaluebox {
border: 1px solid #ccc;
background-color: white;
padding: 10px;
width: 60%;
}
.form-multivaluebox-textbox {
border: 1px solid #ccc;
border-radius: 0;
width: 100%;
}
.btncontainer {
width: 6%;
padding-left: 1%;
margin: 0;
}
.subbutton {
margin-top: 2px;
width: 34px;
height: 34px;
padding: 1%;
background-color: #0098ff;
color: white;
border: none;
font-weight: bold;
}
.addbutton {
width: 34px;
height: 34px;
padding: 1%;
background-color: #0098ff;
color: white;
border: none;
font-weight: bold;
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper" class="multivaluebox ">
<input asp-for="#Model" class=" form-multivaluebox-textbox" value="hello" onfocus="makeCurrentSelection(this)">
</div>
<div class="btncontainer col-sm-1">
<input type="button" class="addbutton " onclick="addtextbox(); " value="+">
<br>
<input type="button" class=" subbutton" onclick="deletetextbox();" value="-">
</div>

Not perfect but this will give you some idea regarding how to add/delete elements in JavaScript.
Add elements in wrapper div
Removes element from wrapper div
Please expand the snippet while executing.
Hope this helps !
function addtextbox() {
var newdiv = document.createElement('div');
$(newdiv).addClass('multivaluebox');
newdiv.innerHTML = ' <input asp-for="#Model" class=" form-multivaluebox-textbox" value="#(Model?.Count >= 3 ? Model[2] : null)" id="Labels" />';
document.getElementById('wrapper').appendChild(newdiv);
 
}
function deletetextbox() {
var inputlist = document.getElementsByClassName('form-multivaluebox-textbox');// document.getElementsByClassName()
for (i = 0; i < inputlist.length; i++) {
var elem = inputlist[0];
return elem.parentNode.removeChild(elem);
}
 
}
.multivaluebox {
border: 1px solid #ccc;
background-color: white;
padding: 10px;
width: 60%;
}
.form-multivaluebox-textbox {
border: 1px solid #ccc;
border-radius: 0;
width: 100%;
}
.btncontainer {
width: 6%;
padding-left: 1%;
margin: 0;
}
.subbutton {
margin-top: 2px;
width: 34px;
height: 34px;
padding: 1%;
background-color: #0098ff;
color: white;
border: none;
font-weight: bold;
}
.addbutton {
width: 34px;
height: 34px;
padding: 1%;
background-color: #0098ff;
color: white;
border: none;
font-weight: bold;
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper" class="multivaluebox ">
<input asp-for="#Model" class="form-multivaluebox-textbox" value="hello" />
</div>
<div class="btncontainer col-sm-1">
<input type="button" class="addbutton " onclick="addtextbox(); " value="+" />
<br />
<input type="button" class=" subbutton" onclick="deletetextbox();" value="-" />
<div ></div>

Related

Javascript code style property value not updating after Ajax call

I have JS code where I am changing the style of an HTML element based on an AJAX response.
So my code looks like this.
$.ajax(settings).done(function(response) {
const button_submit = document.getElementById("submit")
button_submit.disabled = response[0];
button_submit.style.cursor = '\"' + response[1] + '\"';
button_submit.style.marginTop = '\"' + response[3] + '\"';
document.getElementById("email").style.visibility = '\"' + response[2] + '\"';
})
input[type=text],
select {
width: 100%;
padding: 12px 20px;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
font-size: 20px;
margin-bottom: 1.2 rem;
margin-bottom: -6%;
}
#submit {
width: 100%;
background: #f39d13;
background: linear-gradient(to bottom, #f39d13 0, #c64f01 100%);
color: white;
padding: 14px 20px;
margin-top: 4%;
border: none;
border-radius: 4px;
font-size: 20px;
cursor: pointer;
}
#customForm {
border-radius: 5px;
padding: 20px;
margin: auto;
width: 65%;
}
p {
font-size: 12px;
color: gray;
margin-top: 5%;
text-align: center;
}
#email {
visibility: hidden;
font-size: 16px;
color: red;
line-height: -6px;
line-height: 1.6;
text-align: left;
display: block;
}
</head>
<div id="customForm">
<form accept-charset="UTF-8" id="" action="#action" method="POST">
<input name="inf_form_xid" type="hidden" value="dd500cb6988ssd3e0151492cb3eff8cf594" />
<input name="inf_form_name" type="hidden" value="UYTS" />
<input name="if_version" type="hidden" value="1.70.0.4582435" />
<div class="if-field">
<label for="inf_field_Email"></label>
<input id="inf_field_Email" name="inf_field_Email" placeholder="Enter your email address " type="text" /></div>
<div>
<div> </div>
</div>
<label id="email">Please enter a valid email address.</label>
<div class="ifn-submit">
<button id="submit" type="submit">Send Now</button></div>
</form>
</div>
But the style is not changing even after all of the JS function is finished.
I wonder what is wrong with my code.
The response of the AJAX is an array that I am going to put on style properties using JS.
Sample response:
['false', 'pointer', 'hidden', '-3%']
The string 'false' is not the same as the boolean false. The disabled property should be a boolean.
You shouldn't add quotes around the other properties. Quotes are part of the syntax in textual styles, they're not part of the property value itself.
$.ajax(settings).done(function(response) {
const button_submit = document.getElementById("submit")
button_submit.disabled = response[0] === 'true';
button_submit.style.cursor = response[1]';
button_submit.style.marginTop = response[3];
document.getElementById("email").style.visibility = response[2];
})
input[type=text],
select {
width: 100%;
padding: 12px 20px;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
font-size: 20px;
margin-bottom: 1.2 rem;
margin-bottom: -6%;
}
#submit {
width: 100%;
background: #f39d13;
background: linear-gradient(to bottom, #f39d13 0, #c64f01 100%);
color: white;
padding: 14px 20px;
margin-top: 4%;
border: none;
border-radius: 4px;
font-size: 20px;
cursor: pointer;
}
#customForm {
border-radius: 5px;
padding: 20px;
margin: auto;
width: 65%;
}
p {
font-size: 12px;
color: gray;
margin-top: 5%;
text-align: center;
}
#email {
visibility: hidden;
font-size: 16px;
color: red;
line-height: -6px;
line-height: 1.6;
text-align: left;
display: block;
}
</head>
<div id="customForm">
<form accept-charset="UTF-8" id="" action="#action" method="POST">
<input name="inf_form_xid" type="hidden" value="dd500cb6988ssd3e0151492cb3eff8cf594" />
<input name="inf_form_name" type="hidden" value="UYTS" />
<input name="if_version" type="hidden" value="1.70.0.4582435" />
<div class="if-field">
<label for="inf_field_Email"></label>
<input id="inf_field_Email" name="inf_field_Email" placeholder="Enter your email address " type="text" /></div>
<div>
<div> </div>
</div>
<label id="email">Please enter a valid email address.</label>
<div class="ifn-submit">
<button id="submit" type="submit">Send Now</button></div>
</form>
</div>

Why javascript 'if else' statement seems looping over

I am writing some javascript code called account register. The requirement is showing information inputted on the screen when clicked the register button, and each row can be deleted by clicking the delete button on the left.
My problem is when the first time I click the register button, information not showing up. The second time is fine. From the third time, extra rows start added. For me it seems the 'if else' statement is looping over inside the function.
What is the reason of that?
Execute result
var counterVal = 0;
document.getElementById("tuikaBtn").onclick = function() {
const addButton = document.getElementById('tuikaBtn');
const listContainer = document.getElementById('result');
const name = document.getElementById('namae');
const nick = document.getElementById('nickname');
const rmvButton = document.getElementById('rmv');
console.log('counter = ' + counterVal);
if (name.value == "" | nick.value == "") {
window.alert("Please input both name and nickname.");
} else if (counterVal == 3) {
document.getElementById("tuikaBtn").style.display = 'none';
} else {
//funtion to get parent item
const handleRemove = function(e) {
const item = e.target.closest('.item');
//remove the listener, to avoid memory leaks.
item.querySelector('.remove-btn').removeEventListener('click', handleRemove);
item.parentElement.removeChild(item);
};
//adds text and button to list once clicked the button
addButton.addEventListener('click', e => {
const item = document.createElement('div');
const paragraph = document.createElement('div');
const remove = document.createElement('button');
item.classList.add('item');
paragraph.classList.add('paragraph-style');
remove.classList.add('remove-btn');
paragraph.textContent = name.value + ' ' + nick.value;
remove.textContent = 'Remove';
item.append(paragraph);
item.append(remove);
listContainer.append(item);
name.value = '';
nick.value = '';
remove.addEventListener('click', handleRemove);
})
return counterVal += 1;
}
}
.base {
margin: 2% 7% 0;
height: 500px;
background: blue;
padding: 5% 10%;
box-shadow: 5px 9px 8px 5px rgba(0, 0, 0, 0.5);
}
input {
width: 300px;
height: 40px;
font-size: large;
}
#tuikaBtn {
background: green;
}
h1 {
font-family: serif;
}
.form-control::placeholder {
color: #cacaca;
opacity: 1;
}
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #312929;
padding: 5px 10px;
}
.card {
width: 100%;
height: 350px;
}
.back {
padding: 30px;
position: absolute;
bottom: 0;
right: 0;
}
.form-group {
margin: 10px 0 15px 0px;
}
#result {
font-size: 120%;
margin: 10;
margin: 10px 20px;
padding: 10px 5px 20px;
margin: 10px 5px 10px 5px;
}
.row .card {
color: black;
}
.card {
color: blue;
display: block;
position: relative;
}
#modal {
display: none;
margin: 1.5em auto 0;
background-color: white;
border: 1px solid black;
width: 50%;
padding: 10px 20px;
position: fixed;
border-radius: 5px;
}
#overLay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 120%;
background-color: rgba(0, 0, 0, 0.75);
}
.items {
display: flex;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: 1fr 6em;
grid-column-gap: 1em;
margin-bottom: 0.667em;
align-items: center;
}
.paragraph-style {
font-style: italic;
}
<div class="base container">
<div class="row">
<h1>Account Register</h1>
</div>
<div class="row">
<div class="card" id="card">
<div class="card-block">
<form id="form-area" class="form-inline" method="post">
<div class="form-group">
<div class="input-group">
<input id="namae" name="namae" type="text" class="form-control" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input id="nickname" name="nickname" type="text" class="form-control" placeholder="Nick Name">
</div>
</div>
<div class="form-group">
<input id="tuikaBtn" type="button" name="touroku" value="Add">
</div>
</form>
<div id="tuikaMoto">User Information</div>
<div id="result"></div>
</div>
</div>
</div>
</div>
<div id="overLay"></div>
Only one tuikaBtn.onclick is needed. Also no need of counter
document.getElementById("tuikaBtn").onclick = function() {
const listContainer = document.getElementById('result');
const name = document.getElementById('namae');
const nick = document.getElementById('nickname');
const rmvButton = document.getElementById('rmv');
if (name.value == "" || nick.value == "") {
window.alert("Please input both name and nickname.");
}
else {
//funtion to get parent item
const handleRemove = function(e) {
const item = e.target.closest('.item');
//remove the listener, to avoid memory leaks.
item.querySelector('.remove-btn').removeEventListener('click', handleRemove);
item.parentElement.removeChild(item);
document.getElementById("tuikaBtn").style.display = '';
};
//adds text and button to list once clicked the button
////// addButton.addEventListener('click', e => { /// // /no need of this
const item = document.createElement('div');
const paragraph = document.createElement('div');
const remove = document.createElement('button');
item.classList.add('item');
paragraph.classList.add('paragraph-style');
remove.classList.add('remove-btn');
paragraph.textContent = name.value + ' ' + nick.value;
remove.textContent = 'Remove';
item.append(paragraph);
item.append(remove);
listContainer.append(item);
name.value = '';
nick.value = '';
remove.addEventListener('click', handleRemove);
if(listContainer.querySelectorAll('.item').length>=3)
{
document.getElementById("tuikaBtn").style.display = 'none';
}else{
document.getElementById("tuikaBtn").style.display = '';
}
////// })
}
}
.base {
margin: 2% 7% 0;
height: 500px;
background: blue;
padding: 5% 10%;
box-shadow: 5px 9px 8px 5px rgba(0, 0, 0, 0.5);
}
input {
width: 300px;
height: 40px;
font-size: large;
}
#tuikaBtn {
background: green;
}
h1 {
font-family: serif;
}
.form-control::placeholder {
color: #cacaca;
opacity: 1;
}
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #312929;
padding: 5px 10px;
}
.card {
width: 100%;
height: 350px;
}
.back {
padding: 30px;
position: absolute;
bottom: 0;
right: 0;
}
.form-group {
margin: 10px 0 15px 0px;
}
#result {
font-size: 120%;
margin: 10;
margin: 10px 20px;
padding: 10px 5px 20px;
margin: 10px 5px 10px 5px;
}
.row .card {
color: black;
}
.card {
color: blue;
display: block;
position: relative;
}
#modal {
display: none;
margin: 1.5em auto 0;
background-color: white;
border: 1px solid black;
width: 50%;
padding: 10px 20px;
position: fixed;
border-radius: 5px;
}
#overLay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 120%;
background-color: rgba(0, 0, 0, 0.75);
}
.items {
display: flex;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: 1fr 6em;
grid-column-gap: 1em;
margin-bottom: 0.667em;
align-items: center;
}
.paragraph-style {
font-style: italic;
}
<div class="base container">
<div class="row">
<h1>Account Register</h1>
</div>
<div class="row">
<div class="card" id="card">
<div class="card-block">
<form id="form-area" class="form-inline" method="post">
<div class="form-group">
<div class="input-group">
<input id="namae" name="namae" type="text" class="form-control" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input id="nickname" name="nickname" type="text" class="form-control" placeholder="Nick Name">
</div>
</div>
<div class="form-group">
<input id="tuikaBtn" type="button" name="touroku" value="Add">
</div>
</form>
<div id="tuikaMoto">User Information</div>
<div id="result"></div>
</div>
</div>
</div>
</div>
<div id="overLay"></div>

pass Javascript array to PHP using AJAX

I have to pass Javascript array variable to PHP ,
so here php and javascript code both are in same page .
when i give console inside isset($_POST['kvcArray'])) -- > it is not printing . guess some problem with this . Can anyone help me in this
body {
color: #566787;
background: #f5f5f5;
font-family: 'Varela Round', sans-serif;
font-size: 13px;
}
.table-wrapper {
background: #fff;
padding: 20px 25px;
margin: 30px 0;
border-radius:1px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
}
.table-title {
padding-bottom: 15px;
background: linear-gradient(40deg, #2096ff, #05ffa3) !important;
color: #fff;
padding: 16px 30px;
margin: -20px -25px 10px;
border-radius: 1px 1px 0 0;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
}
.table-title h2 {
margin: 5px 0 0;
font-size: 24px;
}
.table-title .btn-group {
float: right;
}
.table-title .btn {
color: #fff;
float: right;
font-size: 13px;
border: none;
min-width: 50px;
border-radius: 1px;
border: none;
outline: none !important;
margin-left: 10px;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.247);
}
.table-title .btn i {
float: left;
font-size: 21px;
margin-right: 5px;
}
.table-title .btn span {
float: left;
margin-top: 2px;
}
table.table tr th, table.table tr td {
border-color: #e9e9e9;
padding: 12px 15px;
vertical-align: middle;
}
table.table tr th:first-child {
width: 60px;
}
table.table tr th:last-child {
width: 100px;
}
table.table-striped tbody tr:nth-of-type(odd) {
background-color: #fcfcfc;
}
table.table-striped.table-hover tbody tr:hover {
background: #f5f5f5;
}
table.table th i {
font-size: 13px;
margin: 0 5px;
cursor: pointer;
}
table.table td:last-child i {
opacity: 0.9;
font-size: 22px;
margin: 0 5px;
}
table.table td a {
font-weight: bold;
color: #566787;
display: inline-block;
text-decoration: none;
outline: none !important;
}
table.table td a:hover {
color: #2196F3;
}
table.table td a.edit {
color: #FFC107;
}
table.table td a.delete {
color: #F44336;
}
table.table td i {
font-size: 19px;
}
table.table .avatar {
border-radius: 1px;
vertical-align: middle;
margin-right: 10px;
}
.pagination {
float: right;
margin: 0 0 5px;
}
.pagination li a {
border: none;
font-size: 13px;
min-width: 30px;
min-height: 30px;
color: #999;
margin: 0 2px;
line-height: 30px;
border-radius: 1px !important;
text-align: center;
padding: 0 6px;
}
.pagination li a:hover {
color: #666;
}
.pagination li.active a, .pagination li.active a.page-link {
background: #03A9F4;
}
.pagination li.active a:hover {
background: #0397d6;
}
.pagination li.disabled i {
color: #ccc;
}
.pagination li i {
font-size: 16px;
padding-top: 6px
}
.hint-text {
float: left;
margin-top: 10px;
font-size: 13px;
}
/* Custom checkbox */
.custom-checkbox {
position: relative;
}
.custom-checkbox input[type="checkbox"] {
opacity: 0;
position: absolute;
margin: 5px 0 0 3px;
z-index: 9;
}
.custom-checkbox label:before{
width: 18px;
height: 18px;
}
.custom-checkbox label:before {
content: '';
margin-right: 10px;
display: inline-block;
vertical-align: text-top;
background: white;
border: 1px solid #bbb;
border-radius: 1px;
box-sizing: border-box;
z-index: 2;
}
.custom-checkbox input[type="checkbox"]:checked + label:after {
content: '';
position: absolute;
left: 6px;
top: 3px;
width: 6px;
height: 11px;
border: solid #000;
border-width: 0 3px 3px 0;
transform: inherit;
z-index: 3;
transform: rotateZ(45deg);
}
.custom-checkbox input[type="checkbox"]:checked + label:before {
border-color: #03A9F4;
background: #03A9F4;
}
.custom-checkbox input[type="checkbox"]:checked + label:after {
border-color: #fff;
}
.custom-checkbox input[type="checkbox"]:disabled + label:before {
color: #b8b8b8;
cursor: auto;
box-shadow: none;
background: #ddd;
}
/* Modal styles */
.modal .modal-dialog {
max-width: 400px;
}
.modal .modal-header, .modal .modal-body, .modal .modal-footer {
padding: 20px 30px;
}
.modal .modal-content {
border-radius: 1px;
}
.modal .modal-footer {
background: #ecf0f1;
border-radius: 0 0 1px 1px;
}
.modal .modal-title {
display: inline-block;
}
.modal .form-control {
border-radius: 1px;
box-shadow: none;
border-color: #dddddd;
}
.modal textarea.form-control {
resize: vertical;
}
.modal .btn {
border-radius: 1px;
min-width: 100px;
}
.modal form label {
font-weight: normal;
}
<script type="text/javascript">
$(document).ready(function(){
// Activate tooltip
$('[data-toggle="tooltip"]').tooltip();
// Select/Deselect checkboxes
var checkbox = $('table tbody input[type="checkbox"]');
$("#selectAll").click(function(){
if(this.checked){
checkbox.each(function(){
this.checked = true;
});
}else{
checkbox.each(function(){
this.checked = false;
});
}
});
checkbox.click(function(){
if(!this.checked){
$("#selectAll").prop("checked", false);
}
});
});
</script>
</head>
<body>
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2>Manage <b>Instances</b></h2>
</div>
<div class="col-sm-6">
<i class="material-icons"></i> <span>Add New Employee</span>
<!-- <button id="Delete" onclick="Deleteall();" class="btn btn-danger" data-toggle="modal"><i class="material-icons"></i> <span>DELETe Existing User</span></a> -->
<input type="submit" class="button1" name="insert" value="insert" />
</div>
</div>
</div>
<div align="center">
<form method="post" id="theform">
<button type="button" name="load_data" id="load_data" class="btn btn-info">Load Data</button>
</form>
</div>
<br />
<div id="employee_table">
</div>
</div>
</div>
<div id="addEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="Index.php">
<div class="modal-header">
<h4 class="modal-title">Add Employee</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Customer Name</label>
<input type="text" class="form-control" name="CName" required>
</div>
<div class="form-group">
<label>Environment</label>
<input type="text" class="form-control" name="Environment" required>
</div>
<div class="form-group">
<label>URL Value</label>
<textarea class="form-control" name = "URLValue"required></textarea>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<input type="submit" name="submit" class="btn btn-info" value="Insert">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$( document ).ready(function() {
$( ".button1" ).click(function() {
var val = [];
$("input:checked").each(function (index,value) {
val[index] = this.value;
});
var myJSONText = JSON.stringify(val);
$.ajax({
data: {"myJSONText": myJSONText},
type: 'POST',
success: function(response) {
alert(response);
}
});
});
});
</script>
<?php
if (isset($_POST['myJSONText'])) {
echo "<script>console.log('Debug Objects' );</script>";
echo "<pre>";
var_dump(json_decode($_POST['kvcArray'], true));
echo "</pre>";
die();
}
?>
<?php
if(isset($_POST['submit'])){
//index.php
$file_open = fopen("FILES/employee.csv", "a");
$no_rows = count(file("FILES/employee.csv"));
if($no_rows > 1){
$no_rows = ($no_rows - 1) + 1;
}
$form_data = array(
'CustomerName' => $_POST['CName'],
'Environment' => $_POST['Environment'],
'URLValue' => $_POST['URLValue']
);
fputcsv($file_open, $form_data);
}
?>
</html>
<script>
$(document).ready(function(){
$('#load_data').click(function(){
$.ajax({
url:"FILES/employee.csv",
dataType:"text",
success:function(data)
{
var employee_data = data.split(/\r?\n|\r/);
var table_data = ' <table class="table table-striped table-hover"><thead> <tr><th><span class="custom-checkbox"><input type="checkbox" id="selectAll"><label for="selectAll"></label></span></th>';
table_data += '<tr><th></th>';
for(var count = 0; count<employee_data.length; count++)
{
var cell_data = employee_data[count].split(",");
// table_data += '<tr>';
for(var cell_count=0; cell_count<cell_data.length; cell_count++)
{
if(count === 0)
{
table_data += '<th>'+cell_data[cell_count]+'</th>';
if(cell_count == 4){
table_data += '<th></th><th></th>';
}
}
else
{
if(cell_count === 0 ){
table_data +='<tr><td><span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox"'+count+'" name="options[]" value="'+count+'"><label for="checkbox1"></label></span></td>';
table_data += '<td>'+cell_data[cell_count]+'</td>';
}else{
table_data += '<td>'+cell_data[cell_count]+'</td>';
}
}
}
table_data += '</tr>';
}
table_data += '</table>';
$('#employee_table').html(table_data);
}
});
});
});
</script>
So whole code is provided above , here adding instance works fine , but only problem is when i click on delete all the checkbox values selected should be passed to php , so that i can delete that particular row from csv file .
Based on your edit couple of notes about your code:
1st - put all you javascript function in 1 place, lets say just before the closing body tag - like this:
<script>
$(document).ready(function(){
// all your function here ! in 1 place
});
</script>
</body>
</html>
2nd - not so important but still, move all the php code at the top of your file:
<?php
// all the php here
?>
<!DOCTYPE html>
<html>
<head>
...
...
As far as I understand you're making request to the same page where you form with check boxes is. So you can have something like this:
<?php
if (isset($_POST['kvcArray'])) {
echo "<pre>";
echo "<b>".__FILE__."</b><br/>";
var_dump(json_decode($_POST['kvcArray'], true));
echo "</pre>";
die();
}
?>
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox1" name="options[]" value="1"><label for="checkbox1"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox2" name="options[]" value="2"><label for="checkbox2"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox3" name="options[]" value="3"><label for="checkbox3"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox4" name="options[]" value="4"><label for="checkbox4"></label></span><br />
<input type="submit" class="button" name="insert" value="insert" />
Note that I have edited your js code, the way you're constructing your array and also no need to use "url" inside ajax when posting to same page!
<script type="text/javascript">
$( document ).ready(function() {
$( ".button" ).click(function() {
var val = [];
$("input:checked").each(function (index,value) {
val[index] = this.value;
});
var myJSONText = JSON.stringify(val);
$.ajax({
data: {'kvcArray': myJSONText},
url: 'index.php',
type: 'POST',
success: function(result) {
//alert("Success");
}
});
});
});
</script>
This code has been tested and works on 100%

JS - replace quotation with apostrophe

There is a String like (the String represents another html elements):
<div id="myValue">Something</div>
which is a value of another field.
I Would like to add this value as an innerHTML to another div.
I need to replace the quotation " with apostrophe ' from this string and then put it as innerHTML but how to do that?
Use replace with a regex rule:
var content = document.getElementById("myValue")
content.innerHTML = content.innerHTML.replace(/\"/g, "'")
Don't. You would only need such a transformation if you were manually interpolating something in a template. In this case just let the DOM handle it:
document.querySelectorAll('.append').forEach(button => {
button.addEventListener('click', e => {
let rel = e.target.getAttribute('rel'),
htmlContent = document.querySelector(`#${rel}`).value;
console.log(htmlContent, rel);
document.querySelector('#targetDiv').innerHTML += htmlContent;
});
});
.inputcontainer {
float: left;
width: 49%;
margin-bottom: 0.6em;
font-size: 12px;
}
.htmlvalue {
margin: 0.5em 0;
width: 230px;
font-size: 12px;
}
.append {
border-radius: 4px;
}
#targetDiv {
font-size: 12px;
border: 1px solid gray;
margin: 4px;
padding: 4px;
min-height: 1em;
min-width: 200px;
float: left;
display: block;
}
#targetDiv>div {
float: left;
display: inline-block;
font-size: 12px;
margin: 6px 4px;
padding: 4px;
}
#targetDiv .double {
border: 2px dotted blue;
}
#targetDiv .single {
border: 2px dotted green;
}
<div class="inputcontainer">
<input class="htmlvalue " id="input1" value='<div class="double">Double Quoted</div>'>
<button class="append" rel="input1">Append with " "</button>
</div>
<div class="inputcontainer">
<input class="htmlvalue " id="input2" value="<div class='single'>Single Quoted</div>">
<button class="append" rel="input2">Append with ' '</button>
</div>
<div id="targetDiv">
</div>

jQuery append adds more than one item

I'm trying to create a div automatically when clicking on a button, I have an issue here, for each time I click on the button its incremented the display of the div. Could you please help with this
$(document).ready(function() {
$("#btn2").click(function() {
$("div").append("<div>Appended item</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div></div>
<button id="btn2">cliquer</button>
I followed your suggestion and test it in my own code but I still have the same issue
please find below my code
JavaScript
function DisplayOffer(){
$("button").click(function() {
var id_button =this.id;
console.log("id_button:"+ id_button);
var value_button =$('#'+ id_button).text();
console.log("value_button:"+ value_button);
$('#row').append('<p id=aaa>'+ value_button + '</p>');
});
}
In my JS I have 4 buttons, when I click on a button it should create two new div for each one i'll display a name of the button and a description for the first step I just wanted to display the buttons's name but it is displayed wrong ( not one time only like I told you in the beginning of my question )
function bot() {
var input = document.getElementById("input").value;
output.innerHTML = '<div id="a2" class="msj macro"><div class="avatar"><img class="img-circle" style="width:100%;" src="'+ me.avatar +'" /></div></div><div class="title1">Bonjour ' + input + ' ,vous voulez des informations sur quelle offre ? </br> <button type="button" id="h" class="btn btn-danger btn_hdwm bt" onclick=DisplayOffer()>Hourly</button> <button type="button" id="d" class="btn btn-danger btn_hdwm bt " onclick=DisplayOffer()>Daily</button> <button type="button" id="w" class="btn btn-danger btn_hdwm bt" onclick=DisplayOffer()>Weekly</button> <button type="button" id="m" class="btn btn-danger btn_hdwm bt" onclick=DisplayOffer()>Monthly</button></div>';
HTML :
<div class="container" id="id_div_hide">
<div id="row" class="chattt col-sm-3 col-sm-offset-4 frame a">
<div id="test_id"></div>
<div id="output" class="ma"> </div>
<div id="outputh2" class="output2"></div>
<div id="outputh3" class="output3"></div>
</div>
<div id="az1" class="text text-r az1_class" style="background:whitesmoke !important">
<input id="input" class="mytext" placeholder="Type a message" />
</div>
</div>
Full JS :
var me = {};
me.avatar = "https://lh6.googleusercontent.com/-lr2nyjhhjXw/AAAAAAAAAAI/AAAAAAAARmE/MdtfUmC0M4s/photo.jpg?sz=48";
$('#outputh2').hide();
$('#outputh3').hide();
var timedQuestion=0;
var questionNum = 0;
var question = '<div class="text-chat1">Bonjour cher client, moi c est Djezzy bot, tu t appelles comment?</h1></div>';
var output = document.getElementById('output');
output.innerHTML = question;
function bot() {
var input = document.getElementById("input").value;
output.innerHTML = '<div id="a2" class="msj macro"><div class="avatar"><img class="img-circle" style="width:100%;" src="'+ me.avatar +'" /></div></div><div class="title1">Bonjour ' + input + ' ,vous voulez des informations sur quelle offre ? </br> <button type="button" id="h" class="btn btn-danger btn_hdwm bt" onclick=DisplayOffer()>Hourly</button> <button type="button" id="d" class="btn btn-danger btn_hdwm bt " onclick=DisplayOffer()>Daily</button> <button type="button" id="w" class="btn btn-danger btn_hdwm bt" onclick=DisplayOffer()>Weekly</button> <button type="button" id="m" class="btn btn-danger btn_hdwm bt" onclick=DisplayOffer()>Monthly</button><div id="zmar"></div></div>';
setTimeout(timedQuestion, 2000);
console.log("num question est :"+ questionNum);
}
function DisplayOffer(){
var date = formatAMPM(new Date());
$("button").click(function() {
var id_button =this.id;
console.log("id_button:"+ id_button);
var value_button =$('#'+ id_button).text();
console.log("value_button:"+ value_button);
//$('#row').append( value_button);
$('#row').append('<span class=aaa>'+value_button+ '</span>');
});
}
// to get the time
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
// to hide and display the chat
function toggle_div(img, id) {
var div = document.getElementById(id);
if(div.style.display=="none") {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
$(document).keypress(function(e) {
if (e.which == 13) {
bot();
questionNum++;
}
});
CSS :
.chat{
background-color:#fff4f6;
overflow-y:scroll;
width: 280px;
height: 370px;
position: fixed;
//float:right;
bottom: 0px;
right: 0px;
}
.title1{
font-size: 12px;
color: #183f88;
}
.btn_hdwm1{
padding-left: 20px;
padding-right: 15px;
border-radius: 8px;
padding-bottom: 5px;
background: #e11e26;
color: #fff;
}
.btn_hdwm{
padding: 7px 12px
display: inline-block;
margin: 5px;
background: #fff;
//color: #06c5a6;
color:#c52206;
cursor: pointer;
border-radius: 20px;
font-size: 0.9rem;
//border: 1px solid rgba(6,153,184,0.3);
border: 1px solid rgba(184, 6, 6, 0.3);
}
.mytext{
border:0;padding:10px;background:whitesmoke;
position: fixed;
/*margin: 10px;*/
height: 4%;
width: 15%;
/*margin: 67px 0px 0px -57px;*/
margin: 5px 0px 0px -11px;
}
.text{
width:75%;display:flex;flex-direction:column;
}
.text > p:first-of-type{
width:100%;margin-top:0;margin-bottom:auto;line-height: 13px;font-size: 12px;
}
.text > p:last-of-type{
width:100%;text-align:right;color:silver;margin-bottom:-7px;margin-top:auto;
}
.text-l{
float:left;padding-right:10px;
}
.text-r{
float:right;padding-left:10px;
}
.avatar{
display:flex;
justify-content:center;
align-items:center;
width:25%;
float:left;
padding-right:10px;
}
.macro{
margin-top:5px;width:85%;border-radius:5px;padding:5px;display:flex;
}
.msj-rta{
float:right;background:whitesmoke;
}
.msj{
float:left;background:white;
}
.frame{
background:#e0e0de;
height:372px;
overflow:hidden;
padding:0;
}
.frame > div:last-of-type{
position:absolute;bottom:5px;width:100%;display:flex;
}
ul {
width:100%;
list-style-type: none;
padding:18px;
position:absolute;
bottom:32px;
display:flex;
flex-direction: column;
}
.msj:before{
width: 0;
height: 0;
content:"";
top:-5px;
left:-14px;
position:relative;
border-style: solid;
border-width: 0 13px 13px 0;
border-color: transparent #ffffff transparent transparent;
}
.msj-rta:after{
width: 0;
height: 0;
content:"";
top:-5px;
left:14px;
position:relative;
border-style: solid;
border-width: 13px 13px 0 0;
border-color: whitesmoke transparent transparent transparent;
}
input:focus{
outline: none;
}
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: #d4d4d4;
}
::-moz-placeholder { /* Firefox 19+ */
color: #d4d4d4;
}
:-ms-input-placeholder { /* IE 10+ */
color: #d4d4d4;
}
:-moz-placeholder { /* Firefox 18- */
color: #d4d4d4;
}
.a{
/*margin-top: 199px;*/
float: right;
}
.boutonHourely{
padding: 7px 12px
display: inline-block;
margin: 5px;
background: #fff;
color: #06c5a6;
cursor: pointer;
border-radius: 20px;
font-size: 0.9rem;
border: 1px solid rgba(6,153,184,0.3);
}
.text_chat1{
font-family: Roboto,"Helvetiva Neue","Segoe UI",sans-serif;
font-size: 11px;
}
#output{
font-family: Roboto,"Helvetiva Neue","Segoe UI",sans-serif;
font-size: 11px;
width: 65%;
background-color: #fff;
margin-left: 9px;
border-radius: 20px;
font-size: 12px;
padding: 0px -8px 4px 0px;
margin: 12px;
padding-right: 5px;
padding-left: 12px;
padding-top: 5px;
margin-left: auto;
margin-right: auto;
margin-top: 10%;
}
.bt{
width: 30px;
}
.output:before {
width: 0;
height: 0;
content: "";
top: -5px;
left: -14px;
position: relative;
border-style: solid;
border-width: 0 13px 13px 0;
border-color: transparent #ffffff transparent transparent;
}
.logo-bule{
width: 50px;
height:50px;
border-radius: 40px;
/*float: right;*/
position: fixed;
right: 6%;
bottom: 0px;
}
.logo-bule:after{
/* position:relative;
float:right;
bottom:0px;*/
}
.chattt{
margin-top: 6.3%;
overflow-y: scroll;
}
.output2,.output4,.output5, .output7, .output9, .aaa{
font-family: Roboto,"Helvetiva Neue","Segoe UI",sans-serif;
font-size: 11px;
width: 21%;
background-color: #b2d0e5;
margin-left: 9px;
border-radius: 20px;
font-size: 12px;
padding: 0px -8px 4px 0px;
margin: 12px;
padding-right: -3px;
padding-left: 12px;
padding-top: 5px;
/* margin-left: auto; */
/* margin-right: auto; */
margin-top: 2%;
float: right;
padding-bottom: 5px;
}
.output3{
font-family: Roboto,"Helvetiva Neue","Segoe UI",sans-serif;
font-size: 11px;
width: 65%;
background-color: #fff;
margin-left: 9px;
border-radius: 20px;
font-size: 12px;
padding: 0px -8px 4px 0px;
margin: 12px;
padding-right: 5px;
padding-left: 12px;
padding-top: 5px;
margin-left: auto;
margin-right: auto;
margin-top: 20%;
font-size: 12px;
color: #183f88;
}
.output5{
font-family: Roboto,"Helvetiva Neue","Segoe UI",sans-serif;
font-size: 11px;
width: 21%;
background-color: #b2d0e5;
margin-left: 9px;
border-radius: 20px;
font-size: 12px;
padding: 0px -8px 4px 0px;
margin: 12px;
padding-right: -3px;
padding-left: 12px;
padding-top: 5px;
/* margin-left: auto; */
/* margin-right: auto; */
margin-top: 2%;
float: right;
padding-bottom: 5px;
}
.output6, .output8, .output10{
font-family: Roboto,"Helvetiva Neue","Segoe UI",sans-serif;
font-size: 11px;
width: 65%;
background-color: #fff;
margin-left: 9px;
border-radius: 20px;
font-size: 12px;
padding: 0px -8px 4px 0px;
margin: 12px;
padding-right: 5px;
padding-left: 12px;
padding-top: 5px;
margin-left: auto;
margin-right: auto;
margin-top: 20%;
font-size: 12px;
color: #183f88;
}
Thank you
The problem with this approach is, the inserted element is also <div>. Give a unique way of identification for the master <div>.
$("#btn2").click(function(){
$("body > div").append("<div>Appended item</div>");
});
For this current example, I have used body > div selector, as the <div> is directly under <body>. The better way is to use a class for the <div> and use this way:
<div class="master"></div>
$("#btn2").click(function(){
$(".master").append("<div>Appended item</div>");
});
Full Code
$(document).ready(function() {
$("#btn2").click(function() {
$("body > div").append("<div>Appended item</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div></div>
<button id="btn2">cliquer</button>

Categories