Buttons under each other next to an input text field - javascript

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>

Related

How do I access only specific elements that have a same class? jquery

I am trying to create a shopping cart-like function that displays products found in a database and the user can select the quantity of each product and then add it to a cart. The problem that I am currently facing is that when the user clicks on a plus button, all the quantities change and they all display the clicked total price.
This is the code I have :
$('.plus').bind('click', function(e) {
$('.minus').prop('disabled', false)
var quantity = parseInt($('.quantity').val());
if (!isNaN(quantity) && quantity < 8) {
$('.quantity').val(quantity + 1);
} else if (quantity == 8) {
$('.quantity').val(9);
$(this).prop('disabled', true)
}
var price = parseFloat($('.price').text()).toFixed(2);
if (quantity != 9) {
if ((price * quantity) % 1 !== 0) {
$(".total_price").val(parseFloat(price * (quantity + 1)) + ".00");
} else {
$(".total_price").val(parseFloat(price * (quantity + 1)) + "0");
}
$(".total_price").css("font-weight", "Bold");
$(".total_price").css("color", "brown");
} else {
if ((price * quantity) % 1 !== 0) {
$(".total_price").val(parseFloat(price * 9) + ".00");
} else {
$(".total_price").val(parseFloat(price * 9) + "0");
}
$(".total_price").css("font-weight", "Bold");
$(".total_price").css("color", "brown");
}
});
$('.minus').bind('click', function(e) {
$('.plus').prop('disabled', false)
var quantity = parseInt($('.quantity').val());
if (!isNaN(quantity) && quantity > 1) {
$('.quantity').val(quantity - 1);
} else {
$(this).prop('disabled', true)
$('.quantity').val(0);
}
var price = parseFloat($('.price').text()).toFixed(2);
if ((price * quantity) % 1 !== 0) {
$(".total_price").val(parseFloat(price * (quantity - 1)) + ".00");
} else {
$(".total_price").val(parseFloat(price * (quantity - 1)) + "0");
}
if (quantity != 1) {
$(".total_price").css("font-weight", "Bold");
$(".total_price").css("color", "brown");
} else {
$(".total_price").css("font-weight", "normal");
$(".total_price").css("color", "black");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='row' id='product_item'>
<div class='col-5' style='margin: auto;'>
<input class='product_name' readonly type='text' name='product_name' style='display: inline; width:100%; border:white;' value='".$row[' productName ']."'>
</div>
<div class='col-1' style='margin: auto;'>
<div class='price' style='display: inline;'>".$row['price']."</div>€</div>
<div class='col-3' style='display:inline; margin: auto;'>
<div class='input_group_button'>
<button class='btn plus' type='button'>
<img src='img/plus.png'>
</button>
</div>
<input class='input_group_field quantity' readonly type='number' name='quantity' value='0' max=9>
<div class='input_group_button'>
<button class='btn minus' type='button'>
<img src='img/minus.png'>
</button>
</div>
</div>
<div class='col-2' style='margin: auto;'><input class='total_price' readonly type='number' name='total_price' style='display: inline; width:65%; border:white;' value='0.00'>€</div>
<div class='col-1'>
<button class='btn' type='button' id='add_cart'>
<img src='img/add-to-cart.png'>
</button>
</div>
</div>
I appreciate any help I can get!
I've taken your example and put together something which might be useful to you, here is the JSFiddle to be able to test it for yourself
https://jsfiddle.net/xsvg7t8L/
Here is the HTML, not how I have added an ID to each of the quantity fields and then an attribute to the plus and minus buttons which is the selector for the field we want to update.
<div class='row' id='product_item'>
<input id="quantity_1" class='input_group_field quantity' readonly type='number' name='quantity_1' value='0' max=9>
<button class='btn plus' type='button' update="#quantity_1">
+
</button>
<button class='btn minus' type='button' update="#quantity_1">
-
</button>
</div>
<div class='row' id='product_item_2'>
<input id="quantity_2" class='input_group_field quantity' readonly type='number' name='quantity' value='0' max=9>
<button class='btn plus' type='button' update="#quantity_2">
+
</button>
<button class='btn minus' type='button' update="#quantity_2">
-
</button>
</div>
Here is the JS, you can see I am getting the attribute using jQuery's attr() function and then using that to get the pointer to the quantity field rather than using the class.
$('.plus').bind('click', function(e) {
$('.minus').prop('disabled', false)
// This attribute will contain the ID of the quantity you want to update
var qtyField = $(this).attr('update');
var quantity = parseInt($(qtyField).val());
if (!isNaN(quantity) && quantity < 8) {
$(qtyField).val(quantity + 1);
} else if (quantity == 8) {
$(qtyField).val(9);
$(this).prop('disabled', true)
}
});
$('.minus').bind('click', function(e) {
$('.plus').prop('disabled', false)
// This attribute will contain the ID of the quantity you want to update
var qtyField = $(this).attr('update');
var quantity = parseInt($(qtyField).val());
if (!isNaN(quantity) && quantity > 1) {
$(qtyField).val(quantity - 1);
} else {
$(this).prop('disabled', true)
$(qtyField).val(0);
}
});
Not exactly what you asked for but hope it helps!
To make this work you can use the reference to the clicked element, using the this keyword in the event handler, to traverse the DOM to find the related elements using jQuery's built in methods such as closest() and find().
In addition there's a couple of other things which can be addressed.
bind() has been deprecated. Use on() instead.
You can combine the .minus and .plus event handlers by using a data attribute on the buttons to determine which value should be added to the quantity. This reduces the amount of repetition in the code.
You can use Math.max() and Math.min() to set the extents of the quantity field. This makes the code more succinct by removing the need for the lengthy if condition.
Do not use id attributes in content which is repeated throughout the page. id have to be unique within the DOM. Use class attributes instead to group elements by behaviour.
It's odd to use a block level div element and force it to be inline. If you want an inline element use on directly, such as a span.
Avoid putting styling rules in your HTML. Put them in an external stylesheet.
With all that said, try this:
$('.btn-inc').on('click', function(e) {
let $el = $(this);
let inc = $el.data('inc');
$el.closest('.col-3').find('.quantity').val((i, v) => Math.min(Math.max(parseInt(v, 10) + inc, 0), 8));
updatePrice();
});
let updatePrice = () => {
$('.row').each((i, row) => {
let $row = $(row);
let $price = $row.find('.price');
let $quantity = $row.find('.quantity');
$row.find('.total_price').val(parseFloat($price.text() * $quantity.val()).toFixed(2));
});
}
.row {
border: 1px solid #CCC;
border-radius: 5px;
margin: 10px;
padding: 10px;
}
.row > div margin: auto;
}
.row > .col-3 {
display: inline;
}
input.product_name {
display: inline;
width: 100%;
border: white;
}
input.total_price {
display: inline;
width: 65%;
border: white;
}
span.price {
display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- item 1 -->
<div class="row">
<div class="col-5">
<input class="product_name" readonly type="text" name="product_name" value="productName">
</div>
<div class="col-1">
<span class="price">1.00</span>€
</div>
<div class="col-3">
<div class="input_group_button">
<button class="btn plus btn-inc" type="button" data-inc="1">+</button>
</div>
<input class="input_group_field quantity" readonly type="number" name="quantity" value="0" max="9">
<div class="input_group_button">
<button class="btn minus btn-inc" type="button" data-inc="-1">-</button>
</div>
</div>
<div class="col-2">
<input class="total_price" readonly type="number" name="total_price" value="0.00"> €
</div>
<div class="col-1">
<button class="btn" type="button" class="add_cart">Add to cart</button>
</div>
</div>
<!-- item 2 -->
<div class="row">
<div class="col-5">
<input class="product_name" readonly type="text" name="product_name" value="productName">
</div>
<div class="col-1">
<span class="price">9.99</span>€
</div>
<div class="col-3">
<div class="input_group_button">
<button class="btn plus btn-inc" type="button" data-inc="1">+</button>
</div>
<input class="input_group_field quantity" readonly type="number" name="quantity" value="0" max="9">
<div class="input_group_button">
<button class="btn minus btn-inc" type="button" data-inc="-1">-</button>
</div>
</div>
<div class="col-2">
<input class="total_price" readonly type="number" name="total_price" value="0.00"> €
</div>
<div class="col-1">
<button class="btn" type="button" class="add_cart">Add to cart</button>
</div>
</div>
What you are doing is wrong.
Think about it, you have a List of product_item then when you click on plus or minus then you need those values that are under this specific product_item right?
Ok lets see what we can do about your code and make a small change that will fix the issue.
$('.plus').bind('click', function(e) {
var productItem = $(this).closest("#product_item")
console.log(productItem.length)
productItem.find('.minus').prop('disabled', false)
var quantity = parseInt(productItem.find('.quantity').val());
if (!isNaN(quantity) && quantity < 8) {
productItem.find('.quantity').val(quantity + 1);
} else if (quantity == 8) {
productItem.find('.quantity').val(9);
$(this).prop('disabled', true)
}
var price = parseFloat(productItem.find('.price').text()).toFixed(2);
if (quantity != 9) {
if ((price * quantity) % 1 !== 0) {
productItem.find(".total_price").val(parseFloat(price * (quantity + 1)) + ".00");
} else {
productItem.find(".total_price").val(parseFloat(price * (quantity + 1)) + "0");
}
productItem.find(".total_price").css("font-weight", "Bold");
productItem.find(".total_price").css("color", "brown");
} else {
if ((price * quantity) % 1 !== 0) {
productItem.find(".total_price").val(parseFloat(price * 9) + ".00");
} else {
productItem.find(".total_price").val(parseFloat(price * 9) + "0");
}
productItem.find(".total_price").css("font-weight", "Bold");
productItem.find(".total_price").css("color", "brown");
}
});
$('.minus').bind('click', function(e) {
var productItem = $(this).closest("#product_item")
productItem.find('.plus').prop('disabled', false)
var quantity = parseInt(productItem.find('.quantity').val());
if (!isNaN(quantity) && quantity > 1) {
productItem.find('.quantity').val(quantity - 1);
} else {
$(this).prop('disabled', true)
productItem.find('.quantity').val(0);
}
var price = parseFloat(productItem.find('.price').text()).toFixed(2);
if ((price * quantity) % 1 !== 0) {
productItem.find(".total_price").val(parseFloat(price * (quantity - 1)) + ".00");
} else {
productItem.find(".total_price").val(parseFloat(price * (quantity - 1)) + "0");
}
if (quantity != 1) {
productItem.find(".total_price").css("font-weight", "Bold");
productItem.find(".total_price").css("color", "brown");
} else {
productItem.find(".total_price").css("font-weight", "normal");
productItem.find(".total_price").css("color", "black");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='row' id='product_item'>
<div class='col-5' style='margin: auto;'>
<input class='product_name' readonly type='text' name='product_name' style='display: inline; width:100%; border:white;' value='".$row[' productName ']."'>
</div>
<div class='col-1' style='margin: auto;'>
<div class='price' style='display: inline;'>".$row['price']."</div>€</div>
<div class='col-3' style='display:inline; margin: auto;'>
<div class='input_group_button'>
<button class='btn plus' type='button'>
<img src='img/plus.png'>
</button>
</div>
<input class='input_group_field quantity' readonly type='number' name='quantity' value='0' max=9>
<div class='input_group_button'>
<button class='btn minus' type='button'>
<img src='img/minus.png'>
</button>
</div>
</div>
<div class='col-2' style='margin: auto;'><input class='total_price' readonly type='number' name='total_price' style='display: inline; width:65%; border:white;' value='0.00'>€</div>
<div class='col-1'>
<button class='btn' type='button' id='add_cart'>
<img src='img/add-to-cart.png'>
</button>
</div>
</div>

Generate Serial Number on adding new line and adjust serial no when any line removed

I am cloning four field (sl no,stationery type ,quantity, Remove ) of a form by using java script.I can very well append or remove these field
I am not able to generate the serial no on the first column and if I delete any row in between this should also adjust the serial no.How can i achieve this My code is below
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
$(document).on('keypress', '.number_only', function(e) {
return isNumbers(e, this);
});
function isNumbers(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<br />
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;>
<div class=" row ">
<div class="col-md-4 ">
</div>
<div class="col-sm-12 ">
<h4 align="center "><b><u>Add Stationery Stock<b></u></h4>
<br />
<form method="post " id="insert_form ">
<div class="col-sm-6 ">
<input type="text " name="Order No. " class="form-control " placeholder="Order NO "/>
</div>
<div class="col-sm-6 ">
<input type="date " name="Date " class="form-control " placeholder="Date " />
</div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center "><b><u>Stationery Details<b></u></h4>
<div> </div>
<div class="table-repsonsive ">
<span id="error "></span>
<table class="table table-bordered " id="item_table ">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button " name="add " class="btn btn-success btn-sm add "><span class="glyphicon glyphicon-plus "></span></button></th>
</tr>
</table>
<div align="center ">
<input type="submit " name="submit " class="btn btn-info "style="margin-bottom:20px " value="Insert " />
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Using
html += '<td><input type="text" name="item_name[]" class="form-control item_name"></td>';
you can do
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
when needed
I fixed your invalid HTML (u and b not correctly closed and a missing quote on the first inline style)
I ALSO remove the name="submit" - you never want to have name="submit" on a form you plan to submit using script
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
$(function() {
$("#item_table").on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
renum()
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
renum()
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;">
<div class="row">
<div class="col-md-4"></div>
<div class="col-sm-12">
<h4 align="center"><b><u>Add Stationery Stock</u></b></h4>
<form method="post" id="insert_form">
<div class="col-sm-6"><input type="text" name="Order No." class="form-control" placeholder="Order NO " /></div>
<div class="col-sm-6"><input type="date" name="Date" class="form-control" placeholder="Date" /></div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center"><b><u>Stationery Details</u></b></h4>
<div> </div>
<div class="table-repsonsive"><span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center"><input type="submit" class="btn btn-info" style="margin-bottom:20px" value="Insert" /></div>
</div>
</form>
</div>
</div>
</div>

JS: Uncaught TypeError: onlcick is not a function

When I put the form tag on the button tag id="paybutton" function, it works well. But when I put the form tag on the div class="form-group, the up and down buttons don't work. i've added type="button" and tried to change input type ="button" but it is still not working.
<script>
var up = function(max) {
document.getElementById("mynumber").value = parseInt(document.getElementById("mynumber").value) + 1;
if (document.getElementById("mynumber").value >= parseInt(max)) {
document.getElementById("mynumber").value = max;
}
document.getElementById("amount").value = parseInt(document.getElementById("mynumber").value) * 5000;
if (document.getElementById("amount").value >= 50000) {
document.getElementById("amount").value = 50000;
}
}
function down(min) {
document.getElementById("mynumber").value = parseInt(document.getElementById("mynumber").value) - 1;
if (document.getElementById("mfFFfFFynumber").value <= parseInt(min)) {
document.getElementById("mynumber").value = min;
}
document.getElementById("amount").value = parseInt(document.getElementById("mynumber").value) * 5000;
if (document.getElementById("amount").value <= 5000) {
document.getElementById("amount").value = 5000;
}
}
</script>
<form method="post" action="/kakaoPay">
<!-- ??? ?? -->
<div class="form-group">
<label>??? ? (1??? : 5??): </label>
<div class="input-group">
<div class="input-group-btn">
<button type="button" id="down" class="btn btn-default" onclick="down('1')">
<span class="glyphicon glyphicon-minus"></span>
</button>
</div>
<input type="text" name="mybumber" id="mynumber" class="form-control input-number" value="1" />
<div class="input-group-btn">
<button type="button" id="up" class="btn btn-default" onclick="up('10')">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
<output type="number" id="amount" name="total" class="form-control input-number"></output>
</div>
-
<h1> ?? </h1>
-
<!-- <form method="post" action="/kakaoPay"> -->
- <button name="paybutton" id="paybutton"> ?? </button> -
</form>
use window.up window.down
because scope is current form not window
like this
You have to rename your functions "up" and "down". Try "up2" and "down2" and it will work. This is because the identifier names conflicts with your function names.
<script>
var up2 = function(max) {
document.getElementById("mynumber").value = parseInt(document.getElementById("mynumber").value) + 1;
if (document.getElementById("mynumber").value >= parseInt(max)) {
document.getElementById("mynumber").value = max;
}
document.getElementById("amount").value = parseInt(document.getElementById("mynumber").value) * 5000;
if (document.getElementById("amount").value >= 50000) {
document.getElementById("amount").value = 50000;
}
}
function down2(min) {
document.getElementById("mynumber").value = parseInt(document.getElementById("mynumber").value) - 1;
if (document.getElementById("mfFFfFFynumber").value <= parseInt(min)) {
document.getElementById("mynumber").value = min;
}
document.getElementById("amount").value = parseInt(document.getElementById("mynumber").value) * 5000;
if (document.getElementById("amount").value <= 5000) {
document.getElementById("amount").value = 5000;
}
}
</script>
<form method="post" action="/kakaoPay">
<!-- ??? ?? -->
<div class="form-group">
<label>LABEL (1? : 5?): </label>
<div class="input-group">
<div class="input-group-btn">
<button type="button" id="down" class="btn btn-default" onclick="down2('1')">
<span class="glyphicon glyphicon-minus">DOWN</span>
</button>
</div>
<input type="text" name="mybumber" id="mynumber" class="form-control input-number" value="1" />
<div class="input-group-btn">
<button type="button" id="up" class="btn btn-default" onclick="up2('10')">
<span class="glyphicon glyphicon-plus">UP</span>
</button>
</div>
</div>
<output type="number" id="amount" name="total" class="form-control input-number"></output>
</div>
-
<h1> HEADER </h1>
-
<!-- <form method="post" action="/kakaoPay"> -->
- <button name="paybutton" id="paybutton"> PAY </button> -
</form>
Refer to this answer for more details: Why JS function name conflicts with element ID?

How do i remove an li my case

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);
}

Change just one input field with javascript

I have code like this:
<script>
(function() {
window.inputNumber = function(el) {
var min = el.attr('min') || false;
var max = el.attr('max') || false;
var els = {};
els.dec = el.prev();
els.inc = el.next();
el.each(function() {
init($(this));
});
function init(el) {
els.dec.on('click', decrement);
els.inc.on('click', increment);
function decrement() {
var value = el[0].value;
value--;
(value<1) ? value=1 : '';
if(!min || value >= min) {
el[0].value = value;
}
}
function increment() {
var value = el[0].value;
value++;
if(!max || value <= max) {
el[0].value = value++;
}
}
}
};
})();
inputNumber($('.input-number'));
</script>
but this will change every input field when I click on one decrement or increment... But I need to be separated and dynamic, here is html:
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left"></i></span><input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right"></i></span>
</div>
I can have more then one input field, and all need to work separately... Any solution?
The problem is here
els.dec = el.prev();
els.inc = el.next();
.prev() and .next() will get all the preceding and following elements of the matched elements in el.
Remove this step completely and use
function init(el) {
el.prev().on('click', decrement);
el.next().on('click', increment);
// ...
instead.
(function() {
window.inputNumber = function(el) {
var min = el.attr('min') || false;
var max = el.attr('max') || false;
el.each(function() {
init($(this));
});
function init(el) {
el.prev().on('click', decrement);
el.next().on('click', increment);
function decrement() {
var value = el[0].value;
value--;
(value < 1) ? value = 1: '';
if (!min || value >= min) {
el[0].value = value;
}
}
function increment() {
var value = el[0].value;
value++;
if (!max || value <= max) {
el[0].value = value++;
}
}
}
};
})();
inputNumber($('.input-number'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left">-</i></span>
<input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right">+</i></span>
</div>
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left">-</i></span>
<input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right">+</i></span>
</div>
<div class="quantity">
<span class="input-number-decrement" style="margin-right: 15px;"><i class="fa fa-angle-left">-</i></span>
<input type="text" step="4" min="" max="" name="" value="0" class="input-number" size="4" />
<span class="input-number-increment" style="margin-left: 10px;"><i class="fa fa-angle-right">+</i></span>
</div>
You should initialize your code like that:
$('.input-number').each(function(){
inputNumber($(this));
})
instead of:
inputNumber($('.input-number'));
See JS fiddle

Categories

Resources