I have dropdown list of items and a popup (used colorbox for opening popup) with a list of checkboxes. The popup is shown on click of '+Add/Edit'. Both the dropdown items and the checkboxes are generated in PHP from a complaint.csv file.
complaint.csv file
1,complaint type 1
2,complaint type 2
3,complaint type 3
etc...
PHP code
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Chief Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<select name="Language.PrimarySpoken" ng-hide="showAddAnswer"
ng-model="question.response.value"
ng-options="a.text as a.getText() for a in question.answers.items"
id="Language.PrimarySpoken" ng-value="a.text" class="input-wide"
ng-class="{error:hasError()}">
<option class="hidden" disabled="disabled" value=""></option>
<?php
$file_handle = fopen("../complaint.csv", "r");
while (!feof($file_handle)) {
$lines_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach ( $lines_of_text as $line_of_text):
?>
<option value="<?php print $line_of_text[1]; ?>">
<?php print $line_of_text[1]; ?></option>
<?php endforeach; ?>
</select>
<br/> <br/>
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Additional Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<div class="form-row added ng-binding" ng-bind-html="question.getText()" id="text" ></div>
<div class="form-row addlink ng-binding"
ng-bind-html="question.getText()">
<em><a class='inline' href="#inline_content">+ Add/Edit</a></em>
</div>
<div style='display:none'>
<div id='inline_content' style='padding:25px; background:#fff; font-size: 17px;'>
<form action="" id="popup_form">
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('../complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[1].'" id="checkbox'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
?>
<br/>
<input type="submit" name="submit" id="update"
class="button button-orange"
style="width: 90px; margin-top: 450px; margin-left:-1062px;"
value="Update">
<input type="submit" name="cancel" id="cancel"
class="button button-orange"
style="width: 90px; background-color:#36606e;"
value="Cancel">
</form>
</div>
</div>
Question:
If a Main complaint item is select then that same complaint does not appear in Additional Complaint list (i.e. if 'complaint type 1' is selected for Main complaint, 'complaint type 1' does not display on Additional Complaint list)
How should I get that using one complaint.csv file like checking for the selected item, and avoid it when displaying the list e.g on select 'complaint type 1', the data from complaint.csv file will be display on popup checkbox list except 'complaint type 1' which is selected?
There is empty space generating if we remove the element. I don't want the empty space of removed item in checkbox list. Empty space means if 'complaint type 2' is removed then there empty space creates between 'complaint type 1' and 'complaint type 3'.
Is there any way to have AJAX for this situation like when the item is selected AJAX will call and it will remove the item from the checkbox list which is selected and then load the new items list except the selected one. (right now both list are loading at a same time on page load insted of that using AJAX the dropdown list should load on page load and checkbox list on click '+Add/Edit' button avoiding selected item.) Thus might be the empty space will not be there.
How this should be done using AJAX?
OR
Can anyone please suggest any solution with PHP or JS to get both requirements?
In your code, make sure the select dropdown value is $line_of_text[0] e.g. 1, 2, 3 etc.
Now add onChange="hideSpaceAndComplain(this.value)" on the select element.
Copy the following javascript function as is
function hideSpaceAndComplain(id){
//Hide selected one
$("#popup_form").find('label').show();
//Hide selected one
$('input[value=' + id + ']').parents('label').hide();
//Now rearrange all the visible label in columns
var visibleLabels = $("#popup_form").find('label:visible');
visibleLabels.each(function(i,v){
var column = Math.floor(i/4); // 4 being the number of column
$(this).appendTo($("#popup_form").find('.column:eq('+column+')'));
});
}
This is doing both hiding the element which is selected and then re arranging the labels in column to remove one extra space.
Since the logic you describe depends on what the user does in the browser, what you functionality does must be done in the browser, that means in Javascript.
According to the tags of the question you are using JQuery, so here are some pointers on how to do it with JQuery. First you have to attach an event handler to the dropdown to know when the user changes its value:
$('select').on('change', function() {
//Put here what to do when the value of the dropdown changes.
}
In that function, you want to do two things:
Un-hide the complaint that you may have hidden previously
Hide the main complaint
To do so, write something like this in the event handler:
//Un-hide everything
$('label').show();
//Hide selected one
$('input[value=' + $(this).val() + ']').parent().hide();
You can see a working example in this JSFiddle.
Hope this helps.
Note that I see in your code that you uses Angular, so you may want to use this instead. But I am not sure why you generate the select options both with Angular and PHP, so I am assuming this is some copy-pasted code that you are not using.
Related
I have a dropdown that uses JQuery/Javascript within my php/html program.
This works fine if I hard code the name of the program that runs the SQL to load data into the dropdown list.
I would like this code to be re-usable rather than duplicate it for each dropdown list (I want 2 in the current instance) so I would like to know how to pass different program names as each dropdown list accesses different files. Example: ClubID dropdown requires data from clubs using clubsSearch.php but MemberTypeID requires data from memtyp using memtypSearch.php.
Here is the Javascript including my latest effort to pass the program name as a variable:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("click input", function()
{
/* Get input value on change */
var srchName = <?php echo $SearchName?>;
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get(srchName, {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
If I use
$.get("clubsSearch.php", {term: inputVal}).done(function(data){
it works fine.
The relevant section of the form is:
<div class="col-6 col-md-4">
<div class="form-group <?php echo (!empty($ClubIDer)) ? 'has-error' : ''; ?>">
<label>Club ID:</label>
<div class="search-box">
<input type="hidden" name="clubID" value="<?php $SearchName = "\"clubsSearch.php\"";?
>" >
<input type="text" name="ClubID" autocomplete="off" class="form-control"
value="<?php echo $ClubID; ?>" >
<?php echo $SearchName?>
<div class="result">
</div>
<span class="help-block"><?php echo $ClubIDer;?></span>
</div>
</div>
</div>
The **$SearchName** displays as "clubsSearch.php" but in Chrome's developer tools I can see the javascript has not recognised the variable var srchName = ; x and no dropdown list appears.
Can anyone tell me how to present the search name to the javascript as I am completely unfamiliar with it. Any assistance would be appreciated.
Pass the program name in the data- attr like
<select name="WHATEVER" id="WHATEVER" data-program="YOUR_PROGRAM_NAME">
in JS get it like
var srchName = $(this).attr("data-program");
Resolved: In the html
<input id="ClubID" data-pgm="\"clubsSearch.php\"">
and in the Javascript
var srchName =input.dataset.pgm
I'm trying to prep forms with multiple (dynamic) inputs to insert correctly via ajax.
Currently, using my php loop, I have 4 div/forms. Each form has a starting input, and upon clicking the moreItems_add button, it dynamically adds another input, up to 10 per form/div.
This works fine. But I added a variable and console.log to log the value of my hidden input though, which should be getting an ID (<?php echo $ticker['ticker'] ?>) for each form, but it's currently only logging '1'. So when I clicked the button in the first form it looked right, but when I click the others, it's still 1. I think this is because I don't have a unique ID on the hidden input?
How can I change the way I'm keeping track of the hidden input so that I can make an ajax call that will only make an insert on the inputs of the given form WITH the correct ticker ID?
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
To generate a unique id attribute you should append your ticker value from php to... the id attribute. Or if not the ticker value, at least something that makes it unique. But you don't really need to.
Since all your elements are wrapped in a form tag and are at the same level, you can find to which ticker corresponds the clicked button by finding the hidden input among its siblings:
var tickerID = $(this).siblings('input[name="tickerID"]').val();
I have a CMS that I've built allowing users to create a 'Page' made up of different panels each with their own content. I've made this work so that a user can create a page with one panel and one textarea of content but I still can't figure out how to do this for multiple panels/content.
Currently, if the page load gets the value of '1' from the URL value, it loads html templates with a fullwidth div and halfwidth div. I'm trying to set the panel type of each with hidden input types and they each have their own tinymce text area.
<?php if($value == 1){?>
<form method="post">
<div class="col-lg-12 fullWidth" id="full">
<input type="hidden" name="fullWidth" value="">
<div class="fullContent" style="background-color: white; height: 100%;">
<form id="form-data3" method="post">
<textarea class="original" id="mytextarea3" name="fullText">Some Text Here</textarea>
<input type="submit" value="Save Content">
</form>
</div>
</div>
<div class="col-lg-12 halfWidth" id="half">
<input type="hidden" name="halfWidth" value="">
<div class="halfContent" style="background-color: white; height: 100%;">
<form id="form-data4" method="post">
<textarea class="original" id="mytextarea4" name="halfText">Some Text There</textarea>
<input type="submit" value="Save Content">
</form>
</div>
</div>
</form>
<?php } ?>
Once this is done and they go to save page, there is another form that lets them set the title of the page and it also gets the page type ($value from above)
<form action="addPage.php" method="post">
<input type="hidden" name="pageType" value="<?php echo $value;?>">//This comes from the url value
<input class="form-control" id="addTitle" name="addTitle">
<input type="submit" name="Save Page">
The problem is, when I now call my addPage.php script to insert the records, I don't know how to pass the values correctly so that I add one page record (the $value for page_type_id and the Title) but then insert 2 content and panel records for the text areas.
Here's my expected insert in the case of the above code:
pages
ID | Title | page_type_id
1 | TitleNew | 1 /*this comes from $value*/
content
ID | Content
1 | Some Text Here
2 | Some Text There
panels
ID | panel_type_ID | page_id | content_id
1 | 1 | 1 | 1
2 | 2 | 1 | 2
This works for one insert in all 3 tables but if I can set multiple panel types to each div, how can I modify this to still insert the one page record but successfully account for multiple panel and content?
Here's the add page script
//Insert Page
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$addpage = "
INSERT INTO pages (title, page_type_id)
VALUES ('$title','$page_type');
";
$mysqlConn->query($addpage)
$page_id = $mysqlConn->insert_id;
//Insert Content
$content = $_POST['page_content'];
$addContent = "
INSERT INTO content(content)
VALUES('$content');
";
$mysqlConn->query($addContent);
$cont_id = $mysqlConn->insert_id;
//Insert panel(s)
$panelID = $_POST['panelType'];
$addPanel = "
INSERT INTO panels(panel_type_id, page_id, cont_id)
VALUES ('$panelID', '$page_id', '$cont_id');
";
$mysqlConn->query($addPanel);
You're manage it wrong, it should be:
pages
ID | Title | page_type_id
1 | TitleNew | 1 /*this comes from $value*/
content
ID | Content
1 | Some Text Here
2 | Some Text There
panels
ID | panel_type_ID | page_id | content_id
1 | 1,2 | 1 | 1,2
I can't find panelType in your form but, You should detect the panels Ids which user has chosen and then send it to php, Example:
if user choose the panel (1) and the panel (2) your script should wrote it here:
<input type="hidden" value="1,2">
We separate the panels Ids with a comma because we will need it when we get the data from the database.
How to get the panels IDs:
After we get the data from database it will be like 1,2 and this won't work for you so how to get them in array?
It's so simple just do this:
<?php
$string = "1,2";
$get = explode(',', $string ); // explode with ,
?>
Now, You have your array which will look like this:
Array ( [0] => 1 [1] => 2 )
how to use it?
You can use a loop:
<?php
$string = "1,2";
$get = explode(',', $string ); // explode with and
$count = count($get);
for ($i=0; $i < $count; $i++) {
$PaN = $get[$i];
/*Some code....*/
}
?>
I hope i understand you.
I guess your problem is handling multiple data collection. use [] in your element names to collect more than one data of the same collection.
<textarea class="original" id="mytextarea3" name="fullText[]">Some Text Here</textarea>
and while saving you get an array from fullText . Loop through that and save it.
if you have multiple documents in the same form. use the key in the first loop to access the respective data from the other elements array.
Hope it helps!!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
There is a sewing management app am working on and on the order page, someone can have multiple orders, but all orders are to be invoiced using one reference code. First page, I collected basic details such as pricing, but on next page, each individual order has to be entered in more detail, a sample picture of the material, instructions and style code if any.
So I've been able to successfully create the page where the data entry person can add multiple details and even select whether there's a style or not, but am stuck in the database submission.
Remember, every other pages am working with, like staff management and others are working just fine, so this error of not submitting to the database is not relative to an external page included or any other thing except probably how the arrays are handled. Below is a breakdown of the code;
JavaScript:
<script>
function showfield(name,event){
if(name=='iHaveStyle') {
$(event).next('#div1').html('<label>Enter Style Code</label><br /> <input type="text" name="style[]" />');
} else{
$(event).next('#div1').html('');
}
}
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".form-group"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div style="margin-top:20px; border-top:1px solid #333333;"><label>Upload Sample Material</label><br /><input type="file" name="sample_material[]" style="width:200px; height: 40px;" /><br/><br/><label>Customer's Requirement</label><br /><textarea name="cust_requirement[]" style="width:200px; height: 150px;" /></textarea><br/><br/><label>Do you have a style</label><br /><select name="sketch_code" id="sketch_code" onchange="showfield(this.options[this.selectedIndex].value,this)"><option value="">I don't have a style code</option><option value="iHaveStyle">I have a style code</option></select><div id="div1"></div><br />Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
HTML:
<form action="orderadd1.php?id=<?php echo "".$order_id; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<button class="add_field_button">Add another sub-order</button>
<div style="margin-top:20px;">
<label>Upload Sample Material</label><br />
<input type="file" name="sample_material[]" style="width:200px; height: 40px;" /><br/><br/>
<label>Customer's Requirement</label><br />
<textarea name="cust_requirement[]" style="width:200px; height: 150px;" /> </textarea><br/><br/>
<label>Do you have a style</label><br />
<select name="sketch_code" id="sketch_code" onchange="showfield(this.options[this.selectedIndex].value,this)">
<option value="">I don't have a style code</option>
<option value="iHaveStyle">I have a style code</option>
</select>
<div id="div1"></div>
</div>
</div>
<input type="submit" class="btn btn-lg btn-color btn-block" value="Continue Order" name="submit_val">
</form>
PHP Code:
<?php
$order_id = $_REQUEST['id'];
if (isset($_POST['submit_val'])) {
if(is_array($_POST['cust_requirement']))
{
for($i=0; $i < count($_POST['cust_requirement']); $i++ ) {
$cust_requirement = mysql_real_escape_string($_POST['cust_requirement'][$i]);
$style = mysql_real_escape_string($_POST['style'][$i]);
$folder = "sample_material/";
$extention = strrchr($_FILES['sample_material']['name'], ".");
$new_name = $order_id."-".$i++;
$sample_material = $new_name.'.jpg';
$uploaddir = $folder . $sample_material;
move_uploaded_file($_FILES['submit_material']['tmp_name'], $uploaddir);
$data_submit = $pdo->query("INSERT INTO `order_desc` (order_id, sample_photo_url, cust_requirements, style_code) VALUES ('".$order_id."', '".$uploaddir."', '".$cust_req."', '".$style."')");
}}
}
?>
The error it is showing is:
Warning: strip_tags() expects parameter 1 to be string, array given in C:\xampp\htdocs\tms\header.php on line 2
I checked the header.php and this is exactly what I have there:
<?php
$_POST = array_map('strip_tags', $_POST);
?>
I used this header on all my pages and they are fine.
array_map function applies strip_tags() to every element of an array - but the most possible reason of this is that your $POST looks like this ['test1',['test2','test3]], $POST[1] == ['test2','test3] is an array and strip tags cannot be applied. You can do it using loop and checking if item is not an array to be stripped, or use recursion to go all over you $POST array
Your POST superglobal contains arrays that is why you get a warning with array_map. Try replacing it with array_walk_recursive http://php.net/manual/en/function.array-walk-recursive.php
enter image description hereI have a modal which opens a form, the form has a line with 4 fields
Select input field
Text
Select input field (filtered by first select)
Select input field (filtered by second select)
I want to clone this line with empty values. I was able to clone it, but in the cloned line, whenever I try to select a new value, it expands the first field in first line only.
Modal Code
<div id="add-ins-company">
<div class="form-group">
<div class="col-md-4">
<div class="input-group col-md-12">
<select id="mq_ins_company" name="mq_ins_company[]" class="modal-select-chosen" data-placeholder="Insurance Company" onchange="getpolicyclass(this.value);" required>
<option value=""></option>
<?php
$company_id = mysqli_real_escape_string($GLOBALS['con'], $_SESSION['company_id']);
$sql = "select * from insurance_companies where ins_comp_company = $company_id";
$data = FetchMultipleData($sql);
for($i=0;$i<count($data);$i++) {
?>
<option value="<?php echo $data[$i]['ins_comp_id']; ?>"><?php echo $data[$i]['ins_comp_name'];?></option>
<?php } ?>
</select>
</div>
</div>
<div class="col-md-2">
<input type="email" id="mq_fees" name="mq_fees[]" class="form-control" placeholder="Fees" required="required">
</div>
<div class="col-md-3">
<div id="mq_class"></div>
</div>
<div class="col-md-3">
<div id="mq_size"></div>
</div>
</div>
</div>
JavaScript
function addcompanyrow() {
var row = $('#add-ins-company').clone(true);
$(row).insertAfter("#add-ins-company");
}
Any Suggestion on the following:
Clear all input values
Remove the chosen class and reapply it on the cloned line
In general:
If the list is dynamic you should have some workaround, such as:
Consider move the php generations to external ajax calls hosted in js functions.
Use a binding of option of 3rd-parties like JQuery/KnockoutJS.
Anyway, if i understand your specific question well:
Clearing input values is possible like this:
$('<the_input_selector>').removeAttr('value');
OR
$('<the_input_selector>').val('');
For clearing "select" elem you can also use:
$('<the_select_selector>').val('');
if the empty option exists. OR you can set it to first one:
$('<the_select_selector>').prop('selectedIndex',0);
Removing class is possible too:
$('<the_select_selector>').removeClass('modal-select-chosen');
You can then add any other class:
$('<the_select_selector>').addClass('<any_other_class>');
Good luck!