I am trying to build a form calculation javascript that works fine with radio buttons, but I haven't been able to make it work with checkboxes.
The form includes a domain whois check, which generates checkboxes with the name 'domain' and the value is the checked domain's tld, its price is echoed in the same table cell. I managed to whip up a js code that matches the checked values with data from an array containing the tld prices. (see below)
Problem #1: The value of the checkbox should be the whole domain name (so that I can carry that variable with $_POST later on
Problem #2: The currently working js does not add up more domains of the same tld (foo.com and bar.com's price is added only once insted of twice) since the for loop that works well with radio buttons cannot work with multiple checks
--
Solutions I have pondered:
Solution #1: Add ID to checkboxes with their names being the searched domains and their value being the price of that domain tld and push them into a js object where the for loop could match the checked ones with their prices -- conflicts with problem #1, although I suppose I could get all checked checkboxes with jQuery and append them to a hidden input that PHP could process later on (?)..
Solution #2: Make js get the price of the domain from the table cell it's located in and add that up. -- problem: how do I make js get the price if the table cell's ID depends on what domain is searched for?
Here's the currently working js that processes only the checkboxes:
var domaintld = new Array();
domaintld["com"]=3000;
domaintld["eu"]=3650;
domaintld["org"]=3650;
domaintld["net"]=2850;
domaintld["info"]=4050;
function calcdomaintldPrice() {
var domaintldPrice=0;
var theForm = document.forms["orderform"];
var chosenDomains = theForm.elements["domain"];
for(var i=0; i < chosenDomains.length; i++) {
if(chosenDomains[i].checked) {
domaintldPrice = domaintld[chosenDomains[i].value];
break;
}
}
return domaintldPrice;
}
Here's an example of a checkbox markup:
<input type="checkbox" name="domain" value="net" id="dfbdfb.net" class="domainradio"
onclick="calculateTotal()"><label for="dfbdfb.net" class="domainradio"> </label>
Ad problem 1: You might want to provide more info, such as how the html is generated. As far as I can see you could just set value to the same as id couldn't you?
Ad problem 2:
Substitute
domaintldPrice = domaintld[chosenDomains[i].value];
with
domaintldPrice += domaintld[chosenDomains[i].value];
and remove the break
Related
I have a drop-down menu in a form with elements retrieved from a database. Something like this :
for($i=0;$i<count($resq);$i++){
print("<li><a class=\"dropdown-item\" href=\"#\" id=\"$i\">{$resq[$i][0]}</a></li>");
}
$resq being an array containing the result of the query (i used mysqli_fetch_all).
As you can see I tried to dynamically generate the id of the items(first item has id=0, second has id=1 and so on till the final value of $i) but I think this is not correct.
Previously, I had the following JS code(which worked) which I used to set the drop-down value to the one selected by the user and to set the value of a hidden input to that value.(I know the code isn't elegant but I just wanted to test the logic in the first place)
var x=document.getElementById('dropdownMenuButton1slct');//dropdown
var c1=document.getElementById("0");//i - categories(IDs of the dropdown elements)
var c2=document.getElementById('1');
var c3=document.getElementById('2');
var c4=document.getElementById('3');
var c5=document.getElementById('4');
var p=document.getElementById('iaval');//hidden input from form
function clic(z){
z.onclick=function () {
x.innerHTML=z.innerHTML;
p.value=x.innerHTML;
};
}
clic(c1);
clic(c2);
clic(c3);
clic(c4);
clic(c5);
But now the same method won't work. If you can, please suggest me a different way or something, I am kinda stuck. I can provide more info if this seems vague or something like that. Thanks.
I am not a front-end developer and I have very limited exposure to JQuery JS etc. So any help is appreciated, thanks.
Objective : - I want to put the sum of all fields (except last ) of a fieldset into last field of that fieldset.
The form is rather complicated, in this form, there are multiple fieldsets and each fieldset contain multiple fields.
This form is generated by Drupal Views & I have very limited options to navigate in this form.
I can not use id, name or any other attribute as they are dynamically generated by CMS also there are hundreds of such fieldset so it is not feasible to write code for every one of them.
So, future addition of fields may alter the attributes. And I can not add my own attributes, classes, or ids to this form.
form looks something like this
<fieldset>
------<div>
---------<fieldset> **this one**
------------------<input>
------------------<input>
------------------<input>
------------------<input>
----------------nth <input> <= Sum of 1st to (n-1)th should come here
-----------------------<div>
I think that it can be done possibly through input:last but can't figure out how to use it properly.
Here is the function I wrote
$(function() {
$('input').change(function() {
var sum = 0;
// Loop through all inputs
$(this).closest('fieldset').find('input').each(function() {
sum += parseInt($(this).val());
console.log(sum);
// i want to put sum into last <input> tag of the current fieldset
});
});
}); // end function()
the output of console.log ($(this).closest('fieldset').find("input").last());); is
So, I figured that I have to extract attribute value, so far I have tried these
$(this).closest('fieldset').find("input").last().data('value'); Undefined
and
$(this).closest('fieldset').find("input").last().attr('value'); results in Undefined
I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];
I'm trying to generate a price based on radio button selections, on input fields that are added (sort of like a list). Unfortunately since each set of radio buttons added has a unique name (so that they can be parsed separately later) the function that calculates the price is pulling the radio buttons value by it's name. This is clearly problematic since there are multiple instances of the same scenario.
Anyone?
http://jsfiddle.net/pxrpF/1/
I'm also looking to generate a Grand Total that will add up each set, so if anyone can help me figure these two bits out that would be wonderful!
This should handle the problem with grabbing the right radio buttons:
var containerCount = $(this).parents('.container').prevAll('.container').size();
var $r = $('.container:eq('+containerCount+')').find(cardType);
var $d = $('.container:eq('+containerCount+')').find(cardQ);
EDIT (to incorporate conversation below)
In addition, the selector strings cardType and cardQ should be as follows:
var cardType = ":radio[name*='type']:checked"
var cardQ = ":radio[name*='quantity']:checked"
The *= ensures that the attribute starts with type or quantity respectively.
I have a table which has a button to "Add Rows". This button adds a row dynamically with JQuery. It works by copying the first ... and then replacing all the id=".." with an incremented number.
The problem is that the rows have a YUI AutoComplete which looks like the following:
<td>
<input type="hidden" name="location_num[0]" value="508318" maxLength="25" style="width:230px" id="location_num[0]"/>
<input type="textbox" name="location_numDisplayDesc[0]" value="WINNIPEG" maxLength="25" style="width:230px" id="location_numDisplayDesc[0]"/>
<div id="Container_location_num[0]" style="display:inline;"></div>
<script type="text/javascript">
// Initialize autocomplete
var location_numAC = new YAHOO.widget.AutoComplete(
"location_numDisplayDesc[0]",
"Container_location_num[0]",
locationDataSource,
acConfig);
location_numAC.useShadow = true
location_numAC.useIFrame = true
location_numAC.dataErrorEvent.subscribe(acErrorFunction);
// Format results to include the reference number
location_numAC.formatResult = function(resultItem, query) {
return resultItem[0];
};
// Clear key before request
location_numAC.dataRequestEvent.subscribe(function fnCallback(e, args) {
YAHOO.util.Dom.get("location_num[0]").value = ""; });
// Set key on item select
location_numAC.itemSelectEvent.subscribe(function(event, args) {
YAHOO.util.Dom.get("location_num[0]").value = args[2][1];
});
// Clear key when description is cleared
location_numAC.textboxBlurEvent.subscribe(function fnCallback(e, args) {
if (isEmpty(YAHOO.util.Dom.get("location_numDisplayDesc[0]").value)) {
YAHOO.util.Dom.get("location_num[0]").value = "";
} // end if
});
</script>
</td>
This code works fine in Firefox and the newly created AutoCompletes work, but in IE (6 & 7) I am getting an error that means that the location_num_AC is not being created successfully. I believe that it's because that it's not reading the newly created inputs or div as it should. I've tried wrapping the javascript with
$("Container_location_num[0]").ready(function {...});
but that didn't seem to work. Does anyone have any other ideas?
Form fields that are inserted into the DOM in IE don't add to the forms collection as you might expect.
Normally you can refer to a form field one of two ways:
document.forms[0]["myFormName"];
document.forms[0][12];
That is, by its form field name or by its index. But when you add a form field to the DOM in IE you can't refer to it by name, only by its index. If your code (or any supporting code) is looking for a form field in the collection by its name you've obviously got a problem.
If your only key is the name you can loop through all the form fields by index and find what you're looking for, but that's obviously going to be a linear operation. You can also loop through and find which form fields are indexed numerically but not by name and update the form object yourself.
I don't have enough detail to know how (or if) this is occurring in your project, but it's one of those IE quirks that sounds like it might be playing a role since you're adding fields dynamically.