how to validate on form repeater jquery - javascript

i have form repeater ,and i need to validate specific field before submit.
here's my code
<div class="col-lg-2" style="margin:0px 5%">
<div class="form-group">
<label for="amount_split">Amount</label>
<input tclass="form-control split-amount{{ $index }}"
name="split_amount" type="number" id="amount_split">
</div>
</div>
the form is inside table , so it keep repeated for every row.
i need whenever any field add cannot submit the form before the
addition of all this field is equal some number .
i have tried this
#section('custom_script')
<script>
var iteration = 0;
var amount = 0;
function buttonClicked(ind){
iteration++;
setTimeout(function(){
console.log(ind);
console.log($(".split-amount"+ind));
var arr=[];
for (var index = 0; index <= iteration; index++) {
// console.log(index);
arr.push($("input[name='moves["+index+"][split_amount]']"));
arr.forEach(function(e){
$(e).bind('change',function(){
// ele.value = 23;
// console.log(e[0]);
amount += e[0].value;
if(amount <= 10){
// console.log('yes');
}else{
// console.log('nooo');
}
});
});
}
},100);
}
</script>
#endsection

here's my answer for this problem
function ind(i){
$(document).ready(function(){
var el = $(".splite"+i).change(function(){
var amo = 0;
for(var it = 0;it< el.length;it++){
amo += parseFloat(el[it].value);
}
console.log(amo);
var am = $("#total"+i);
am = parseFloat(am[0].value);
if(amo == am){
$("#sub"+i).removeAttr('disabled');
}else{
$("#sub"+i).attr('disabled',true);
}
$("#split_amount_p"+i).html(amo);
$("#orignal_amount_p"+i).html(am);
if((am - amo) == 0){
$("#difference_amount_p"+i).html(0).css('color','green');
}else{
$("#difference_amount_p"+i).html(am - amo).css('color','red');
}
// console.log(am);
});
});
}
function addButton(index){
ind(index);
}
function removeButton(index)
{
setTimeout(function(){
ind(index);
},500);
}
</script>

Related

Add space after dot

Good day. I've got some problem.
I've got input where I wrote some information.
Example:
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
And I've got my controller.
Example:
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
How I can add space after dot? Who knows?
Here is link to jsfiddle with my example.
We achieve it by adding space to each splitted string other than first one and an empty string
function someCtrl($scope) {
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
var addSpace='';
if(i>0 && strt[i].trim().length>0){
addSpace=' ';
}
strt[i] = addSpace+strt[i].trim().charAt(0).toUpperCase() + strt[i].trim().substr(1);
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div class="wizard wizardstep1" ng-controller='someCtrl'>
<p class="wizardtitle">Put you Theme</p>
<input id="taskTheme" required type="text" placeholder="Put you Theme" ng-model="taskThemeWizardInputValue" ng-change="checkThemeWizardInputValue()">
</div>
</div>
You can do this simply by changing strt.join('.') to strt.join('. ').
$scope.checkThemeWizardInputValue = function () {
if ($scope.taskThemeWizardInputValue === undefined) {
$scope.taskThemeWizardInputValue = "";
console.log($scope.taskThemeWizardInputValue);
console.log($scope.taskThemeWizardInputValue.length);
} else {
var strt = $scope.taskThemeWizardInputValue.split('.');
for (var i = 0 ; i < strt.length; i++) {
strt[i] = strt[i].trim();
if(strt[i].length > 0) {
strt[i] = ' '+strt[i].charAt(0).toUpperCase() + strt[i].substr(1);
}
}
$scope.taskThemeWizardInputValue = strt.join('.');
console.log($scope.taskThemeWizardInputValue);
console.log(strt);
}
}
This is working fiddle
I suggest creating a directive so that you can plugin this behaviour whenever required., rather than writing your ng-change in every controller.
In directive simple line element.val(event.target.value.split(".").join(". ")); will work for you., with help of directive controller parameter.
See example fiddle

How to show nearest div id for a given input number?

Let's say I have the following input field:
<input id="inputField" type="number" value="">
and some divs such as:
<div id="1000"></div>
<div id="1200"></div>
<div id="1500"></div>
<div id="1900"></div>
...
When the user enters a number in the input field, I want my code to go to the nearest div id to that number.
e.g: If user enters 1300 then show div with id = "1200".
What's the most efficient way to implement that in javascript considering there will be a large number of divs?
Right now I'm doing:
<script>
function myFunction()
{
var x = document.getElementById("inputField").value;
if(x >= 1750 && x <= 1900)
{
window.location.hash = '#1800';
}
}
</script>
One way is to wrap all your divs with number ids in another div if you can (and give it some id, say 'numbers'); this allows you to find all the divs in your javascript file.
Javascript:
// Get all the divs with numbers, if they are children of div, id="numbers"
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
// Append the integer of the id of every child to an array
array.push(parseInt(children[i].id));
}
// However you are getting your input number goes here
let number = 1300 // Replace
currentNumber = array[0]
for (const value of array){
if (Math.abs(number - value) < Math.abs(number - currentNumber)){
currentNumber = value;
}
}
// You say you want your code to go to the nearest div,
// I don't know what you mean by go to, but here is the div of the closest number
let target = document.getElementById(currentNumber.toString());
Let me know if there's more I can add to help.
Demo
function closestNum() {
let children = document.getElementById('numbers').children;
let array = [];
for (i = 0; i < children.length; i++) {
array.push(parseInt(children[i].id));
}
let number = document.getElementById('inputnum').value;
currentNumber = array[0]
for (const value of array) {
if (Math.abs(number - value) < Math.abs(number - currentNumber)) {
currentNumber = value;
}
}
let target = document.getElementById(currentNumber.toString());
document.getElementById('target').innerHTML = target.innerHTML;
}
<div id="numbers">
<div id="1000">1000</div>
<div id="2000">2000</div>
<div id="3000">3000</div>
<div id="4000">4000</div>
<div id="5000">5000</div>
</div>
<br />
<input type="text" id="inputnum" placeholder="Input Number" onchange="closestNum()" />
<br />
<br /> Target:
<div id="target"></div>
With some optimization this shall be ok-
var element;
document.addEventListener("change",
function(evt){
if(element && element.classList){
element.classList.remove("selected", false);
element.classList.add("unselected", true);
}
var listOfDivs =
document.querySelectorAll(".unselected");
var val = evt.target.value;
var leastAbs=listOfDivs[0].id;
for(let anIndex=0, len=listOfDivs.length;anIndex<len;anIndex++){
if(Math.abs(listOfDivs[anIndex].id-val)<leastAbs){
leastAbs = Math.abs(listOfDivs[anIndex].id-val);
element = listOfDivs[anIndex];
}
}
element.classList.remove("unselected");
element.classList.add("selected");
});
.selected{
background-color:red;
}
.unselected{
background-color:yellow;
}
.unselected, .selected{
width:100%;
height:50px;
}
<input id="inputField" type="number" value="">
<div id="1000" class='unselected'>1</div>
<div id="1200" class='unselected'>2</div>
<div id="1500" class='unselected'>3</div>
<div id="1900" class='unselected'>4</div>
This may work for you. Loops through each div and compared it to your inputted ID. Tracks closest one, hides all divs, then displays the closest.
document.getElementById("inputField").addEventListener("change", function(){
var divs = document.getElementsByTagName("div");
var closestDiv = -1;
var inputId = document.getElementById("inputField").value;
for(var i=0; i<divs.length; i++)
{
if(Math.abs(inputId - closestDiv) > Math.abs(inputId - divs[i].id) || closestDiv == -1)
{
closestDiv = divs[i].id;
for (var x = 0; x < divs.length; x++) {
divs[x].style.display = 'none';
}
divs[i].style.display = "block";
}
}
});
See it Live: jsfiddle.net

javascript disable button conditionally

How come I get the alert's but the button doesn't enable after a negative is changed to a positive after updating the grand total from a select.
Here is the section that is not working:
if ($('.grand_total').val() < 0) {
$('#submit').prop('disabled', true);
alert('negative number found');
} else if ($('.grand_total').val() > 0) {
$('#submit').prop('disabled', false);
alert('positive number found');
}
and here is the complete code:
<script language="javascript">
$(".add_to_total").on('change', function() {
var total = 0;
var grand_total = 0;
$(".dynamic_row").each(function() {
var row = $(this);
var start_hour_am = parseFloat(row.find(".start_hour_am").val()) || 0;
var start_minute_am = parseFloat(row.find(".start_minute_am").val()) || 0;
var end_hour_am = parseFloat(row.find(".end_hour_am").val()) || 0;
var end_minute_am = parseFloat(row.find(".end_minute_am").val()) || 0;
var start_hour_pm = parseFloat(row.find(".start_hour_pm").val()) || 0;
var start_minute_pm = parseFloat(row.find(".start_minute_pm").val()) || 0;
var end_hour_pm = parseFloat(row.find(".end_hour_pm").val()) || 0;
var end_minute_pm = parseFloat(row.find(".end_minute_pm").val()) || 0;
total = ( (Number(end_hour_am) + (Number(end_minute_am))) - (Number(start_hour_am) + Number(start_minute_am)) + (Number(end_hour_pm) + Number(end_minute_pm)) - (Number(start_hour_pm) + Number(start_minute_pm)));
row.find(".total").val(total);
grand_total = Number(grand_total) + Number(total);
});
$("#grand_total").val(grand_total);
if ($('.grand_total').val() < 0) {
$('#submit').prop('disabled', true);
alert('negative number found');
} else if ($('.grand_total').val() > 0) {
$('#submit').prop('disabled', false);
alert('positive number found');
}
});
</script>
Any ideas would be appreciated.
UPDATE
Here is the html for the Grand total:
<input type="text" class="grand_total" name="grand_total" id="grand_total" data-role="none" value="0" size="3" readonly="true">
and here is the button which i'm trying to disable:
<button type="submit" data-theme="e" data-mini="true" data-inline="true" name="submit" id="submit" class="submit" data-icon="check" value="submit-value">Submit</button>
With Nick N's suggestion, still get the same problem with the button disable/enable.
<script language="javascript">
$(".add_to_total").on('change', function() {
var total = 0;
var grand_total = 0;
$(".dynamic_row").each(function() {
var row = $(this);
var start_hour_am = parseFloat(row.find(".start_hour_am").val()) || 0;
var start_minute_am = parseFloat(row.find(".start_minute_am").val()) || 0;
var end_hour_am = parseFloat(row.find(".end_hour_am").val()) || 0;
var end_minute_am = parseFloat(row.find(".end_minute_am").val()) || 0;
var start_hour_pm = parseFloat(row.find(".start_hour_pm").val()) || 0;
var start_minute_pm = parseFloat(row.find(".start_minute_pm").val()) || 0;
var end_hour_pm = parseFloat(row.find(".end_hour_pm").val()) || 0;
var end_minute_pm = parseFloat(row.find(".end_minute_pm").val()) || 0;
total = ( (Number(end_hour_am) + (Number(end_minute_am))) - (Number(start_hour_am) + Number(start_minute_am)) + (Number(end_hour_pm) + Number(end_minute_pm)) - (Number(start_hour_pm) + Number(start_minute_pm)));
row.find(".total").val(total);
grand_total = Number(grand_total) + Number(total);
});
$("#grand_total").val(grand_total);
//if (parseFloat($('.grand_total').val()) < 0) {
// $('#submit').prop('disabled', true);
// alert('negative number found');
//} else if (parseFloat($('.grand_total').val()) > 0) {
// $('#submit').prop('disabled', false);
// alert('positive number found');
//}
var total = parseFloat($('#grand_total').val());
if(total < 0){
$('#submit').prop('disabled', true);
alert('negative number found...');
}
else {
$('#submit').prop('disabled', false);
alert('positive number found...');
}
});
</script>
UPDATE
Ok looks like the issue is because the button is a jquery mobile generated button its not updating the state of the button when a negative value is found, If i refresh the whole form the button state then chnages. I tested this by setting the data-role to none so the submit button becomes a standard form button and the disable/enable functionality works.
Any ideas how i can get around this?
This should work:
var total = parseFloat($('.grand_total').val());
if(total < 0){
$('#submit').attr("disabled", "disabled");
alert('negative number found');
}
else {
$('#submit').removeAttr("disabled");
alert('positive number found');
}
Jquery Mobile: Don't refresh the whole form, but refresh just the button:
$('#submit').button('refresh');
Please note: that I changed '#' to '.'. Dependent on your HTML you could also change this line:
$(".grand_total").val(grand_total);
to:
$("#grand_total").val(grand_total);
you are passing $('.grand_total').val()
instead of $('#grand_total').val()
try this:
var total = parseInt($('.grand_total').val());
if(total < 0){}
else {}

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources