PHP/Bootstrap - Dynamically Add Fields & Submit Form - javascript

Im a bit lost and figured you guys might be able to help.
What I am trying to do:
I have a form where the user will dynamically add fields and then I would like the user to submit that form and display the values on the next page. But the user has to select a dropdown to show the type of data they are submitting inside the text box. For example
--------------------------
- Drop Down -Text Box -
--------------------------
--------------------------
- INT - 123 -
--------------------------
--------------------------
- TEXT - ABC - +
--------------------------
After Form Submit:
INT - 123
TEXT- ABC
Does anyone know how I could do this?
My Code:
<div class="col-md-4">
<div class="values">
<label>Type:</label>
<form method="post" action="values.php">
<div class="form-group multiple-form-group input-group">
<div class="input-group-btn input-group-select">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="concept">int</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>int</li>
<li>text</li>
</ul>
<input type="hidden" class="input-group-select-val" name="contacts['type'][]" value="int">
</div>
<input type="text" name="contacts['value'][]" class="form-control">
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-add">+</button>
</span>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<script>
(function ($) {
$(function () {
var addFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $formGroupClone = $formGroup.clone();
$(this)
.toggleClass('btn-success btn-add btn-danger btn-remove')
.html('–');
$formGroupClone.find('input').val('');
$formGroupClone.find('.concept').text('int');
$formGroupClone.find('.input-group-select-val').text('int');
$formGroupClone.insertAfter($formGroup);
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', true);
}
};
var removeFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', false);
}
$formGroup.remove();
};
var selectFormGroup = function (event) {
event.preventDefault();
var $selectGroup = $(this).closest('.input-group-select');
var param = $(this).attr("href").replace("#","");
var concept = $(this).text();
$selectGroup.find('.concept').text(concept);
$selectGroup.find('.input-group-select-val').val(param);
}
var countFormGroup = function ($form) {
return $form.find('.form-group').length;
};
$(document).on('click', '.btn-add', addFormGroup);
$(document).on('click', '.btn-remove', removeFormGroup);
$(document).on('click', '.dropdown-menu a', selectFormGroup);
});
})(jQuery);
</script>

Related

Collect list item according to name and store in array or object

I have a dual list in which you get an option to add left list item in right list. And right list is a form. Now i am stuck at a problem where when user click the submit button all the li in right list and there inside values get store in an object with there specific name div id name. I have worked on it for 5 days now but unable to collect data according to div id name. Like
<div id="name1">
<input id="tts" type="text" value="${CTLIST.tts}"> s<br>
<input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
Suppose this is an li of right list.
I want data to get stored like
{
[name : name1,
tts.value : 10,
ifcheckboxcheck : true,
],
[name : name2,
tts.value : 10,
ifcheckboxcheck : true,]
}
HEre is my html
<section class="ctList">
<div class="container">
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"><i class="fa fa-search"
aria-hidden="true" style="padding-right: 20px;"></i></span>
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
</div>
</div>
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
</div>
<ul class="list-group" id="La">
</ul>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"><i class="fa fa-arrow-left"
aria-hidden="true"></i></span>
</button>
<button class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"><i class="fa fa-arrow-right"
aria-hidden="true"></i></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<form id="rightData" method="POST">
<ul class="list-group" id="accordian">
<!-- right list -->
</ul>
<input type="submit" value="submit" name="submit">
</form>
</div>
</div>
</div>
</div>
</section>
This is my js which is obviously not working
$('.content').hide();
$('.listelement').on('click', function () {
if (!($(this).children('.content').is(':visible'))) {
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
$(function () {
$('body').on('click', '.list-group .list-group-item', function () {
$(this).toggleClass('active');
});
$('.list-arrows button').click(function () {
var $button = $(this), actives = '';
if ($button.hasClass('move-left')) {
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
} else if ($button.hasClass('move-right')) {
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
}
});
$('.dual-list .selector').click(function () {
var $checkBox = $(this);
if (!$checkBox.hasClass('selected')) {
$checkBox.addClass('selected').closest('.well').find('ul li:not(.active)').addClass('active right');
$checkBox.children('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');
} else {
$checkBox.removeClass('selected').closest('.well').find('ul li.active').removeClass('active');
$checkBox.children('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
}
});
$('[name="SearchDualList"]').keyup(function (e) {
var code = e.keyCode || e.which;
if (code == '9') return;
if (code == '27') $(this).val(null);
var $rows = $(this).closest('.dual-list').find('.list-group li');
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
////printing properties
$(function () {
var ctList = [];
var ctRight = [];
var $tBody = $("#La");
var $rbody = $("#accordian");
$.getJSON('https://api.myjson.com/bins/d6n2a', function (data) {
data.topic_info.qt_ct_connection.map(value => {
value.ct_list.forEach((CTLIST) => {
$tBody.append(`<li class="list-group-item" id="rl">
<span id="nameOfCt">${CTLIST.ct}</span>
View More
<div id="${CTLIST.ct}" class="collapse valueDiv">
<label>${Object.keys(CTLIST)[2]}</label> <input id="tts" type="text" value="${CTLIST.tts}"><br>
<label>${Object.keys(CTLIST)[1]}</label> <input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
</li>`);
});
})
})
})
</script>
<script>
var SendDataObject = {};
$("#rightData").on("submit", function (event) {
event.preventDefault();
var IDs = [];
var list = {};
var data = {} ;
var tts = {};
let rightListLength;
rightListLength = $('#rightData li').length;
var tts = [];
$("#rightData li").each(function (){
$("#rightdata").find("div").each(function(){ IDs.push(this.id);
$('#rightData').find("#tts").each(function () { IDs.push(this.value)})
})
});
// $('#rightData li').each(function () {
// var a = $(this).html();
// console.log("i am writin second", list[$(this).attr('value')] = $(this).html());
// console.log(list[$(this).attr('id')] = $(this).html())
// });
console.log(IDs)
console.log(tts)
CSS
<style>
.ctList {
padding-top: 20px;
}
.ctList .dual-list .list-group {
margin-top: 8px;
}
.ctList .list-left li,
.list-right li {
cursor: pointer;
}
.ctList .list-arrows {
padding-top: 100px;
}
.ctList .list-arrows button {
margin-bottom: 20px;
}
.dual-list.list-left .well li.list-group-item .show {
display: none;
}
</style>
This is rendered HTML in browser if ony one li in right list . ANd if two li then another HTML will be rendered by diffrent i name coming from json and value .
point_in_first_quad
View More
<div id="point_in_first_quad" class="collapse valueDiv">
<label>tts</label> <input id="tts" type="text" value="10"><br>
<label>topic_level</label> <input id="topic_level" type="text" value="capable"><br>
<label>to_be_shown_individually</label> <input id="to_be_shown_individually" type="checkbox" checked=""> <br>
<label>check_for_geometry</label><input id="check_for_geometry" type="checkbox" checked=""><br>
</div>
Adjust your html to include classes or some other identifier, since you cannot have two elements with same ids, things like #topic_level, Probably add a class to help with selection, something like below should help
<div id="point_in_first_quad" class="collapse valueDiv">
<label class="tts-label">tts</label> <input id="tts" class="tts-value" type="text" value="10"><br>...
You added classes to element you want to use in your result.
Adjust the following to make your result object
var finalResult = [];
$('#accordion div').each(function(index, item) {
var $it = $(item);
var ob = {};
ob['name'] = $it.find('.tts-label').text();
ob['tts.value'] = $it.find('.tts-value').val();
ob['ifcheckboxcheck'] = $it.find('[type="checkbox"]').is(":checked");
finalResult.push(ob);
});
Since you have two checkbox field, add a class selector to the one you want to use in result.

Insert Multi Inputs to DB

How To Get Multi Inputs Value And Save To Db?
this is my Input Generator:
<div class="form-group input-group">
<input type="text" class="form-control">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-add">
+
</button>
</span>
</div>
and Jquery Codes:
<script>
(function ($) {
$(function () {
var addFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $formGroupClone = $formGroup.clone();
$(this)
.toggleClass('btn-default btn-add btn-danger btn-remove')
.html('–');
$formGroupClone.find('input').val('');
$formGroupClone.insertAfter($formGroup);
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', true);
}
};
var removeFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', false);
}
$formGroup.remove();
};
var countFormGroup = function ($form) {
return $form.find('.form-group').length;
};
$(document).on('click', '.btn-add', addFormGroup);
$(document).on('click', '.btn-remove', removeFormGroup);
});
})(jQuery);
</script>
the code generate Several Input text By push on the + Button.
Question:
how to get values all inputs?
in razor page and input model class?
if this is only One Input i can do it.but several input that genereted by javascript i tired to this action!
Question: how to get values all inputs? in razor page and input model class?
Since you use $formGroup.clone(), you could simply apply same name attribute on all inputs and save it as List<string> in PageModel. For example:
1.page.cshtml
#model TestInputModel
<form method="post">
<div class="form-group input-group">
<input type="text" class="form-control" name="MyAllInputs">
<span class="input-group-btn">
<button type="button" class="btn btn-default btn-add">
+
</button>
</span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
#section Scripts{
<script>...</script>
}
2.PageModel
public class TestInputModel : PageModel
{
//using your db context by DI
private readonly MyApplicationDbContext _context;
public TestInputModel(MyApplicationDbContext context)
{
_context = context;
}
//bind your all inputs' values
[BindProperty]
public List<string> MyAllInputs{ get; set; }
public void OnGet()
{
}
public void OnPost()
{
//logic to save you input values to dbcontext
var data = MyAllInputs;
//...
}
}

Force user to select text from Autocomplete options in Dynamic Add / Remove Fields

I have created an add/remove dynamic fields with Autocomplete option. I am using jquery UI autocomplete for text field. The code works perfect. But I want to force user only to select text that are coming in autocomplete options. Following is the code...
jQuery(document).ready(function($) {
var wrapper = $("#username-fields");
var add_button = $("#add-username-fields");
var x = 1;
var availableAttributes = [
"John",
"Pamela",
"Rogers",
"Peter"
];
add_button.click(function(e) {
e.preventDefault();
x++;
var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_login[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>');
element.fadeIn("slow").find("input[name^='user_login']").autocomplete({
source: availableAttributes,
});
wrapper.append(element);
});
wrapper.on("click", "#remove_field", function(e) {
e.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).closest('#user-fields').remove();
x--;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<button type="button" class="btn btn-success" id="add-username-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>
<div id="username-fields">
</div>
I searched and got the following JSFiddle - http://jsfiddle.net/pxfunc/j3AN7/, I want to incorporate the JSFiddle code in my code but some how I am not able to merge both.
Try this Code
jQuery(document).ready(function($) {
var wrapper = $("#username-fields");
var add_button = $("#add-username-fields");
var x = 1;
var availableAttributes = [
"John",
"Pamela",
"Rogers",
"Peter"
];
var previosValue='';
add_button.click(function(e) {
e.preventDefault();
x++;
var element = $('<div id="user-fields"><div class="row"><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" id="user_login" name="user_login[]" placeholder=""></div></div><div class="col-md-5"><div class="form-group"><input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="status[]" value="Unverified" placeholder=""></div></div><div class="col-md-2"><button type="button" class="btn btn-danger" id="remove_field"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</button></div></div><div class="clear"></div></div>');
element.fadeIn("slow").find("input[name^='user_login']").autocomplete({
autoFocus: true,
source: availableAttributes,
});
wrapper.append(element);
})
wrapper.on("keyup","#user_login",function() {
var isValid = false;
for (i in availableAttributes) {
if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
wrapper.on("click", "#remove_field", function(e) {
e.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).closest('#user-fields').remove();
x--;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<button type="button" class="btn btn-success" id="add-username-fields"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</button>
<div id="username-fields">
</div>

jQuery - moved item from one listbox to another cannot be accessed

I am using jQuery to move items from one listbox to another using "Add" / "Remove" buttons' click events. On the screen I can see items move but when I put a breakpoint in the code and examine the content after move is complete, I don't see moved item(s). This affecting server side processing since I cannot get correct data.
<div class="row" id="zip">
<div class="col-sm-10 col-sm-offset-2" style="padding-left: 0px;">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="lbxUnassignedZips">All ZIPs</label>
<asp:ListBox runat="server" ID="lbxUnassignedZips" ClientIDMode="Static"></asp:ListBox>
</div>
</div>
<div class="col-sm-2">
<div class="form-group center-block text-center" style="margin: 0 -20px;">
<div class="form-group center-block" style="padding-top: 70px">
<button id="btnAddZip" type="submit" class="btn btn-default btn-block">Add <i class="fa fa-angle-double-right"></i></button>
<button id="btnRemoveZip" type="submit" class="btn btn-default btn-block"><i class="fa fa-angle-double-left"></i> Remove</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="lbxAssignedZips">Assigned ZIPs</label>
<asp:ListBox runat="server" ID="lbxAssignedZips" ClientIDMode="Static"></asp:ListBox>
</div>
</div>
</div>
<!--/.row -->
</div>
</div>
<button id="btnSubmit" class="btn btn-primary" aria-hidden="true" aria-label="Submit">Submit</button>
Javascrip/jQuery
$(document).ready(function () {
....
$('#btnAddZip').click(function () {
var selectedOptions = $('#lbxUnassignedZips option:selected');
if (selectedOptions.length == 0) {
alert("Please select option to move");
return false;
}
$('#lbxAssignedZips').append($(selectedOptions).clone());
$(selectedOptions).remove();
return false;
});
// When I examine lbxUnassignedZips content after I moved one item to it using
// this function, it still lists old items only!
$('#btnRemoveZip').click(function () {
var selectedOptions = $('#lbxAssignedZips option:selected');
if (selectedOptions.length == 0) {
alert("Please select option to move");
return false;
}
$('#lbxUnassignedZips').append($(selectedOptions).clone());
$(selectedOptions).remove();
return false;
});
});
$(document).on("click", "#btnSubmit", function (event) {debugger
var isValid = validateUpdateSubmit();
if (isValid) {
var assignedZips = $('#lbxAssignedZips option').not('option:eq(-1)').map(function () {
return this.innerHTML;
}).get().join(',');
// does not show newly added item
var unassignedZips = $('#lbxUnassignedZips option').not('option:eq(-1)').map(function () {debugger
return this.innerHTML;
}).get().join(',');
__doPostBack('btnubmit', "SaveUpdate");
$('#editModal').modal('hide');
}
else
return false;
});
Please look on below code. I have changed some jQuery code now you will have all items of listboxs
$(document).on("click", "#btnSubmit", function (event) {
var isValid = validateUpdateSubmit();
if (isValid) {
var assignedZips = [];
$('#lbxUnassignedZips').children("option").each(function () {
var $this = $(this);
assignedZips.push($this.text() + "," + $this.val());
});
alert("AssignedZips => " + lbxUnassignedZips.join());
var lbxUnassignedZips = [];
$('#lbxUnassignedZips').children("option").each(function () {
var $this = $(this);
lbxUnassignedZips.push($this.text() + "," + $this.val());
});
alert("AssignedZips => " + lbxUnassignedZips.join());
__doPostBack('btnubmit', "SaveUpdate");
$('#editModal').modal('hide');
}
else
return false;
});

on keyup validation is working but on keypress its not working

Input box requires following validations:
1) Length input box should take upto 3 integer length values (decimals not allowed)
2) Height input box should take 3 integer number and decimals upto 2 places Its working fine for the first time, but after clicking + button(near of Open New Row 1) same input fields are opening but now: In the new boxes validations are not working even if I use the same classes for input boxes, i.e, newly added input boxes are taking any number of digits and characters.
In keyup function it is working,but if user presses any key it doesn't work for newly opened row, so how to make its working on keypress also in both the cases; on keyup validation is working but on keypress its not working
var app = angular.module('Calc', []);
var inputQuantity = [];
$(function() {
$(".form-control").each(function(i) {
inputQuantity[i]=this.defaultValue;
$(this).data("idx",i); // save this field's index to access later
});
$(".form-control").on("keyup", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10); // retrieve the index
// window.console && console.log($field.is(":invalid"));
// $field.is(":invalid") is for Safari, it must be the last to not error in IE8
if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
app.controller('Calc_Ctrl', function ($scope, $http) {
$scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
$scope.areas = [{id : 'choice2', total : 0}];
$scope.addNewChoice = function () {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if (lastItem !== 0) {
$scope.choices.splice(lastItem);
}
};
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>
<body>
<div ng-app="Calc" ng-controller="Calc_Ctrl">
<div data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
<h6>Open New Row {{$index + 1}}
<button type="button" class="btn btn-default pull-right btn-right-gap btn-red" aria-label="Left Align" ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</h6>
<div class="row walls top-gap">
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="length">Length :</label>
<input type="number" class="form-control text-red bold" id="length" ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
</div>
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="height">Height :</label>
<input type="number" class="form-control text-red bold" id="height" ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
</div>
<button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
</button>
</div>
</div>
</div>
</body>
</html>
To fire keyup event for all fields we need to change the listener's definition slightly,the selector .form-control should be defined inside the on() as a child selector & document as main selector:
$(document).on("keyup",".form-control", function (e) {
// listener code
});
keypress event behaves differently than keyup event. keypress is fired for each key pressed & just before the value is set in the field.Whereas keyup event is fired for each key released & just after the value is set in the field.So the same approach will not work for keypress.
var app = angular.module('Calc', []);
var inputQuantity = [];
$(function() {
$(".form-control").each(function (i) {
inputQuantity[i] = this.defaultValue;
$(this).data("idx", i); // save this field's index to access later
});
$(document).on("keypress", ".form-control", function (e) {
if (e.charCode!=0){
var $field = $(this),
val = this.value + '' + String.fromCharCode(e.charCode), pattern;
if (this.step == 0.00)
pattern = /[^0-9]/
else
pattern = /[^0-9.]/
if (val > parseInt(this.max, 10) || pattern.test(val) || (val.match(/\./) && (val.match(/\./g).length > 1 || val.replace(/\d+\./, '').length > 2))) {
e.preventDefault();
}
}
});
$(document).on("keyup",".form-control", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10);
if (parseInt(val,10) > parseInt(this.max, 10) ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
app.controller('Calc_Ctrl', function ($scope, $http) {
$scope.choices = [{id : 'choice1', l2 : 0, b2 : 0}];
$scope.areas = [{id : 'choice2', total : 0}];
$scope.addNewChoice = function () {
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({
'id' : 'choice' + newItemNo, l2 : 0, b2 : 0
});
};
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if (lastItem !== 0) {
$scope.choices.splice(lastItem);
}
};
});
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="newscript.js"></script>
<body>
<div ng-app="Calc" ng-controller="Calc_Ctrl">
<div data-ng-repeat="choice in choices" class="col-md-12 col-sm-12 col-xs-12 bottom-line no-gap">
<h6>Open New Row {{$index + 1}}
<button type="button" class="btn btn-default pull-right btn-right-gap btn-red" aria-label="Left Align" ng-click="addNewChoice()" style="margin-top: -5px;" id="plus_icon">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</button>
</h6>
<div class="row walls top-gap">
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="length">Length :</label>
<input type="text" class="form-control text-red bold" id="length" ng-model="choice.l2" min="0" max="999" maxlength="6" step="0.00">
</div>
<div class="form-group col-md-3 col-sm-3 col-xs-12">
<label for="height">Height :</label>
<input type="text" class="form-control text-red bold" id="height" ng-model="choice.b2" min="0" max="999" maxlength="6" step="0.01">
</div>
<button type="button" class="btn btn-default pull-right btn-red" aria-label="Left Align" ng-click="removeChoice()" id="minus_icon">
</button>
</div>
</div>
</div>
</body>
</html>

Categories

Resources