Troubleshooting jQuery input value - javascript

I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when click changes the amount to $5. I'm trying to get get it so that when the user changes the amount from 5 that it changes the amt = to user input.
The bit of script that changes it
function setDonrAmount(id){
var amt = id.substring(10);
if( amt == 'Other' ){ amt = 5}
var others = id.substring(0,10);
$("button[id*="+others+"]").removeClass('active');
$('button#'+id).addClass('active');
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp

I've made a few updates to setDonrAmount() to handle custom donations.
$("#donrAmountButtons").on("click", function() {
var amt = id.substring(10);
setDonrAmount(amt);
$('#donrAmount' + amt).addClass('active');
});
$("#donrAmountInput").on("focusout", function() {
setDonrAmount($("#donrAmountInput").val());
$('#otherAmount button').addClass('active');
});
function setDonrAmount(val) {
var amt = val || 0;
if (amt.length < 2 && amt < 5)
amt = 5;
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
$('#donrAmountButtons .active').removeClass('active');
}

You'll want to check for a keyup event on the input field, and make the selection when that happens. Something like... (inside document.ready)
$('#donrAmountInput').on('keyup', function() {
// Probably best to strip any non-numeric characters from the field here
amt = $(this).val();
// pseudo-code: $('#donrAmountOther').select(); as I'm not sure about jQuery's handling of input group buttons. There'll be a way to select this one somehow!
});

Related

Javascript - clicking back in the browser and saving previously manipulated html elements

The website is a school, each school day has a set of 4 lessons with each lesson costing £7.50. When the user selects a day they go to a payment page where all 4 lessons are automatically selected as checkboxes, so the total cost is £30. The user can tick or untick each box to add or remove lessons which in turn changes the total amount on screen. The total amount is a html element with an id of #fullamount and a value of £30 :
<h6>Total Cost : <div id="fullamount" name="fullamount">£30</div></h6>
The problem I am having is that if the user proceeds to the external payment page(after selecting all lessons they want) but then decides to click on the back button to return to the original page - the checkboxes remain as they were but the total(#fullamount) returns back to the original state of £30 so if they had only selected 2 checkboxes it should be £15 but it shows up as £30, then if the user checks the other 2 checkboxes the total becomes £45.
Here is the Javascript:
$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#fullamount");
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("£", "") || 0);
var cur_total = +($total.html().replace("£", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("£" + cur_total);
$total.val(cur_total);
});
$('#myform').submit(function(e) {
e.preventDefault();
var $total = $("#fullamount");
var amount = $('#amount');
var thetotal = +($total.html().replace("£", "") || 0);
amount.val(thetotal);
this.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm finding it quite hard to explain but I hope I made some sort of sense. Looking for a solution and struggling with it a bit. Any kind of help or advice would be really appreciated. Thanks.

jQuery traversing and finding textboxes

If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark
Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()
Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});
You could use $(this).closest('input')
Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});

textbox keyup event not working properly

I am using following code to update one textbox value txtUnitPrice based on other textbox txtQuantity ,both can be generated dynamically which is done.
//update unitprice based on quantity of product and tax applied
$('input').live('keyup', function () {
var inputId = $(this).attr('id'); //get textbox txtQuantity id
var rowNum = parseInt(/txtQuantity(\d+)/.exec(inputId)[1], 10); //get row id
var productValue = $("#ddlProduct" + rowNum).val();
var taxValue = $("#ddlTax" + rowNum).val();
var unitPriceValue = $("#txtUnitPrice" + rowNum).val();
var quantityValue = $("#txtQuantity" + rowNum).val();
if ((quantityValue != " ") && (quantityValue > 0)) {
$("#txtUnitPrice" + rowNum).val(unitPriceValue * quantityValue);
}
else {
$("#txtUnitPrice" + rowNum).val(unitPriceValue);
}
});
Now problem arising in the code above is that when I even moving cursor forward or backward in the textbox txtQuantity then the value for txtUnitPrice is changing becuase which this event 'keyup' is firing and hence whole code is executed with the existing txtunitprice value and multiplies this again with the existing txtquantity which I dont' want Please can anyone help me regarding this . Thanks
Just add a check to ignore the cursor movements like shown below
$('input').live('keyup', function (e) {
if([37, 38, 39, 40].indexOf(e.which)){
return false;//do nothing because the cursor keys have been pressed
}
//the rest of your code
});

jQuery validate dynamic percentage field

I'm using the jQuery validate plugin. I'm trying to calculate the sum of all inputs fields using the class .percent. If the sum of the .percent fields isn't equal to 100%, throw validation error.
The percent rows are a part of a dynamic grid and can very in number. You'll see a sample of what I've been working on below. I'm finding the addMethod is called for every input.percent rather than a single time. I'd also like to say it's being called before submit is called.
the code.
html
<div class="row">
<input value="" class="percent"/>
</div>
<div class="row">
<input value="" class="percent"/>
</div>
js
$.validator.addClassRules({
percent: {percent:true}
});
$.validator.addMethod("percent",
function cals(value, element) {
// all the fields that start with 'coeff'
var percent = element;
var total = 0;
for (var i = 0; i < percent.length; i++) {
total += Number(percent[i].value);
}
return total == 100;
}, $.format("Percentage fields most total up to 100%"));
$("form").validate({
});
Updates
I've tried the following code with minor success
$("#modify-funding .percent").rules('add', {sum: 100});
$.validator.addMethod("sum", function (value, element, params) {
var sumOfVals = 0;
$("#modify-funding .percent").each(function () {
sumOfVals = sumOfVals + parseInt($(this).val().length ? $(this).val() : 0);
});
if (sumOfVals == params) return true;
return false;
},
$.format("Percentage fields most total up to 100%")
);
when passing the class into rules it's only passing in a single element which doesn't enable me to query for the additional percent fields. The other issue is it only adds the error class to the first .percent element and the additional elements will not release the error once the 100% criteria has been met.
Update 2
This is the closest I've come to getting percent validation working. It isn't very efficient code since it needs to loop through all the percent fields every time you loop the rules. The code still validates before a submit action has taken place plus does not clear all the percent errors on keyup when the percent has been corrected to equal 100.
$("#modify-funding .percent").each(function() {
$(this).rules('add', {sum: [".percent"]});
})
$.validator.addMethod("sum", function (value, element, params) {
var sumOfVals = 0;
$(params[0]).each(function() {
sumOfVals += parseFloat($(this).val().length ? $(this).val() : 0);
});
if (sumOfVals == 100) return true;
return false;
},
$.format("Percentage fields most total up to 100%")
);
Don't use jquery for such a simple validation. I don't really understand what all the hype is about jquery. It just makes your code look all ugly.
function validate() {
var ret = false;
var total = 0;
var elems = document.getElementsByTagName('*'), i;
for (i in elems)
if (elems[i].className == "percent")
total += parseFloat( elems[i].value);
if (total == 100)
ret = true;
return ret;
}

jQuery submit form IF

Hey guys,
I have this great scripts someone on stack overflow helped me out with, except the one major function I need is missing.
This is a game where the user picks a number (by entering that number in a text field) then hits a play button. After they hit the play button a series of numbers will appear, they then have to click on the number that matches their number.
The query script I'm using counts how many times they hit the number and how many times they missed the number. Take a look at the script in action here. link text
now what I need it to do, is send the score (hits and misses ) to a database after 3 misses, so I can keep high score. Any ideas? Here's the script.
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
if (IsNumeric(n)) {
setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '');
}, <?php echo $time ?>);
}
$('#randomnumber').empty();
for (var i = 0; i < 5; i++) {
li.push($('<li />').click(function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
}
$this.addClass('clicked');
}).appendTo('#randomnumber'));
}
return false;
});
I've updated your problem here.
After updating the status Check for the missCount if it is greater than or equal to 3 then stop the play(clear the interval and unbind the event), then save the value using an ajax request.
I've changed the event handling to use event delegation instead of direct click event on the <li> elements. Event delegation is better in cases where there are lot of elements to which we have to bind a particular event.
I updated your fiddle with the solution. Check http://jsfiddle.net/DHPQT/2/.
I marked all the new stuff with a comment in the form of
//new ....
The main thing to do is checking after
$('#misscount').text(++missCount);
if missCount is 3 and if yes stop the game and send something

Categories

Resources