How would I go about creating the following:
I am looking to create a dropdown menu full of form input types but when one is selected I would like it to create the respective html for the input and save it to the database. I will be using codeigniter.
Example:
If I select Text Area from the dropdown menu it will then create <textarea></textarea> so then I could escape it and save it to the database.
I have come up with the following code so far
if (isset($_REQUEST['general_options']))
{
$optionName = $_REQUEST['general_options'];
$optionValue = strtolower(str_replace(" ", "", $_REQUEST['general_options']));
//$this->load->view( $page, $data, FALSE);
echo form_label($optionName, $optionValue);
echo form_input($optionValue, '', '');
}`
`
Unless your intent on reloading the page every time you make a select choice, your best bet is to incorporate something like jQuery which is a javascript library.
Then with that you can do something like
<select id="mySelect">
<option value="none" selected="selected">---Select---</option>
<option value="textarea">Textarea</option>
</select>
<div id="appendElem"></div>
<script type="text/javascript">
$('#mySelect').change(function()
{
if($(this+' option:selected').val() == "textarea")
{
$('#appendElem').html('<textarea>Some Text...</textarea>');
}
})
</script>
A note worth mentioning is just cause Codeigniter has a form helper class, and makes it sound through its docs that its the only way to build a form on your page. Standard HTML forms work just as well in your views.
Related
I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.
Question: I have two drop-down boxes. Using jQuery, I want to populate second drop-down box on selection of the first drop-down box (help with my existing code). I have marked the area I need help with in the jQuery code below, plus an explanation of what I want to achieve in "Code help".
I realise this is a VERY frequently requested item on SO and I have seen many comments that this can be done in simple JS, but since there are already other jQuery elements in use on the page (not coded by me) and for simplicity, I want to use JQ.
I am completely new to any jQuery code, I have researched many examples, however I am getting lost in the logic since I am not familiar with JS or JQ coding conventions, so keeping things simple is important so I can understand what is happening within the code (I am not just looking for help to get my code working, but also so I can learn and understand what is happening).
I found pretty much exactly the operation I want to achieve (except for one important point explained in "Code help" below) by following a tutorial here: http://jqueryfordesigners.com/populate-select-boxes/. A sample page showing the operation is here: http://jqueryfordesigners.com/demo/select-boxes.html
Code help: In the tutorial, the second dropdown is populated from the content of static html files in: $article.load('select-boxes-' + categoryName + '.html');
I need the second dropdown to be populated from the JS variable $st_list and the PHP variable $student_block based on the selected value in the first dropdown, as shown in my code below.
Could anyone please help with how to adapt the code to make that happen?
Thank you
My code:
For simplicity, the first dropdown is static with simple integer values, but will be populated from the DB in $test_seq in the working code with integer values same as the example code below (if that matters). Additionally, in a separate PHP process (later) the $test_seq, $student_id and other new variables will be used to send back data to the DB (included for reference only, though not relevant for this request).
select-boxes.php
$sql = "SELECT * FROM TBL_NAME";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$test_seq = $row['SEQ'];
$student_id = $row['st_num'];
$student_name = $row['st_name'];
$student_block .= '<OPTION value="'.$student_id.'">'.$student_id.' - '.$student_name.'</OPTION>';
}
Form:
<form action="select-boxes.php">
<label for="test_day">Test day:</label>
<select name="test_day" id="test_day">
<option selected value=""> </option>
<option value="1">Day 1</option>
<option value="2">Day 2</option>
<option value="3">Day 3</option>
</select>
<input type="submit" id="next" value="next »" />
</form>
jQuery:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
var $test_day = $('#test_day'),
$st_list = null;
$test_day.change(function () {
var test_dayVal = $test_day.val();
if ($st_list == null) {
$st_list = $('<select name="st_name" id="st_name"><?php echo $student_block; ?></select>').appendTo('form');
$next.remove();
$('form').append('<input type="submit" value="process »" />');
}
$st_list.load('#test_dayVal'); //<--I think this is where I need help.. What do I do here?
});
var $next = $('#next');
$next[0].setAttribute('type', 'button');
});
</script>
Right now, I have variables that default to the current d/m/y, which is then popped into a mySQL query that displays all data from a table WHERE date='$dday' AND month='$dmonth' AND year='$dyear'.
$ddate = date("d");
$dmonth = date("m");
$dyear = date("Y");
Instead, I'd like to have a select box that will change the variables based on the option selected. So the default option for the Day select will be the current date, but if I change that to day 12 for example, I want the variable to change when the select option changes, and then re-query the database automatically. I'm assuming this would be done with AJAX.
Is what I'm talking about even possible? If the automation of the query adds a big layer of complexity, I'd be fine with just changing the variable and updating based on the press of a submit button.
I promise to take a break from asking questions and start answering some, if questions below my simple level are even asked.
Yes, this is possible. jQuery even makes it easy.
Create your <select> element and give it an ID so it can be used in jQuery.
Add an event listener in jQuery that is fired when the <select> changes, like $("#date").change().
In the event handler for the change event, get the current value of the <select>, and then use jQuery's AJAX $.post() function to send that data to a PHP file.
In that PHP file, sanitize the data to prevent MySQL Injections, and then query the database for the new data.
Use PHP's echo function to send back the data.
In the jQuery $.post() callback function (third parameter), receive the echoed data and put it into a variable.
Use jQuery to update your HTML with the data.
Both of the solutions you suggest would work. You can send the values from the select box to a php script using AJAX, or you could just submit the form and access them that way via $_POST or $_GET depending on your form method.
Heres an example, ill leave you to do the query:
<?php
//Some pseudo data kinda as your receive it from your query
$datafromSql = array(
array('id'=>1,'date'=>1,'month'=>1,'year'=>2012,'theData'=>'This is some data when the user select 1/1/2012'),
array('id'=>2,'date'=>2,'month'=>2,'year'=>2012,'theData'=>'This is some data when the user select 2/2/2012'),
array('id'=>3,'date'=>3,'month'=>3,'year'=>2012,'theData'=>'This is some data when the user select 3/3/2012'),
);
//Super simple API to access the data
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
header('Content-Type: text/html');
//pseudo code, really you would just format your query result
$return=array();
foreach($datafromSql as $row){
//Select all from array which match select choice
if($row['date']==$_POST['day'] || $row['month']==$_POST['month'] || $row['year']==$_POST['year']){
$return[]=$row['theData'].'<br />';
}
}
//output, with a fancy horizontal rule
echo implode('<hr />',$return);
die;
}?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
$.post('./<?php echo basename(__FILE__)?>',
{
day: $("#day").val(),
month: $("#month").val(),
year: $("#year").val()
},
function(data) {
$('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
});
}
$(document).ready(function(){
update();
});
</script>
</head>
<body>
<form id="dateform" >
<p>Select Date:
<select size="1" name="day" id="day" onChange="update()">
<?php foreach(range(1,31) as $i){echo '<option value="'.$i.'">'.$i.'</option>';} ?>
</select>
<select size="1" name="month" id="month" onChange="update()">
<?php foreach(range(1,12) as $i){echo '<option value="'.$i.'">'.$i.'</option>';} ?>
</select>
<select size="1" name="year" id="year" onChange="update()">
<?php foreach(range(2008,2012) as $i){echo '<option value="'.$i.'">'.$i.'</option>';} ?>
</select>
</p>
</form>
<p id='result'></p>
</body>
</html>
I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.
I am working in the confines of a CMS system, which defines certain fields which can be used to make forms for use within the application in PHP.
The list function has the signature:
function inputBasicList ($id,$value = "",$list = array(), $displayName = NULL, $displayLabel = true)
I use it thusly:
$theinput = new inputBasicList("type",$therecord["paymenttype"],array("Cash"=>"cash","Credit"=>"credit"), "Payment Type");
Likewise, there is a checkbox, which has the signature:
function inputCheckbox($id,$value = false, $displayName = NULL, $disabled = false, $displayLabel = true)
I use it thusly
$theinput = new inputCheckbox("paid", $therecord["paid"], "Paid");
What I would like to do, is if the list is set to credit instead of the default cash, to automatically set the checkbox to true/checked.
I don´t think the CMS system allows a way to do this using any built in functions, and am wary of adding any javascript.
Is such a thing possible with just PHP?
Otherwise, how complicated would the javascript have to be to do such a thing?
edit:
The generated HTML from the phpBMS forms
<p class="big"><label for="type" class="important">Payment Type</label>
<br />
<select name="type" id="type" class="important" >
<option value="cash" >Cash</option>
<option value="credit" >Credit</option>
</select>
</p>
<p class="big">
<input type="checkbox" id="paid" name="paid" value="1" class="radiochecks" />
<label id="paidLabel" for="paid" >Paid</label>
</p>
It's not possible to do such thing with PHP only, because PHP is run on your server. You need some code that is run on the client.
I believe that the first paramater $id is used as id attribute for the elements? If I'm wrong correct me. If so you can do the following using the jQuery JavaScript Library:
jQuery(function($){
$('#type').change(function(){
if ($(this).val() == "credit") {
$('#paid').attr('checked','checked');
} else {
$('#paid').removeAttr('checked');
}
});
});
UDPATE
BMS is using Mootools, the JavaScript should like like this to work in mootools:
window.addEvent('domready', function(){
$('type').addEvent('change',function(){
if($(this).get('value') == 'credit') {
$('paid').set('checked','checked');
} else {
$('paid').removeProperty('checked');
}
});
});
I would recommend using the mootools version of this snippet, but just for your interest, if you want to install jQuery, you can add the jquery.js into phpbms/common/javascript. Then you can edit phpbms/header.php to include this:
after the last $tempjsarray[] add:
$tempjsarray[] = "common/javascript/jquery.js";
then after $phpbms->showJsIncludes(); you need to include this, so jQuery works without problems besides mootools:
echo '<script type="text/javascript">jQuery.noConflict();</script>';
If this doesn't work, you should post what the html output looks like.
It should be fairly easy in the javascript . You can attach an event listener on the onchange function of the list and set the value of checkbox in that function .