PHP $_POST value being lost when using JS .insertAfter() - php

I have the following code, which should adds a field to a form if the user selects 'Other' from a dropdown. However, using this code seems to overwrite the value of the dropdown, so that when the form is posted $_POST['enquiry_source'] is empty.
I've narrowed it down to this line that is causeing me the problem buy adding the field on any change in the dropdown, not just if 'Other' is selected -
$(field_to_append).insertAfter('#form-field-enquiry_source');
I've also tried $('#form-field-enquiry_source').after(field_to_append);, but the result was the same.
$(function(){
/** Looks for changes to the enquiry source dropdown */
$('#form-field-select-enquiry_source').live('change', function(){
/** Check the enquiry source */
var enquiry_source = $('select[name="enquiry_source"]').val();
/**
* Adds another field to the enquires form when the user selects 'Other' form the enquiry source dropdown
*/
if(enquiry_source === 'other'){ // The user has selected other as the enquiry source, so lock the form
var field_to_append = '<div id="form-field-enquiry_source_other" class="form-field float-left">'+
'<label>Other<span class="required"></span></label>'+
'<input name="enquiry_source" id="form-field-input-enquiry_source_other" />'+
'</div>';
$(field_to_append).insertAfter('#form-field-enquiry_source');
} else {
$('#form-field-enquiry_source_other').remove();
}
});
});
Any ideas what is causing this problem?

If you have a select with name = enquiry_source and then you ad an input with the same name only one element is posted to the server, in your case the input field (only the latter element is posted) so you should give the field a different name
var field_to_append = '<div id="form-field-enquiry_source_other" class="form-field float-left">'+
'<label>Other<span class="required"></span></label>'+
'<input name="enquiry_source_other" id="form-field-input-enquiry_source_other" />'+
'</div>';

Are you inserting inside? sounds like you are generating a html code like
<form>something</form><input name=enquiry_source>
Maybe what you want is $('#form-field-enquiry_source').append($(field_to_append));
I don't know what is "#form-field-enquiry_source". Is a form?

I know this may seem a bit off topic (but kind of is not). You could change your approach by having a hidden div with those contents already within it, then your problem comes down to having the drop down show/hide depending on the field.
The nice part about this is upon javascript minification that long strings cannot be minified, you will save a lot more space by doing it this way.
if(enquiry_source === 'other'){ // The user has selected other as the enquiry source, so lock the form
$("#enquiry_source_other").show();
} else {
$("#enquiry_source_other").hide();
}
I feel like this approach is a bit simplier

Related

Setting checkbox state correctly

I'm hoping I'm on the right track here....
I have some elements on my page (tables).. that are dynamically generated based on the results of querying a DB.... (I add inside of a container DIV)..
inside these tables are some text..and a handful of checkboxes... each table is the same (outside of the value of the text fields)..
When a user clicks on a checkbox.. I add an element to another container DIV off to the side.
If a user un-checks the checkbox.. it removes the element from the container DIV on the side. On each 'click' event..... I am also either adding or removing the 'selections' from an ARRAY (and also updating this array to my PHP SESSION)..
When the user is done.. they click a button and go to another page.. where this SESSION array is grabbed and reviews/summarizes their 'choices'..
*there is no FORM tags.. checkboxes are free-form in the tables (not wrapped in any FORM tags..so there is NO general POST action to grab everything.. hence the use of an array/SESSION)
If the user goes BACK to the original 'selection page' (with the tables/checkboxes)..
I am re-populating the PAGE (both re-checking any checkboxes...and re-populating the elements in the container DIV to the side.. all based on the SESSION data)
In each checkbox.. I am adding a little PHP function to write in checked="checked" or not.. when the checkboxes instantiate)
like so:
<label><input id="articlesnaming" name="Articles Naming Expert" type="checkbox" value="0.00" <?=sessionCheck($row["id"] ."-A","Articles Naming Expert") ?> onclick=""/> Articles Naming Expert</label>
FYI: on the function being called:
function sessionCheck($recordID, $checkBoxID){
if(isset($_SESSION['userPicks']) && count($_SESSION['userPicks']) != 0){
for($r = 0; $r< count($_SESSION['userPicks']); $r++){
if($_SESSION['userPicks'][$r]['recordid'] == $recordID){
for($z=0; $z < count($_SESSION['userPicks'][$r]['itemsordered']); $z++){
if($_SESSION['userPicks'][$r]['itemsordered'][$z]['name'] == $checkBoxID){
return 'checked="checked"';
}else if($z == (count($_SESSION['userPicks'][$r]['itemsordered']) - 1)){
return "";
}
}
}else if($r == (count($_SESSION['userPicks']) - 1)){
return "";
}
}
}else{
return "";
}
}
Everything up to this point works fine...
Its when I go to dynamically build/add (append) those elements in the container DIV on the side... where problems happen.
I am getting them added just fine and when a user RE-VISITS the page.. previous checkboxes they had selected were/are checked again... -and-.. the elements ARE in the container DIV to the side of the stage/screen)...
PROBLEM: When I un-check one of the checkboxes, it DOES NOT remove the element in the container DIV on the side? I have to re-click the checkbox..(which adds a duplicate).. then I can un-check it.. but it only removes the NEW one..
Everything seems to work fine until a refresh/re-visit of the page (and I have to automatically populate the checkboxes and the elements in the container DIV on the side).. then the checkboxes stop behaving/interacting with the elements that were adding through another function (still same ID's...paths..from what I can tell)....and -not- added through an initial checkbox event/action..
I am grasping at straws here.... it is perhaps because I'm using a PHP function to set the checkboxes on refresh? and it maybe doesn't know its current state? (although the visual state of the checkbox is accurate/correct)
Any ideas are appreciated.
Code used to set/un-set checkboxes & add/remove elements from the side container DIV :
<script>
//var to hold current check box clicked
var targetCheckbox;
//var to hold cumulative total
var totalPrice = 0;
//array to keep track of user picks from returned record results
//try to get SESSION array (if available/set) from PHP into jQuery using json_encode()
<?php if(isset($_SESSION['userPicks'])){ ?>
//overwrite jQuery userPicks MAIN array
var userPicks = <?php echo json_encode($tempArray) ?>;
<? }else{ ?>
//create new jQuery userPicks MAIN array, and populate through user clicks/interaction
var userPicks = [];
<? } ?>
$(document).ready(function() {
//check to see if seesion and populate checks and side column from previous picks
//if existing session, loop through and populate the CHOICES column
if(userPicks.length > 0){
console.log("SESSION EXISTS, POPULATE CHOICES COLUMN FROM ARRAY");
for(i=0; i<userPicks.length; i++){
//build up sub array data first then append at one time.
var subArrayLength = userPicks[i].itemsordered.length;
var subArray = '';
for(s=0; s<subArrayLength; s++){
subArray += '<li id="' + userPicks[i].orderid + userPicks[i].checkboxid + '">' + userPicks[i].itemsordered[s].name + '</li>';
}
$("#choicesWrapper #itemList").append('<div class="recordChoices"><h5>CASE NAME: '+userPicks[i].casename+'</h5><ul id="'+userPicks[i].recordid+'">'+subArray+'</ul></div>');
}
}
//onClick event
$('.orderOptions').on('click', 'input:checkbox', function () {
//routine when checkbox is checked
if ($(this).is(":checked")) {
$(this).prop("checked", true);
console.log("checked");
//console.log('doesnt exist..create it');
$("#choicesWrapper #itemList").append('<div class="recordChoices"><h5>CASE NAME: '+caseName+'</h5><ul id="'+resultsID+'"><li id="'+orderID+targetCheckbox+'">'+itemOrdered+'</li></ul></div>');
}else{
$(this).prop("checked", false);
console.log("un-checked");
//remove the option from right column (li element)
console.log("REMOVE TARGET: #choicesWrapper #itemList #"+resultsID+" "+orderID+targetCheckbox);
$("#choicesWrapper #itemList #"+resultsID+" #"+orderID+targetCheckbox).remove();
//check if no more children and remove parent/title (record container/div)
if ($("#choicesWrapper #itemList #"+resultsID+" li").length > 0) {
//console.log("Still has children...do nothing");
}else{
//console.log("No Children...");
$("#choicesWrapper #itemList #"+resultsID).parent().remove();
}
}
}
}
</script>
Oddly enough, when things are 'auto-populated' from the SESSION data (like on refresh or re-visiting the page) and when things 'break', unchecking the checkboxes doesn't remove things, but when I uncheck the very last checkbox in a group, it does remove the parent (so that parent removal code/routine is being executed...but not then child )
I'm thinking this is a pathing issue? (I believe I am creating things with exactly the same ID's/classes...etc).
Definitely worth the +1 if you answer! :)
The only other thing I can think of is.. HOW the userPicks array gets created.. initial visit to page, I just create an empty JS/jQuery array and wait to push/populate it when a user clicks a checkbox (code above for onClick stuff).
But when a user visits the page (refresh or re-visit) and -HAS- (previous) SESSION data still available.... then I grab the PHP SESSION array.. and pass it to jQuery using json_encode()...
Do I need to add/delete from that array differently than I do if I created normally?

Grab checkbox values before form submission

I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.

array not working for dynamic form field

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.

form validation using javascript in changing input tags

I need to validate a form using JavaScript. The form keep changes since I am using data from a field name table to print each field (like name, address, phone no.). I'm using a loop to print the label for field and corresponding text input tag. (eg. name : textbox to enter name, phone no : textbox to enter phone no.) And at last getting these values in an array when submitting the form and entering into details table.
Following is the code for printing each field and text box:
while ($row=mysql_fetch_array($result)){
echo'<labelfor='.$row['field_name'].'name=field_id>'.$row['field_name'].':</label>';
echo'<inputtype="text" name=field_name[]id="'.$row['field_id'].'":value="'.$row['field_value'].'" size="20" class = "inpBox" >';
}
Now I need to check whether these fields are empty using JavaScript and then change the style of that particular text box. Any help will be greatly appreciated.
You'll want to hook on the submit event for your form. You could then do something like:
This is for jQuery:
$("form").submit(function{
$('input[type="text"]',"form").each(function(){
var $me = $(this);
var status = true;
if($me.val() == ""){
$me.addClass("input-validation-error");
status = false;
}
//Return status. True=Form is valid, False=Form is NOT valid
return status;
});
});
You can read more here: http://api.jquery.com/submit/
To get the values for javascript, you could do something like:
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var me = inputs[i];
if(me.value == "") {
me.className = "input-validation-error";
}
}​
Generally Google "dynamic form validation"
For your particular case you will be interested in
See https://developer.mozilla.org/en/DOM/document.getElementsByClassName
and loop over all elements. You may want to add extra properties to your entry fields to define if it needs validation and the type of validation needed.

Create form dynamically in table

Using some code to create a form dynamically which I got here: http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm
This works great. However I have a regular html table I generate with html/php to get data out of a DB. I want to replace that data with a form so when users click the edit button the original entry is replaced with a form (either textbox or pull down menu). The user makes a selection and the new table comes back with the appropriate edit.
So for example one part of the data has this in the table:
<td><?php echo $result[0] ?></td>
Using the link about to create a form dynamically I change this to:
<td id="paraID"><form id="form1" name="form1" method="post" action enctype="text/plain" alt=""><?php echo $result[0] ?></form></td>
Also note the onclick event for the edit button:
This is hard to explain but hoping someone can help me with this interaction. I need some way to say:
if (user clicks edit button)
then
replace html table with form for each entry (for example, the table returns a name called foo and a textbox will appear with foo in it but now they can edit to change the name).
If you can start out with an id for the td then it will make things easier. Then you will need an edit button somewhere. Notice: It might be nice to replace "result_0" with the name for the value/field:
<td id="result_0_parent"><?php echo $result[0] ?><input type="button" onClick="editField('result_0','select')" value="Edit" /></td>
Then in your javascript you will have the editField function defined so that it sets the content of the td to be the dynamic form. Looking at makeForm function in the example javascript, you see this happening with appendChild(myform); The function editField will be like the makeForm function except you will pass in the field_id and field_type as parameters:
function editField(field_id, field_type)
I suggest you change the line that defines mypara to define mytd or better yet, field_parent instead since in your case it will not be a paragraph element, but a td (or possibly some other type of element):
field_parent = document.getElementById(field_id+"_parent");
The example code create a select (dropdown), but I am guessing you want to create other field input types so I recommended having field_type as a second parameter to the function. This means that it would make more sense for your implementation to use myfield instead of myselect and then use the field_type parameter to decide what myfield will be.
Replace the line in the makeForm / editField function:
myselect.setAttribute("id","selectID");
with
myfield.setAttribute("id",field_id);
One more thing: To set the initial value of the input field to be the displayed content, you will need to copy the "innerHTML" of the "parent" element. So place something like this right after defining field_parent:
initial_value = field_parent.innerHTML;
and I think you can figure out the rest. If not, I can elaborate a little more.
This works great. However I have a regular html table I generate with
html/php to get data out of a DB. I want to replace that data with a
form so when users click the edit button the original entry is
replaced with a form (either textbox or pull down menu). The user
makes a selection and the new table comes back with the appropriate
edit.
This is a script that allows with a double click on values to edit them and has a button to send them back. Maybe it would be of some help to use it (or use parts of it).
<?PHP
if(count($_POST)>0)
{
echo 'You gave:<br><per>';
print_r($_POST);
echo '<a href=http://localhost/temp/run.php>Start over</a>';
exit;
}
?>
<html>
<head>
<script type="text/javascript">
/**formEditor Class
*/
function formEditorCls( )
{
/**
Constructor simulator
*/
this.lastFieldEditedId = null;
/** Change span with input box, hide the eddit button and store theses IDS
*/
this.edit=
function (field)
{
//if there was a field edited previously
if(this.lastFieldEditedId != null)
this.save();
//get the inner element of the div, it can be span or input text
var childElem = document.getElementById(field).getElementsByTagName('*')[0];
//then replace the span element with a input element
document.getElementById(field).innerHTML="<input type=text name=n_"+field+
" id=id_"+field+" value="+childElem.innerText+">";
//store what was the last field edited
this.lastFieldEditedId =field;
}//func
this.save=
function ()
{
dbq="\"";sq='\'';
//get the last value
var lastValue = document.getElementById(this.lastFieldEditedId).
getElementsByTagName('*')[0].value;
//store it as span
document.getElementById(this.lastFieldEditedId).innerHTML="<span ondblclick="+dbq+
"formEditor.edit("+sq+this.lastFieldEditedId+sq+");"+dbq+" >"+lastValue+"</span>" ;
//now must reset the class field attribute
this.lastFieldEditedId=null;
}//func
this.submit=
function (path)
{
this.save();//if ay field was edited put new values in span elements
var form = document.createElement("form");//create a new form
form.setAttribute("method", "post");
form.setAttribute("action", path);
var myDiv = document.getElementById( "fieldsDiv" );//get the div that contains the fields
var inputArr = myDiv.getElementsByTagName( "SPAN" );//get all span elements in an array
//for each span element
for (var i = 0; i < inputArr.length; i++)
{
var hiddenField = document.createElement("input");//create an input elemet
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", i);
hiddenField.setAttribute("value", inputArr[i].innerText);
form.appendChild(hiddenField);//append the input element
}
document.body.appendChild(form);//append the form
form.submit();//submit the form
}//func
}//class
formEditor = new formEditorCls( );
</script>
</head>
<body onclick="rt();">
Double click any value to change it..<br><br>
<div id="fieldsDiv">
Name:<font id="nameField">
<span ondblclick="formEditor.edit('nameField');" >Mark</span>
</font><br>
Surname:<font id="surnameField" >
<span ondblclick="formEditor.edit('surnameField');">Smith</span>
</font><br>
</div>
<input type=submit name="submit"
onclick="formEditor.submit('http://localhost/temp/run.php');" value="Submit">
</body>
</html>

Categories