javascript disable button conditionally - javascript

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 {}

Related

Stop taking input in text-field (tag input)

I am taking some tags name like "study","reading" something like that in the textfield with the help of Bootstrap 4 Tag Input Plugin With jQuery - Tagsinput.js and I have also some predefine tags name contain by buttons. If I click the button then the count of the tag's will increase (count++) and again click this button count will decrease(count--). Same rules for the text-field tags and the total count of the tags in both fields (text and buttons)<=5.
I can count the total tags of the both field but can't stop taking input in text-field when it is greater than 5.
html
<button class="btnr btnr-tags-optional" id="1" onclick="tagSelect(this.id)" >1</button>
<button class="btnr btnr-tags-optional" id="2" onclick="tagSelect(this.id)" >2</button>
<button class="btnr btnr-tags-optional" id="3" onclick="tagSelect(this.id)" >3</button>
My Js
var tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
if (total_tags < 5) {
var tags = document.getElementById(clicked_id);
if (tags.style.borderColor == "rgb(255, 72, 20)") {
tags.style.borderColor = "";
tagsCount--;
} else if (tags.style.borderColor == "") {
tags.style.borderColor = 'rgb(255, 72, 20)';
tagsCount++;
}
total_tags = store + tagsCount;
}
console.log(total_tags);
}
$('#tags_text').on('change', function() {
if (total_tags >= 5) {
$("#tags_text").attr('readonly');
console.log('condition')
} else {
$("#tags_text").removeAttr('readonly');
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
console.log(total_tags);
}
});
Here is the example in jsfiddle
This problem is solved.
I have changed the maxTags value of the plugin with the change of the tags click.
window.tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
var r = ("#" + clicked_id).toString();
if (total_tags < 5) {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
} else {
$(r).addClass("classActiveIssue");
window.tagsCount++;
}
} else {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
}
}
total_tags = store + tagsCount;
$("#optionsleft").text(total_tags + "/5 selected");
//console.log("total",total_tags);
}
$('#tags_text').on('change', function() {
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
});
and add the line in add:
self.options.maxTags = 5 - window.tagsCount;
Here is the fiddle

how to validate on form repeater jquery

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>

How to disabled buttons using AngularJS?

I have two functions in PROC.CTRL editProcessRating function i am disabling save button until user answer all question , i have view function(viewProcessRating) so on this function i want to disable save as draft and save both buttons permanently.
How i can achieve this task using AngularJS disable functionality ?
Code so far tried below....
HTML
<div class="spaceonBottom text-center">
<button type="submit" class="btn btn-default" ng-click="handleCancel()">Cancel</button>
<button type="submit" class="btn btn-default" ng-disabled="disableDraft" ng-click="savePRTDraft()" ng-show="showSaveDraftBtn">Save
as Draft</button>
<button type="submit" class="btn btn-primary"
ng-disabled="disableSubmitButton" ng-click="submitClicked()">Submit</button>
</div>
KENDOGRID.JS
{
field: '',
title: 'Action',
width: '8em',
template:'</span> <span class="glyphicon glyphicon-pencil"></span> </span>'
},
Proc.Ctrl
$scope.editProcessRating = function(prcsSessionKey) {
var prtUrl = "/getProcessRating/"+prcsSessionKey;
$location.path(prtUrl);
}
$scope.viewProcessRating = function(prcsSessionKey) {
var prtUrl = "/getProcessRating/"+prcsSessionKey;
$scope.disableDraft = true;
$location.path(prtUrl);
}
RAT.CTRL
$scope.disableSubmitButton = true; //the submit button is disabled until user answers all 12 questions
$scope.calculateTotal = function(value){
var total = 0;
var findRatingKey = {};
$scope.questionSelected[value] = true;
for( i=0; i< $scope.questionnaire.length; i++)
{
total = total + $scope.ratingQstnResult.ratingSelect[i+1];
}
$scope.ratingQstnResult.rtgTotalScore = total;
//If the answer to first question is High, system recommendation should be High
if($scope.ratingQstnResult.ratingSelect[1] === 5){
$scope.ratingQstnResult.sysRecomm = 'High';
findRatingKey = $filter('filter')($scope.decisionList, {text:'High'});
}else if(total < 28 ){
$scope.ratingQstnResult.sysRecomm = 'Low';
findRatingKey = $filter('filter')($scope.decisionList, {text:'Low'});
} else if((total >= 28) && (total < 40)){
$scope.ratingQstnResult.sysRecomm = 'Moderate';
findRatingKey = $filter('filter')($scope.decisionList, {text:'Moderate'});
} else{
$scope.ratingQstnResult.sysRecomm = 'High';
findRatingKey = $filter('filter')($scope.decisionList, {text:'High'});
};
if((!processPromiseObj.data.prQuestionnaireDTOList) || (processPromiseObj.data.sessionStatusLookUpCode === 'RA_PRT_IN_PROG')){
$scope.ratingQstnResult.computerGeneRatingKey = findRatingKey[0].id;
$scope.ratingQstnResult.busDecision = findRatingKey[0].id;
for(j=1; j<= $scope.questionnaire.length; j++ ){
if(!$scope.questionSelected[j]){
//console.log('there is one not selected');
break;
}
}
if(j > $scope.questionnaire.length){
$scope.disableSubmitButton = false;
$scope.showBusDecDropDown = true;
}
}
};
I don't think that j will ever be greater than $scope.questionnaire.length. Use j == $scope.questionnaire.length instead:
if (j == $scope.questionnaire.length) {
$scope.disableSubmitButton = false;
$scope.showBusDecDropDown = true;
}

JQuery show / hide button dependents on number of textarea characters

function countChar(val) {
var len = val.value.length;
if (len == 0 || len == null) {
$('#sending').hide();
} else if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#char_no').text(len + " / 500");
}
};
<textarea id="txt" rows="10" cols="40" onkeyup="countChar(this)"></textarea>
<div id="char_no">0 / 500</div>
<input id="sending" type="submit" value="POST">
Above is my JavaScript and html, it can calculate how many characters are contained in textArea, but I want to hide the submit button if user didn't input anything, or user inputed something but erased them all. any ideas?
You can use toggle to show or hide the button. Also it is recommended to add the event in JavaScript, instead of the markup.
function countChar() {
if (this.value.length > 500) {
this.value = this.value.substring(0, 500);
}
var len = this.value.length;
$('#sending').toggle(!!len); // !! casts a boolean
$('#char_no').text(len + " / 500");
};
$('#txt').on('input', countChar);
Note that this inside the function refers to the element.
DEMO: http://jsfiddle.net/19sLaw7w/1/
<!-- HTML -->
<textarea id = "myinput"></textarea>
<button style = "display: none" id = "mybutton">Submit</button>
Events are neat:
// Pure JS
var myinput = document.getElementById('myinput');
var mybutton = document.getElementById('mybutton');
myinput.onchange = function()
{
var charcount = myinput.value.length;
if(charcount == 0)
{
mybutton.style.display = 'none';
}else{
mybutton.style.display = 'inherit';
}
}
// jQuery
$('#myinput').on('change', function(){
var charcount = $(this).val().length;
if(charcount == 0)
{
$('#mybutton').hide();
}else{
$('#mybutton').show();
}
});

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