To start off, sorry if this is a duplicate, or explained already. I've read a minimum of 15 other topics that I assumed are similar to mine, yet I haven't had any success in getting it to work.
I currently have a form that is action="submit.php". The form is an order form (see Jfiddle link at bottom of post). Inside submit.php I'm making an array of all $_POST values. That works great. Now the problem:
On the forum page (where user inputs), I have the following JQuery script that calculates totals. There are 3 types of totals (all this is clear in the JFiddle). The 3rd total, called "overallTotal", takes the sum of all "grandTotal"s and as of now, puts in #overallTotal ID. I need that number to be included in the form submission (i.e., so it is accessible by $_POST).
Thanks in advance, and sorry again if this is repetitive.
JSFiddle: http://jsfiddle.net/rc694dzL/
function oninput(e) {
// process this row first
var row = $(e.target).closest("tr");
// explicitly cast to a number
var quantity = +$(e.target).val();
var price = +row.find(".val1").text();
var output = row.find(".multTotal");
var total = price * quantity;
output.text(total);
// now calculate total
var subtotal = 0;
var table = $(e.delegateTarget);
table.find(".multTotal").each(function () {
subtotal += (+$(this).text());
});
table.find(".grandTotal").text(subtotal);
// now calculate overall total
var overallTotal = 0;
$(document).find(".grandTotal").each(function () {
overallTotal += (+$(this).text());
});
$('#overallTotal').text(overallTotal);
Add a hidden input in your form like this
<input type="hidden" name="overallTotal" id="overallTotalInput">
and set the value from javascript like this
$('#overallTotalInput').val(overallTotal);
Now when submitting the form, the value will be stored into $_POST['overallTotal']
Add some hidden fields in the form, and then populate the values with jquery.
Edit: tweaking your Fiddle now with an example: http://jsfiddle.net/dozecnp6/1/
1) Added the hidden input in the form:
<input type="hidden" name="OverallTotal" id="overallTotalField">
2) Added a bit to your oninput() function:
$('#overallTotalField').val(overallTotal);
in this fiddle i can use type="text" you can change it to type="hidden"
check this
fiddle
Related
I have three variables. Two are server side from a database:
$base_duration = $arr['adzone_buyandsell_duration']
and
$base_price = $price['price']
both are int. The third will be user input: <input type="text" name="duration" value=""> I need to preform a calculation like such: $cal_price = $base_duration / $base_price * user_input I then need to be able to pass $cal_price back to be able to charge the user the correct price. I'm fairly familiar with php, but don't know how to perform this calculation in real time not when the form is submitted.
When the first two values only change when the page is loaded or resfreshed, there is no need for a AJAX call.
Add the following code to your page:
<script>
$('document').ready(function(){
$('#duration').change(function(){
var base_duration = <?= $arr['adzone_buyandsell_duration'] ?>;
var base_price = <?= $price['price'] ?>;
var userInput = $('#duration').val();
var cal_price = base_duration / base_price * userInput;
$('#calPrice').html(cal_price);
});
});
</script>
It will add the calculated result to a div with the id calPrice and you have to give the input field the id duration
I created a jsFiddle for you to see the code in its full glory. I just used dummy data for your php variables.
https://jsfiddle.net/03e3t137/
Make sure you add jQuery on your page by adding the following line in your <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
I've found most of the pieces i've needed for this form (making the fields dynamic, etc.) however now the array part of this doesn't seem to work to be able to submit correctly.
what i'm trying to accomplish:
a form with a select field that can be duplicated dynamically and then be submitted as a part of the form to it's own table. so if we add and choose three people in the one form, it submits to it's own attending table with a foreign key back to the event the form is for. had to make it dynamic because we'll never know for sure how many people will be attending said event, but it has to happen all in one form. just because it does. my boss says so.
here's my javascript for the add another field button:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the id value of the input inside the new element
newElem.children(':first').attr('id', 'attendee' + newNum).attr('name', 'attendee[' + newNum + ']');
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 6)
$('#btnAdd').attr('disabled','disabled');
});
here's what the field starts out as in the form:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<select name="attendee[1]" id="attendee1" style='float:right;margin-right:4.5%;'>
<option value=''>Please choose one...</option>
<?php
while($row_attendees = mysql_fetch_assoc($res_attendees)){
$attendee_id = $row_attendees['attendee_id'];
$attendee_name = $row_attendees['name'];
echo "<option value='".$attendee_id."'>".$attendee_name." </option>";
}
?>
</select><label style='width:100px;display:inline-block;line-height:28px;' for="attendee">Attendee</label>
</div>
I'm getting all the things to change correctly. all of the select inputs are being id'd and name'd correctly. the div is being updated the same. all of that works correctly. what doesn't is when i go to submit. here's my php:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."','".$attendee."')";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
all the tutorials i used to pull this together show this as correct. however it doesn't work. i'm only getting whatever the first dropdown is, and nothing else is populating into the array. at least that's all it shows/submits if i run the form or echo the attendee variable in the foreach statement. PLEASE HELP! :)
thanks a ton in advance.
UPDATE
I have tried a few ways discussed with another user to display the array for $_POST['attendee'], however it still just shows 1 id in the array, and not however many fields i've actually added. I've also tried removing the number from the array in the select's name attribute. so it would just be name='attendee[]' instead of name='attendee[1]' and so on. this also doesn't help any. can someone please help with why my dynamically added fields aren't being added to the array?
I put your code into a JSfiddle, here: http://jsfiddle.net/rv8Mv/1/
It looks like the selects are being added correctly. You can check by clicking the "Submit" button, which shows a data string of what will be submitted to the server.
One thing you might want to check, is to make sure you are enclosing all the select elements inside a <form> element, which you didn't include in your question.
I think your problem is in the PHP code on the server.
On the server, make sure you are receiving all the variables by using this code:
<?php
foreach($_POST as $key => $value){
error_log($key.' -> '.$value;
}
?>
Then check your error log to see the names and values for all the POST variables.
You are probably not referencing the POST variables correctly in your current PHP code.
You should change your sql to look like this:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."',".$attendee.")";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
Your attendee_id is an int column. You were wrapping the column content with single quotes, which denotes a string. This would result in your attendee_id being null if your column is defined as nullable.
I have a loop in php that echos out a <input type="hidden" id="lol" value=$id />
Every time the loops go through i get a new value in the hidden input field as you can understand.
Now, im trying to grab the value from each of these items and get grab it with Javascript and SAJAX.
The javascript im using now works, But! It only grabs the first value (because the ID is the same on each input)
Javscript:
function Showbooking() {
id = document.getElementById('lol').value;
x_showBookingForm(id, do_showBookingForm);
}
function do_showBookingForm(html) {
openPopup(600, 550, html);
}
As you can see im opening a POPUP with javascript aswell and exports the value into that popup window.
So on every popup I get the same value (the value from the first input).
How Do I get around this problem?
Change ID to name
Use document.getElementsByName and loop
var lols = document.getElementsByName("lol");
var vals=[];
for (var i=0, n=lols.length;i<n;i++) {
vals.push(lols[i].value);
}
alert(vals.join(","));
getElementById says element rather than elements because it returns only one item. id is supposed to be unique. You could do something to the effect of:
var inputs = document.getElementsByTagName("input");
var values = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].type === "hidden"){
values.push(inputs[i].value;
}
}
I have a long form and I need to count the number of inputs and textareas that have data inside them. I need an input field that will display a number representing the number of inputs and textareas that have data within my form.
I prefer jquery or PHP.
Are there any examples out there or suggestions?
Thanks.
Erik
With jQuery you can just use this
var number = $('#form').find('input, textarea')
// filter out every empty input/textarea
.filter(function() { return $(this).val() == ''; })
.length;
You could do an onkeypress function that runs and updates your div with the number of fields that have data.
Off the top of my head but maybe:
function tallyFields() {
var totalFilledFields = 0;
var fieldAVal = document.getElementByID("fieldA").value;
// add more fields here the same way
if(fieldAVal.length > 0) {
totalFilledFields++;
}
// check more fields here the same way and increment the same var
document.getElementByID("yourTotalDiv").innerHTML=totalFilledFields;
}
Assigning this function onkeypress of each of your form fields might do the trick.
This should do the trick:
$(".myform :input").length;
Mostly i have 28 items, i used pagination and display in 3pages using Ajax
each page have 10 items, whatever i selected in check box it should display values at bottom ,every thing is OK right now, but my problem is when i select items in second page the previous list is disappearing , when i return back to fist page it is not showing previously selected items .
iam not getting how to do this
please help
thanks
i used this jquery code to get checked values
function showValues() {
var page = $("#pagedis").val();
var fields = $(":input").serializeArray();
$("#results_" + page).empty();
jQuery.each(fields, function(i, field) {
$("#results_" + page).append(field.value + "<br> ");
});
}
i need the action like gmail if we select 3 items in one page ,4 items in 2nd page ,when i come back the checked value will never chage
do your checkboxes all have the same name? If not, name them all the same.
make sure each checkbox has a unique value attribute
attach a handler to keep track of the checkboxes checked in an array
:
// global variable somewhere
var checkedBoxes = new Array();
$('input[name=theNameYouDefinedAbove]').click(function(event){
checkedBoxes[$(this).val()] = $(this).is(':checked');
});
Now, when you paginate, just do this
:
$('input[name=theNameYouDefinedAbove]').each(function(index, checkbox){
if (checkedBoxes[$(checkbox).val()]) {
// NOTE: choose ONLY ONE!
// for jQuery 1.6+
$(checkbox).prop('checked', true);
// for all jQuery
$(checkbox).attr('checked', 'checked');
}
});