How do i remove an li my case - javascript

how do i remove the text li created in the JavaScript.
the li was created in the javascript and on click on each button in front of them it should only remove that li and not all
function addBook() {
var userInput = document.getElementById('books').value;
if (userInput === "") {
alert("Please Enter A Text");
return false;
}
var book = document.getElementById('addBook');
var list = document.getElementById('addBook').children;
var check = -1;
var btn = document.createElement('button');
btn.innerHTML = 'X';
(list.length === 0) && book.insertAdjacentHTML('beforeend', '<li>' + userInput + '<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a></li>');
for (var k = 0; k < list.length; k++) {
console.log(list[k].innerText);
if (list[k].innerText === userInput + "x") {
check = 1;
break;
}
}
(check === -1) && book.insertAdjacentHTML('beforeend', '<li>' + userInput + '<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a></li>');
}
function removeParent(e) {
var book = document.getElementById('addBook').children;
book.parentNode.parentNode.removeChild(e.parentNode);
}
<div class="col-md-4 form-cont">
<h3>Favourite Books </h3>
<caption>Enter Book's name:</caption> <input type="text" id="books" class="form-control" required="required">
<button onclick="addBook()" class="btn btn-success">Add Book</button>
<ol type="i" id="addBook">
</ol>
<h3 id="h">Hoobies</h3>
</div>

book is not an Element, instead it is a list of Elements
Simple use e instead of book
function removeParent(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
}
Demo
function addBook() {
var userInput = document.getElementById('books').value;
if (userInput === "") {
alert("Please Enter A Text");
return false;
}
var book = document.getElementById('addBook');
var list = document.getElementById('addBook').children;
var check = -1;
var btn = document.createElement('button');
btn.innerHTML = 'X';
(list.length === 0) && book.insertAdjacentHTML('beforeend', '<li>' + userInput + '<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a></li>');
for (var k = 0; k < list.length; k++) {
console.log(list[k].innerText);
if (list[k].innerText === userInput + "x") {
check = 1;
break;
}
}
(check === -1) && book.insertAdjacentHTML('beforeend', '<li>' + userInput + '<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a></li>');
}
function removeParent(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
}
<div class="col-md-4 form-cont">
<h3>Favourite Books </h3>
<caption>Enter Book's name:</caption> <input type="text" id="books" class="form-control" required="required">
<button onclick="addBook()" class="btn btn-success">Add Book</button>
<ol type="i" id="addBook">
</ol>
<h3 id="h">Hoobies</h3>
</div>

Modify the removeParent function like this:
function removeParent(e) {
var book = document.getElementById('addBook');
book.removeChild(e.parentNode);
}
function addBook() {
var userInput = document.getElementById('books').value;
if (userInput === "") {
alert("Please Enter A Text");
return false;
}
var book = document.getElementById('addBook');
var list = document.getElementById('addBook').children;
var check = -1;
var btn = document.createElement('button');
btn.innerHTML = 'X';
(list.length === 0) && book.insertAdjacentHTML('beforeend', '<li>' + userInput + '<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a></li>');
for (var k = 0; k < list.length; k++) {
console.log(list[k].innerText);
if (list[k].innerText === userInput + "x") {
check = 1;
break;
}
}
(check === -1) && book.insertAdjacentHTML('beforeend', '<li>' + userInput + '<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a></li>');
}
function removeParent(e) {
var book = document.getElementById('addBook');
book.removeChild(e.parentNode);
}
<div class="col-md-4 form-cont">
<h3>Favourite Books </h3>
<caption>Enter Book's name:</caption> <input type="text" id="books" class="form-control" required="required">
<button onclick="addBook()" class="btn btn-success">Add Book</button>
<ol type="i" id="addBook">
</ol>
<h3 id="h">Hoobies</h3>
</div>

you simply need to use the "e" parameter it's directly pointing on your element that was clicked :
<a class="btn btn-danger btn-sm remove" style="margin-left:10px;" onclick="removeParent(this)">x</a>
h
function removeParent(e) {
e.parentNode.parentNode.removeChild(e.parentNode);
}

Related

Updated: How do I pass a default value into my modal input element

UPdated: have been stuck on this for 3 day's now and I cannot find an answer anywhere.
I have a model that contains -input type="text" name="mycardname" id="CardName"/-
I want to post the card name into the value of the input box.
I can put it in a label or a span, but cannot find a way or example to add it to the input box.
My code is below.
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '');
$target('#CardName')('value try This');
});
});
$('#settingsModal,#monthModal').on('show.bs.modal', function (event) {
alert("this alert");
var $card = $(event.relatedTarget).closest('.card');
var $modal = $(this);
var data = $card.data();
Document.getElementById('#CardName').val("try This");
for (var item in data) {
$modal.find('[name="' + item + '"]').val(data[item]);
}
});
$('#monthModal .btn-primary').click(function () {
var $modal = $(this).closest('.modal');
var searchType = $modal.find('input[name="SearchTypeRadio"]:checked').val();
var metric = $modal.find('[name="metric"]').val();
var month = $modal.find('[name="month"]').val();
var cdName = $modal.find('[name="mycardname"]').val();
alert("SearchType: " + searchType + " Metric: " + metric + " Month: " + month + " Card Name: " + cdName);
});
$('.btnApplyColors').on('click', function () {
var $modal = $(this).closest('.modal');
var cardName = $modal.find('[name="name"]').val();
var grMin = $modal.find('[name="greenmin"]').val();
var grMax = $modal.find('[name="greenmax"]').val();
var yMin = $modal.find('[name="yellowmin"]').val();
var yMax = $modal.find('[name="yellowmax"]').val();
var rMin = $modal.find('[name="redmin"]').val();
var rMax = $modal.find('[name="redmax"]').val();
var cardTR = cardName + 'TR';
var elements = document.getElementsByClassName(cardTR); // get all elements
for (var i = 0; i < elements.length; i++) {
var tsd1 = cardName + i + 'TD1';
var tsd2 = cardName + i + 'TD2';
var td1 = document.getElementById(tsd1).innerHTML;
var td2 = parseInt(document.getElementById(tsd2).innerHTML);
alert(td1 + " - " + td2);
switch (true) {
case (td2 >= yMin && td2 <= yMax):
alert(td1 + " - " + td2 + " YMin " + yMin + " yMax " + yMax);
elements[i].style.backgroundColor = "lightyellow";
elements[i].style.color = 'brown';
break;
case (td2 >= grMin && td2 <= grMax):
alert(td1 + " - " + td2 + " grMin " + grMin + " grMax " + grMax);
elements[i].style.backgroundColor = "#E7FCE3";
elements[i].style.color = 'darkgreen';
break;
case (td2 >= rMin && td2 <= rMax):
alert(td1 + " - " + td2 + " rMin " + rMin + " rMax " + rMax);
elements[i].style.backgroundColor = "mistyrose";
elements[i].style.color = 'red';
break;
default:
alert("Hit the Default because " + td2 + " not found");
break;
}
}
$('#ScoreCardDefaults').modal('hide');
});
$(document).ready(function () {
$('input[type="radio"]').click(function () {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
// clean this up //
let startYear = 2000;
let endYear = new Date().getFullYear();
for (i = endYear; i > startYear; i--) {
$('#yearpicker').append($('<option />').val(i).html(i));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-4">
<div class="col mb-4" data-mincoolscale="71">
<div class="card text-center" data-metric="14" data-month="2020-10" data-mincoolscale="71" data-maxcoolscale="100" data-minwarmscale="51" data-maxwarmscale="70" data-minhotscale="0" data-maxhotscale="50">
<div class="card-img-top d-flex align-items-center justify-content-center bg-primary text-light metric-header">
<span class="h5 my-1">my card</span>
</div>
<div class="card-body pt-3">
<h6 class="card-title">
my card title
</h6>
<p>
<span class="metric-date">#DateTime.Now.ToString("MMMM yyyy")</span>
<button type="button" class="btn btn-sm btn-link CardModal" data-cardname="The Card Name" data-toggle="modal" data-target="#monthModal" title="Edit" aria-title="Edit">
Ccc
</button>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="monthModal" tabindex="-1" aria-labelledby="monthModalTitle" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="monthModalTitle">Display Statistics For</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span id="modal-cardname"></span>
<input type="text" name="mycardname" id="CardName" />
<div class="myRadios">
<label><input type="radio" name="SearchTypeRadio" value="Monthly"> Monthly</label>
<label><input type="radio" name="SearchTypeRadio" value="Quarterly"> Quarterly</label>
</div>
<div style="display:none" class="Monthly box">You have selected Monthly</div>
<div style="display:none" class="Quarterly box">You have selected quarterly</div>
<div style="display:none" class="Monthly box form-group">
<input type="month" id="month" name="month" class="form-control w-auto" placeholder="mm/yyyy" max="#DateTime.Now.ToString("yyyy-MM")" min="2010-01" />
</div>
<div style="display:none" class="Quarterly box form-group">
#*<label for="month">Yearly Quarter of</label>*#
<select id="QTRS">
<option value="1" selected>1st Quarter</option>
<option value="2">2nd Quarter</option>
<option value="3">3rd Quarter</option>
<option value="4">4th Quarter</option>
</select>
<select name="yearpicker" id="yearpicker"></select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
#*<a class=" btn btn-primary" asp-controller="Home" asp-action="updateSSOA"> Apply</a>*#
<button type="button" class="btn btn-primary" data-dismiss="modal">Apply</button>
</div>
</div>
</div>
</div>
I don’t know if there are multiple text boxes and buttons that are the same on this page. Do you mean to traverse all ATTRIBUTES to the text box corresponding to this button or to pass the ATTRIBUTES corresponding to the modal value into the text box?
If you pass in a corresponding ATTRIBUTES, please refer to the following example:
<input type="text" name="mycardname" id="CardName" />
<button type="button" class="btn btn-sm btn-link CardModal"
data-cardname="kls01" data-toggle="modal" data-target="#monthModal"
title="Edit" aria-title="Edit">
Launch Modal
</button>
#section Scripts{
<script>
$(function () {
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '00');
if ($target.prev().val() == '' || $target.prev().val == null) {
$target.prev().val(attributeName || '')
}
});
});
})
</script>
}
Result:
I finally figured it out:
Change:
$target('#CardName')('value try This');
to:
var myCardName = $(this).data('cardname');
$(".modal-body #mycardname").val(myCardName);

deleting wrong div onclick JS

i am developing a form where you should be able to generate dynamically textfields based on a button and delete if necessary, the wrong thing thing starts when i try to delete the whole DIV element i cloned but instead it only deletes the delete button and the textbox stays there and can't be deleted since the div containing the delete button is the one is deleted, the delete button is in the same div as the textbox, before i forget i am doing all of this using bootstrap 4 so i can't use classes for references as i have seen in some examples, i'll write the codeso you can see what i could be doing wrong
HTML CODE
<div class="form-group" name="CamposTexto" id="CamposTexto"> //whole div i desire to clone
<label class="col-sm-2 control-label" id="label_situacion_actual">Situación Actual:<a id="contador"></a></label>
<div class="col-sm-8">
<textarea id="situacion_permiso_precario" name="situacion_permiso_precario"
class="form-control input-sm" style="resize:none;height:60px;text-transform:uppercase;"
maxlength="500" onKeyPress="return SoloNumeros(event);"></textarea>
</div>
<div id="quitarCampoDeTexto" name="quitarCampoDeTexto"> //this is the div that disappears when i press the X to delete, only happens when i cloned the div
<button type="button" onClick="quitarCampoDeTexto(this);" class="btn btn-danger glyphicon glyphicon-remove"></button>
</div>
</div>
<div id="AgregarCampos" class="form-group" style="margin-bottom:10px;"></div> //reserved space for the cloned div to appear
<div id="Botones" style="margin-bottom:10px;">
<center>
<label>Agregar Más</label> //add more button
<button type="button" class="btn btn-success glyphicon glyphicon-plus"
onClick="agregarCampoDeTexto('CamposTexto', 'AgregarCampos');" id="botonAgregar" name="botonAgregar"></button>
</center>
</div>
JS
var contador = 1;
function agregarCampoDeTexto(divName, CamposTexto) {
if (contador == 25) {
document.getElementById("botonAgregar").remove();
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = document.getElementById(divName).innerHTML;
newdiv.className = 'form-group';
newdiv.id = 'situacion_permiso_precario';
newdiv.name = 'situacion_permiso_precario';
document.getElementById(CamposTexto).appendChild(newdiv);
contador++;
}
var selectElements = document.querySelectorAll('textarea');
for (var i = 1; i < selectElements.length; i++) {
selectElements[i].id = 'situacion_permiso_precario_' + i;
selectElements[i].name = 'situacion_permiso_precario_' + i;
document.getElementById("label_situacion_actual").innerHTML = "Situación Actual:" + i;
}
}
function quitarCampoDeTexto(obj) {
if (contador <= 1) {
return false;
}else{
obj.parentNode.Name == 'form-group'
obj.parentNode.parentNode.removeChild(obj.parentNode);
contador--;
}
}
I have been stuck with this for a couple of days, any kind of help would be great, thanks in advance
EDIT
Labels or div counters are not being displayed properly
Remove the parent of parent using double .parentNode
var contador = 1;
function agregarCampoDeTexto(divName, CamposTexto) {
if (contador == 25) {
document.getElementById("botonAgregar").remove();
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = document.getElementById(divName).innerHTML;
newdiv.className = 'form-group';
newdiv.id = 'situacion_permiso_precario';
newdiv.name = 'situacion_permiso_precario';
document.getElementById(CamposTexto).appendChild(newdiv);
contador++;
}
var selectElements = document.querySelectorAll('textarea');
for (var i = 1; i < selectElements.length; i++) {
selectElements[i].id = 'situacion_permiso_precario_' + i;
selectElements[i].name = 'situacion_permiso_precario_' + i;
document.getElementById("label_situacion_actual").innerHTML = "Situación Actual:" + i;
}
}
function quitarCampoDeTexto(obj) {
if (contador <= 1) {
return false;
}else{
obj.parentNode.Name == 'form-group';
obj.parentNode.parentNode.remove();
contador--;
}
}
<div class="form-group" name="CamposTexto" id="CamposTexto">
<label class="col-sm-2 control-label" id="label_situacion_actual">Situación Actual:<a id="contador"></a></label>
<div class="col-sm-8">
<textarea id="situacion_permiso_precario" name="situacion_permiso_precario"
class="form-control input-sm" style="resize:none;height:60px;text-transform:uppercase;"
maxlength="500" onKeyPress="return SoloNumeros(event);"></textarea>
</div>
<div id="quitarCampoDeTexto" name="quitarCampoDeTexto">
<button type="button" onClick="quitarCampoDeTexto(this);" class="btn btn-danger glyphicon glyphicon-remove"></button>
</div>
</div>
<div id="AgregarCampos" class="form-group" style="margin-bottom:10px;"></div>
<div id="Botones" style="margin-bottom:10px;">
<center>
<label>Agregar Más</label>
<button type="button" class="btn btn-success glyphicon glyphicon-plus"
onClick="agregarCampoDeTexto('CamposTexto', 'AgregarCampos');" id="botonAgregar" name="botonAgregar"></button>
</center>
</div>

PHP - How to Pass Value from Previous Textbox to Newly Created Row on the Same Page?

I'm planning to use a form to register new Teacher (see image bellow). A teacher can assign to different classes to teach different subjects.
Is it possible to pass the value from textbox in Row1_Column1 (AAAA) to textbox in Row2_Column1 when a new row is created by clicking on button (+)?
I don't want the user to take pain in typing the same values in some of the textboxes - the values will be the same. Only [Subject Taught] and [Class Taught] columns might be different, so i want to leave those empty for every new row created.
Sample Form
My code is as follows:
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<div class="row">
<div class="col-xs-12">
<p><button class="btn btn-success" type="button" name="viewStaff">
<i class="ace-icon fa fa-eye bigger-120"></i>
View List</button>
</p>
<form method="post" id="insert_form">
<span id="error"></span>
<table class="table table-bordered" id="staff_table">
<thead>
<tr>
<th>Name (Initials)</th>
<th>Username</th>
<th>Password</th>
<th>Role</th>
<th>Class Assigned</th>
<th>Subject Taught</th>
<th>Class Taught</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</thead>
</table>
<div class="space-24"></div>
<div class="clearfix form-actions">
<div class="center">
<button class="btn btn-info" type="submit" name="submit">
<i class="ace-icon fa fa-check bigger-110"></i>
Submit
</button>
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="initials[]" class="form-control initials" /></td>';
html += '<td><input type="text" name="user_name[]" class="form-control user_name" /></td>';
html += '<td><input type="password" name="password[]" class="form-control password" /></td>';
html += '<td><select name="role[]" class="form-control role"><option value="">Select...</option><option value="admin">Admin</option><option value="form_master">Form Master</option><option value="staff">Staff</option></select></td>';
html += '<td><select name="class_assigned[]" class="form-control class_assigned"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
html += '<td><select name="subject_taught[]" class="form-control subject_taught"><option value="">Select...</option><?php echo fill_subject_box($conn); ?></select></td>';
html += '<td><select name="class_taught[]" class="form-control class_taught"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#staff_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.initials').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.user_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.password').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.role').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_assigned').each(function(){
var count = 1;
if($(this).val() == '')
{
return true;
}
count = count + 1;
});
$('.subject_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"staff_insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#staff_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Staff Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
And staff_insert.php
<?php
//staff_insert.php
$connect = mysqli_connect("localhost", "root", "", "studentsdatabase");
if(isset($_POST["initials"]))
{
$initials = $_POST["initials"];
$user_name = $_POST["user_name"];
$password = $_POST["password"];
$role = $_POST["role"];
$class_assigned = $_POST["class_assigned"];
$subject_taught = $_POST["subject_taught"];
$class_taught = $_POST["class_taught"];
$query = '';
for($count = 0; $count<count($initials); $count++)
{
$initials_clean = mysqli_real_escape_string($connect, $initials[$count]);
$user_name_clean = mysqli_real_escape_string($connect, $user_name[$count]);
$password_clean = mysqli_real_escape_string($connect, $password[$count]);
$role_clean = mysqli_real_escape_string($connect, $role[$count]);
$class_assigned_clean = mysqli_real_escape_string($connect, $class_assigned[$count]);
$subject_taught_clean = mysqli_real_escape_string($connect, $subject_taught[$count]);
$class_taught_clean = mysqli_real_escape_string($connect, $class_taught[$count]);
if($initials_clean != '' && $user_name_clean != '' && $password_clean != '' && $role_clean != '' && $class_assigned_clean != '' && $subject_taught_clean != '' && $class_taught_clean != '')
{
$query .= '
INSERT INTO tbl_users(fullname, username, password, role, class_assigned, subject_taught, class_taught)
VALUES("'.$initials_clean.'", "'.$user_name_clean.'", "'.$password_clean.'", "'.$role_clean.'", "'.$class_assigned_clean.'", "'.$subject_taught_clean.'", "'.$class_taught_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'ok';
}
}
}
?>
Please if you know of a better way, kindly help.
Thanks.
EDIT:
New Image Please check this image
How can I manipulate the above jquery to make the Name, Username, Password, Role and Class Assigned appear for each row the remaining inputs Subject Taught and Class Taught?
Please help.
Some fields are not populated as no server side data can be retrived here. Bu you can see the example for the Role column.
Look for this part in the snippet:
// Here is were you can do the conditional and copying part
var last_row_role_sel_val = $('#staff_table tr:last td:nth-child(4) select option:selected').val();
var last_row_role_sel_html = $('#staff_table tr:last td:nth-child(4) select option:selected').html();
console.log('last_row_role_sel_val',last_row_role_sel_val);
console.log('last_row_role_sel_html',last_row_role_sel_html);
And the replacement part
if (last_row_role_sel_val!=undefined && last_row_role_sel_val!="") {
html += '<td><select name="role[]" class="form-control role"><option value="'+last_row_role_sel_val+'">'+last_row_role_sel_html+'</option></select></td>';
} else {
...
//$( "b" ).clone().prependTo( "p" );
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
// Here is were you can do the conditional and copying part
var last_5_rows_sel_val = [];
var last_5_rows_sel_html = [];
for (var i=1;i<=5;i++) {
if (i>=4) {
last_5_rows_sel_val.push($('#staff_table tr:last td:nth-child('+i+') select option:selected').val());
last_5_rows_sel_html.push($('#staff_table tr:last td:nth-child('+i+') select option:selected').html());
} else {
last_5_rows_sel_val.push($('#staff_table tr:last td:nth-child('+i+') input').val());
last_5_rows_sel_html.push('');
}
}
if (last_5_rows_sel_val[0]!=undefined && last_5_rows_sel_val[0]!="") {
html += '<td><input type="text" name="initials[]" class="form-control initials" value="'+last_5_rows_sel_val[0]+'" /></td>';
html += '<td><input type="text" name="user_name[]" class="form-control user_name" value="'+last_5_rows_sel_val[1]+'" /></td>';
html += '<td><input type="password" name="password[]" class="form-control password" value="'+last_5_rows_sel_val[2]+'" /></td>';
html += '<td><select name="role[]" class="form-control role"><option value="'+last_5_rows_sel_val[3]+'">'+last_5_rows_sel_html[3]+'</option></select></td>';
html += '<td><select name="class_assigned[]" class="form-control class_assigned"><option value="'+last_5_rows_sel_val[4]+'">'+last_5_rows_sel_html[4]+'</option></select></td>';
} else {
html += '<td><input type="text" name="initials[]" class="form-control initials" /></td>';
html += '<td><input type="text" name="user_name[]" class="form-control user_name" /></td>';
html += '<td><input type="password" name="password[]" class="form-control password" /></td>';
html += '<td><select name="role[]" class="form-control role"><option value="">Select...</option><option value="admin">Admin</option><option value="form_master">Form Master</option><option value="staff">Staff</option></select></td>';
html += '<td><select name="class_assigned[]" class="form-control class_assigned"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
}
html += '<td><select name="subject_taught[]" class="form-control subject_taught"><option value="">Select...</option><?php echo fill_subject_box($conn); ?></select></td>';
html += '<td><select name="class_taught[]" class="form-control class_taught"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">-</span></button></td></tr>';
$('#staff_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.initials').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.user_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.password').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.role').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_assigned').each(function(){
var count = 1;
if($(this).val() == '')
{
return true;
}
count = count + 1;
});
$('.subject_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"staff_insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#staff_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Staff Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
table,th,tr,td,div,p {
border: 1px solid #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<div class="row">
<div class="col-xs-12">
<p><button class="btn btn-success" type="button" name="viewStaff">
<i class="ace-icon fa fa-eye bigger-120"></i>
View List</button>
</p>
<form method="post" id="insert_form">
<span id="error"></span>
<table class="table table-bordered" id="staff_table">
<thead>
<tr>
<th>Name (Initials)</th>
<th>Username</th>
<th>Password</th>
<th>Role</th>
<th>Class Assigned</th>
<th>Subject Taught</th>
<th>Class Taught</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">+</span></button></th>
</tr>
</thead>
</table>
<div class="space-24"></div>
<div class="clearfix form-actions">
<div class="center">
<button class="btn btn-info" type="submit" name="submit">
<i class="ace-icon fa fa-check bigger-110"></i>
Submit
</button>
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
UPDATED!!

Buttons under each other next to an input text field

I want to position two buttons under each other next to an input text box with vertical align middle. Here is what I did so far:
jQuery(document).ready(function($) {
//plugin bootstrap minus and plus
//http://jsfiddle.net/laelitenetwork/puJ6G/
$('.btn-number').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('data-field');
type = $(this).attr('data-type');
var input = $("input[name='" + fieldName + "']");
var currentVal = parseFloat(input.val());
if (!isNaN(currentVal)) {
if (type == 'minus') {
if (currentVal > input.attr('min')) {
input.val(currentVal - 0.5).change();
}
if (parseFloat(input.val()) == input.attr('min')) {
$(this).attr('disabled', true);
}
} else if (type == 'plus') {
if (currentVal < input.attr('max')) {
input.val(currentVal + 0.5).change();
}
if (parseFloat(input.val()) == input.attr('max')) {
$(this).attr('disabled', true);
}
}
} else {
input.val(0);
}
});
$('.input-number').focusin(function() {
$(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {
minValue = parseFloat($(this).attr('min'));
maxValue = parseFloat($(this).attr('max'));
valueCurrent = parseFloat($(this).val());
name = $(this).attr('name');
if (valueCurrent >= minValue) {
$(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
} else {
alert('Sorry, the minimum value was reached');
$(this).val($(this).data('oldValue'));
}
if (valueCurrent <= maxValue) {
$(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
} else {
alert('Sorry, the maximum value was reached');
$(this).val($(this).data('oldValue'));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
<div class="input-group">
<input type="text" name="quant[1]" class="form-control input-number" value="1" min="1" max="10">
<ul class="input-group-btn">
<li><button type="button" class="btn btn-default btn-number" disabled="disabled" data-type="minus" data-field="quant[1]">
<span class="glyphicon glyphicon-minus">-</span>
</button></li>
<li><button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant[1]">
<span class="glyphicon glyphicon-plus">+</span>
</button></li>
</ul>
</div>
</div>
The code is working pretty good, but I have no luck with positioning elements.
Something like this
ul.input-group-btn {
display: inline-block;
list-style: none;
padding: 0;
margin: 0;
vertical-align: middle;
}
jQuery(document).ready(function($) {
//plugin bootstrap minus and plus
//http://jsfiddle.net/laelitenetwork/puJ6G/
$('.btn-number').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('data-field');
type = $(this).attr('data-type');
var input = $("input[name='" + fieldName + "']");
var currentVal = parseFloat(input.val());
if (!isNaN(currentVal)) {
if (type == 'minus') {
if (currentVal > input.attr('min')) {
input.val(currentVal - 0.5).change();
}
if (parseFloat(input.val()) == input.attr('min')) {
$(this).attr('disabled', true);
}
} else if (type == 'plus') {
if (currentVal < input.attr('max')) {
input.val(currentVal + 0.5).change();
}
if (parseFloat(input.val()) == input.attr('max')) {
$(this).attr('disabled', true);
}
}
} else {
input.val(0);
}
});
$('.input-number').focusin(function() {
$(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {
minValue = parseFloat($(this).attr('min'));
maxValue = parseFloat($(this).attr('max'));
valueCurrent = parseFloat($(this).val());
name = $(this).attr('name');
if (valueCurrent >= minValue) {
$(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
} else {
alert('Sorry, the minimum value was reached');
$(this).val($(this).data('oldValue'));
}
if (valueCurrent <= maxValue) {
$(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
} else {
alert('Sorry, the maximum value was reached');
$(this).val($(this).data('oldValue'));
}
});
});
ul.input-group-btn {
display: inline-block;
list-style: none;
padding: 0;
margin: 0;
vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="center">
<div class="input-group">
<input type="text" name="quant[1]" class="form-control input-number" value="1" min="1" max="10">
<ul class="input-group-btn">
<li><button type="button" class="btn btn-default btn-number" disabled="disabled" data-type="minus" data-field="quant[1]">
<span class="glyphicon glyphicon-minus">-</span>
</button></li>
<li><button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant[1]">
<span class="glyphicon glyphicon-plus">+</span>
</button></li>
</ul>
</div>
</div>
Create 2 divs and use float property to put them left and right.
<div class="input-group">
<div id="leftdiv" style="float:left">
<input type="text" name="quant[1]" class="form-control input-number" value="1" min="1" max="10">
</div>
<div id="rightdiv" style="float:right;">
<ul class="input-group-btn">
<li>
<button type="button" class="btn btn-default btn-number" disabled="disabled" data-type="minus" data-field="quant[1]">
<span class="glyphicon glyphicon-minus">-</span>
</button>
</li>
<li>
<button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant[1]">
<span class="glyphicon glyphicon-plus">+</span>
</button>
</li>
</ul>
</div>

JavaScript Show Hidden Button

In there I want to make my button is can show and hide when I click button
- Hidden : when I click button minus
- show : when I click button plus
$('.btn-plus').click(function() {
var qty = parseInt($(this).parents('.input-group').find('.input-number').val());
var price = parseInt($(this).parents('.input-group').find('.input-number').attr('data-price'));
var id = parseInt($(this).parents('.input-group').find('.input-number').attr('data-id'));
var new_qty = qty + 1;
var new_price = price * new_qty;
$(this).parents('.input-group').find('.input-number').val(new_qty);
$("#price" + id).text("Rp. " + new_price.number_format(0));
})
$('.btn-minus').click(function() {
var qty = parseInt($(this).parents('.input-group').find('.input-number').val());
var price = parseInt($(this).parents('.input-group').find('.input-number').attr('data-price'));
var id = parseInt($(this).parents('.input-group').find('.input-number').attr('data-id'));
var new_qty = qty - 1;
if (new_qty < 1) {
return
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group" style="width: 150px;">
<span class="input-group-btn">
<button type="button" class="btn btn-danger btn-number btn-minus" data-type="minus">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" name="quantity[]" class="form-control input-number" value="0" data-price="{{$row->price}}" data-id="{{$row->id}}" min="1" max="100" required>
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-number btn-plus" data-type="plus" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
and this what I want to make show hide
<input type='submit' class='btn btn-lg btn-success button-float' value="Book Now">
Add $(":submit").show(); to the function called by the plus button.
Add $(":submit").hide(); to the function called by the minus button.
$(element).hide() sets display to none
$(element).show() sets display to original value
Accordingly, change your code to the following:
var sumbit = $(":submit");
$('.btn-plus').click(function() {
$(submit).show(); //Or wherever else you want it.
var qty = parseInt($(this).parents('.input-group').find('.input-number').val());
var price = parseInt($(this).parents('.input-group').find('.input-number').attr('data-price'));
var id = parseInt($(this).parents('.input-group').find('.input-number').attr('data-id'));
var new_qty = qty + 1;
var new_price = price * new_qty;
$(this).parents('.input-group').find('.input-number').val(new_qty);
$("#price"+id).text("Rp. "+new_price.number_format(0);
});
$('.btn-minus').click(function() {
$(submit).hide(); //Or wherever else you want it.
var qty = parseInt($(this).parents('.input-group').find('.input-number').val());
var price = parseInt($(this).parents('.input-group').find('.input-number').attr('data-price'));
var id = parseInt($(this).parents('.input-group').find('.input-number').attr('data-id'));
var new_qty = qty - 1;
if(new_qty < 1){
return;
});
Here is your full solution:
$('.btn-plus').click(function() {
var qty = parseInt($(this).parents('.input-group').find('.input-number').val());
var price = parseInt($(this).parents('.input-group').find('.input-number').attr('data-price'));
var id = parseInt($(this).parents('.input-group').find('.input-number').attr('data-id'));
var new_qty = qty + 1;
var new_price = price * new_qty;
$(this).parents('.input-group').find('.input-number').val(new_qty);
$("#price" + id).text("Rp. " + new_price);
$(".btn-submit").show();
});
$('.btn-minus').click(function() {
var qty = parseInt($(this).parents('.input-group').find('.input-number').val());
var price = parseInt($(this).parents('.input-group').find('.input-number').attr('data-price'));
var id = parseInt($(this).parents('.input-group').find('.input-number').attr('data-id'));
var new_qty = qty - 1;
var new_price = price * new_qty;
if (new_qty < 1) {
new_qty = 0;
new_price = 0;
$(".btn-submit").hide(); //Or wherever else you want it.
}
$(this).parents('.input-group').find('.input-number').val(new_qty);
$("#price" + id).text("Rp. " + new_price);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" />
<div class="input-group" style="width: 150px;">
<span class="input-group-btn">
<button type="button" class="btn btn-danger btn-number btn-minus" data-type="minus">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" name="quantity[]" class="form-control input-number" value="0" data-price="{{$row->price}}" data-id="{{$row->id}}" min="1" max="100" required>
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-number btn-plus" data-type="plus" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
<input type='submit' class='btn btn-lg btn-success button-float btn-submit' value="Book Now">

Categories

Resources