I am using this JavaScript code:
<script>
function add(total, this_chk_bx)
{
var thetotal = form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//add if its checked
form2.thetotal.value = Number(thetotal)+Number(total);
}
else
{
//subtract if its unchecked
form2.thetotal.value = thetotal-total;
}
}
</script>
And then I have PHP/HTML code that selects from a table in a database and adds checkboxes with the values as a float field in the database.
What I'm trying to do is to make it so that when the checkboxes are ticked, it adds the values up and displays them in a text field, and then when they are unchecked, it removes that value from the field.
For some reason, when subtracting, it's displaying odd numbers and incorrectly.
I have created a fiddle here so you can also see the HMTL: http://jsfiddle.net/j08691/kHxmG/4/
Any ideas on what I can do to get it working properly?
***jsFiddle Demo***
I suggest you read this posts:
Elegant workaround for JavaScript floating point number problem
Is JavaScript's Floating-Point Math Broken?
Write a function to correct the number for you:
function correctNumber(number) {
return (parseFloat(number.toPrecision(12)));
}
And pass your final number to this function:
function add(total, this_chk_bx) {
var thetotal = (form2.thetotal.value * 1);
var total = total * 1;
if (this_chk_bx.checked == true) {
//add if its checked
form2.thetotal.value = correctNumber(thetotal + total);
} else {
//subtract if its unchecked
form2.thetotal.value = correctNumber(thetotal - total);
}
}
Don't forget to check the jsFiddle Demo.
function add(total, this_chk_bx)
{
var thetotal = form2.thetotal.value;
if(this_chk_bx.checked==true)
{
//add if its checked
form2.thetotal.value = ((thetotal*100)+(total*100))/100;
}
else
{
//subtract if its unchecked
form2.thetotal.value = ((thetotal*100)-(total*100))/100;
}
}
Related
I have an order form I'm working on, where I'm using jQuery to update the price in real time when the user selects different options. So, right now, the final project cost, package type, etc are set in jQuery variables, which I need to convert to PHP to insert into the database.
You can easily see the code: http://jsfiddle.net/cadengrant/uddPA/2/
And live preview of working code: http://www.htmlified.com/order-now/
function update_price() {
var base_cost = base_price;
var basic_price = base_price;
var pro_price = base_price;
jQuery('.packages .selected').each(function(index) {
base_cost += jQuery(this).data("price");
basic_price += base_cost;
pro_price += base_cost + 70;
});
jQuery('#markup-pages').each(function(index) {
var price = Number(jQuery(this).val());
var packages = jQuery('.packages .selected').data("price");
var pages = 0;
jQuery('#packages .selected').each(function(index) {
if(jQuery(this).hasClass('basic')) {
if(packages == 199) {
pages = price * 99 - 99;
} else if (packages == 189) {
pages = price * 94 - 94;
} else if (packages == 399) {
pages = price * 199 - 199;
}
} else if (jQuery(this).hasClass('pro')) {
if(pro_price == 269) {
pages = price * 134 - 134;
} else if (pro_price == 259) {
pages = price * 129 - 129;
} else if (pro_price == 469) {
pages = price * 234 - 234;
}
}
});
base_cost += pages;
/* Single or plural page text */
if(price == 1) {
var markup_pages = "markup page";
} else {
var markup_pages = "markup pages";
}
jQuery('.markup-pages').text(markup_pages);
});
jQuery('#packages .selected').each(function(index) {
if(jQuery(this).hasClass('pro')) {
base_cost += 70;
}
});
/* Update Doctype */
jQuery('input[name=page_doctype]:checked', '#order-form').each(function(index) {
var basic_doctype_text = "";
var pro_doctype_text = "";
if(jQuery(this).hasClass('doctypehtml')) {
var doctype_text = "W3C Valid HTML5 & CSS3";
} else if (jQuery(this).hasClass('doctypexhtml')) {
var doctype_text = "W3C Valid XHTML1 & CSS2";
basic_doctype_text += " Transitional";
pro_doctype_text += " Strict";
}
jQuery('.doctype-text').html(doctype_text);
jQuery('.basic-doctype').html(doctype_text + basic_doctype_text);
jQuery('.pro-doctype').html(doctype_text + pro_doctype_text);
});
jQuery('.price').html(base_cost);
jQuery('.basic-price').html(basic_price);
jQuery('.pro-price').html(pro_price);
}
I just need to figure out how to pass those variables (doctype text, basic doctype, pro doctype, base_cost, etc etc) in the JS section to my order.php form, so I can update amount paid, the package type they selected, etc. Any help would be greatly appreciated.
You already have a form in your page. I suggest you create hidden inputs in this form to be submitted with the form. Ex :
<input type="hidden" name="base_cost" value="999">
and you can adjust the value easily with jquery. After submitting the form to the php page you can capture these values using :
$base_cost = $_POST['base_cost'];
But don't forget to sanitize and validate every input from the user.
Hope this helps and excuse my English.
You are looking for a way to tell the Server information from the User? That my friend, without sending the form and without using ajax, will be hard :)
If I am understanding the issue properly, you want some parameters to change in Client side when user triggers some action. In that case you could load the possible parameters on page load and, when user triggers those actions, get the new parameters from those already loaded.
Then when you send the form you add to it the selected parameters.
Hope it helps!
I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp
i have a simple form with two fields whose data are being validated against a database on keyup with jquery. I am also having a button which is currently enabled or disabled based on the number of characters entered in these two fields. THe two jquery functions return an "accept" or "cancel" image for the two fields. I want to enable the button only if both the functions return the accept image or i can even make them return true along with it, which will not be a problem. I just wanna know how to compute a local result based on the returned value from two different ajax requests.
These are two functions that validate teh field against a database.
$("#agentName").keyup(function(){
var agentName = $("#agentName").val();
if(agentName.length > 3)
{
$("#agt-name-result").html(ajax_load).load(loadUrl, "val="+agentName+"&fld=agent_name");
}
else{
$("#agt-name-result").html("<img src=\"images/cancel.png\" />");
}
});
$("#agentSource").keyup(function(){
var agentSource = $("#agentSource").val();
if(agentSource.length > 9)
{
$("#agt-src-result").html(ajax_load).load(loadUrl, "val="+agentSource+"&fld=agent_url");
}
else{
$("#agt-src-result").html("<img src=\"images/cancel.png\" />");
}
});
This is the function that validates the button
$("#agentName,#agentSource").keyup(function(){
var validate;
var agentName = $("#agentName").val();
var agentSource = $("#agentSource").val();
if((agentName === "") || (agentSource === "") || (agentName.length < 3) || (agentSource.length < 10))
{
validate = false;
}
else { validate = true; }
if(validate === true) {
$("#addAgntBtn").removeAttr("disabled");
$("#addAgntBtn").removeClass("dialog-btn-disabled").addClass("dialog-btn");
}
else {
$("#addAgntBtn").attr("disabled", "disabled");
$("#addAgntBtn").removeClass("dialog-btn").addClass("dialog-btn-disabled");
}
});
Any ideas?
I would use a setInterval to poll a $.data() value in which the two ajax calls put their results. You have to pay attention to concurrent accesses, but it should work
I want to validate Checkbox in javascript, checkboxes is generating dynamically by PHP and name of checkboxes are like "checkbox1" , "checkbox2" ,"checkbox3" i.e. incrementing i++ and these numbers are coming from database, it might be first time only 2 rows fetched and next time 112 rows.
How i can make sure in javascript that atleast one checkbox must be selected.
// When you use jQuery... somehow like this
$('form').submit(function() {
if ($("input:checked").length == 0) {
alert('Please check at least one checkbox!');
return false;
}
});
If you do not want to use any js framework, then just give the same name attribute to the checkboxes
Assuming your checkboxes are named test
var chkBoxes = document.getElementsByName("test");
var chked=0;
for(var i=0;i<chkBoxes.length;i++)
{
if(chkBoxes[i].checked)
chked++;
}
if(chked===0)
alert("Please select a value");
Added as per the sample code specified in the comment
function isChecked()
{
var i=1;
var chkd=0;
var elem = "";
var chkForMoreChkBoxes=true;
do{
elem=document.getElementById("check_"+i);
try{
if(elem.checked)
{
chkd++;
}
i++;
}
catch(err)
{
chkForMoreChkBoxes=false;
}
}while(chkForMoreChkBoxes)
if(chkd===0)
{
alert("Please select a value");
return false;
}
}
i have check box array like this
for($j=1;$j<=10;$j++)
<input type="checkbox" name="chkLimit[]" id="chkLimit_<?php echo $j;?>" value="<?php echo $j;?>" />
i got 10 check box
and i write the jquery code like this...
$(document).ready(
function (){
setLimitSelection();
}
);
function setLimitSelection(){
$('input[name="chkLimit[]"]').limitSelection(
{
// number of items to limit to
limit: 4,
// on error, do this
onfailure: function (n){
$("#idCheckboxMsg").html(
"You can not select more than " + n + " items."
);
return false;
},
// on success, do this
onsuccess: function (n){
$("#idCheckboxMsg").html("");
return false;
}
}
);
$('select[name="selLimit[]"]').limitSelection(10);
}
$("input.chkLimit").click(function() {
var numSelected = $("input.chkLimit[]:checked").length;
var numLeft = 10 - parseInt(numSelected);
$("#statusBox").html("You have "+numSelected+" CD's selected.<br>You have "+numLeft+" selections left.");
});
what i want is: user can't select more than 4 check boxs
thanks
I haven't tested this, but it should get the job done for you:
$(function(){
$("#myCheckboxes input[type='checkbox']").change(
var checked = $("#myCheckboxes input[type='checkbox'][checked]").length;
if(checked == 4){
$("#myCheckboxes input[#type='checkbox']").not(":checked").attr('disabled',true);
}else{
$("#myCheckboxes input[#type='checkbox']").not(":checked").attr('disabled',false);
}
)
});
Every time the checked state of a checkbox changes, it looks at how many checkboxes are checked. If there are 4, it disables the unchecked boxes, otherwise it enables them. This assumes that they all live in a container called #myCheckboxes
Looks like #inkedmn had some syntax errors but the comment box just isn't adequate to elaborate. So, here's what I think he's trying to do:
$(function(){
$("#myCheckboxes input[type='checkbox']").change(function() {
var checked = $("#myCheckboxes input[type='checkbox']:checked").length;
if(checked == 4){
$("#myCheckboxes input[type='checkbox']")
.attr('disabled',true)
.filter(':not(:checked)')
.attr('disabled',false);
} else {
$("#myCheckboxes input[type='checkbox']").attr('disabled',false);
}
)
});
That should get it done for you.