I'm using codeigniter framework and I have some fields that I want to fill when I check a checkbox (it takes data from other fields).
The thing is I want to fill the dropdown list with the value of an other dropdown list.
Here's the javascript code that I use to fill the fields :
function FillinEmail(info) {
if (info.checked)
{
document.getElementById('adresse_fact').value = document.getElementById('adresse').value;
document.getElementById('npa_fact').value = document.getElementById('npa').value;
document.getElementById('nomprenom_fact').value = document.getElementById('nom').value + ' ' + document.getElementById('prenom').value;
}
else
{
document.getElementById('adresse_fact').value = '';
document.getElementById('npa_fact').value = '';
document.getElementById('nomprenom_fact').value = '';
}
}
And here is how I do my dropdown list with codeigniter :
<div class="form-group">
<label class="col-md-2 control-label" for="id_npa_localite">Localité</label>
<div class="col-md-4">
<?php echo form_dropdown('id_npa_localite', $id_localite, null,'class="form-control"')?>
</div>
</div>
The null value is where I can put a default value, and that's what I would change in the javascript method, but I don't know how to do that in that case, since the other elements are html elements, it was easy to do.
I would give that select an ID, and use innerHTML in your JS. Do it in this manner:
<select id="the_other">
<option>test1</option>
<option>test2</option>
<option>test3</option>
</select>
<input type="checkbox" onchange="FillinEmail(this)">
<div class="form-group">
<label class="col-md-2 control-label" for="id_npa_localite">Localité</label>
<div class="col-md-4">
<?php echo form_dropdown('id_npa_localite', $id_localite, null, 'id="ci_form" class="form-control"') ?>
</div>
</div>
<script>
function FillinEmail(info) {
document.getElementById('ci_form').innerHTML = document.getElementById('the_other').innerHTML;
/*
if (info.checked) {
document.getElementById('adresse_fact').value = document.getElementById('adresse').value;
document.getElementById('npa_fact').value = document.getElementById('npa').value;
document.getElementById('nomprenom_fact').value = document.getElementById('nom').value + ' ' + document.getElementById('prenom').value;
}
else {
document.getElementById('adresse_fact').value = '';
document.getElementById('npa_fact').value = '';
document.getElementById('nomprenom_fact').value = '';
}
*/
}
</script>
Related
I am created the select box to choose the option, my options have condition to hide and show the input fields. My problem is how to write if else logic to check the $category_id value to show and hide in the input div in the backend page. Hope someone can guide me how to solve it. Thanks.
Below is my coding:
Frontend page:
<div class="form-group">
<label for="cp1" class="control-label col-lg-4">Move to Sub Folder/New Category<span style="color:red;"> *</span></label>
<div class="col-lg-3">
<select class="form-control blank" id="parentid" name="parentid" title="parentid">
<option>Please Select</option>
<option value="0">New Category</option>
<?php
$sql_incharge = 'select * from filing_code_management where status=1 order by id';
$arr_incharge = db_conn_select($sql_incharge);
foreach ($arr_incharge as $rs_incharge) {
$folder_location = $rs_incharge['folder_location'];
$category_id= $rs_incharge['category_id'];
echo '<option value="' . $rs_incharge['id'] . '">' . $rs_incharge['name'] . '</option>';
}
?>
</select>
<!--<input type="text" class="form-control blank" id="parentid" name="parentid" title="parentid" onblur="capitalize(this.id, this.value);">-->
</div>
</div>
<div class="form-group" id="show_hide_fc">
<label for="cp1" class="control-label col-lg-4">Function Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_code" name="function_code" title="function_code">
</div>
</div>
<div class="form-group" id="show_hide_fn">
<label for="cp1" class="control-label col-lg-4">Function Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_name" name="function_name" title="function_name">
</div>
</div>
<div class="form-group" id="show_hide_ac">
<label for="cp1" class="control-label col-lg-4">Activity Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_code" name="activity_code" title="activity_code">
</div>
</div>
<div class="form-group" id="show_hide_an">
<label for="cp1" class="control-label col-lg-4">Activity Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_name" name="activity_name" title="activity_name">
</div>
</div>
Backend page:
<?php
$parentid = $_POST['parentid'];
$sql5 = 'select folder_location,name,category_id from filing_code_management where id='. $parentid;
$arr_sql5 = db_conn_select($sql5);
foreach ($arr_sql5 as $rs_sql5) {
$sub_category_name = $rs_sql5['name'];
$folder_location = $rs_sql5['folder_location'];
$categoryID= $rs_sql5['category_id'];
}
$show_hide_fc = $_POST['show_hide_fc'];
$show_hide_fn = $_POST['show_hide_fn'];
$show_hide_ac = $_POST['show_hide_ac'];
$show_hide_an = $_POST['show_hide_an'];
if ($category_id == '0') {
// $show_hide_fc will show
// $show_hide_fn will show
// $show_hide_ac style display = 'none';
// $show_hide_an style display = 'none';
} else if ($category_id == '1') {
// $show_hide_fc style display = 'none';
// $show_hide_fn style display = 'none';
// $show_hide_ac will show
// $show_hide_an will show
} else if ($category_id == '2') {
// $show_hide_fc will show
// $show_hide_fn will show
// $show_hide_ac will show
// $show_hide_an will show
}
?>
For example if I choose the $category_id number is 1 it will show two input div, like below the sample picture.
If I choose the $category_id number is 2 it will show 4 input div, like below the sample picture.
There are two ways of solving this, depending on the size of your dataset. If there are not too many records with a $parentid (from the backend code, also please read up on SQL injection, you are inserting user data into a SQL query), you can just check the options ahead of submitting (when the form page is requested), and show or hide the items with JS depending on the option selected. This has the advantage of having no additional requests.
If you have a lot of entries in the filing_code_managment table then you should not check them all in advance, as this would be very resource intensive, and 90% of the work done will never be seen by anyone. In this case you can use AJAX to check with the server, and check what fields will be shown or hidden depending on the result. This solution has the advantage of checking only the options that are used, but it introduces latency, as the request needs to be completed before the user can fill the next fields.
Update with example for first option
Example for first option in your front end code:
<div class="form-group">
<label for="cp1" class="control-label col-lg-4">Move to Sub Folder/New Category<span
style="color:red;"> *</span></label>
<div class="col-lg-3">
<select class="form-control blank" id="parentid" name="parentid" title="parentid">
<option >Please Select</option>
<option value="0">New Category</option>
<?php
$sql_incharge = 'SELECT * FROM filing_code_management WHERE status = 1 ORDER BY id';
$arr_incharge = db_conn_select($sql_incharge);
// Test array, I don't have your database
// $arr_incharge = [
// ['category_id' => '0', 'id' => '0', 'name' => 'Nummer 0'],
// ['category_id' => '1', 'id' => '1', 'name' => 'Nummer 1'],
// ['category_id' => '2', 'id' => '2', 'name' => 'Nummer 2']
// ];
$show = [];
foreach ($arr_incharge as $rs_incharge) {
$folder_location = $rs_incharge['folder_location'];
$category_id = $rs_incharge['category_id'];
echo '<option value="' . $rs_incharge['id'] . '">' . $rs_incharge['name'] . '</option>';
// Added
switch ($category_id) {
case '0':
$fc = true;
$fn = true;
$ac = false;
$an = false;
break;
case '1':
$fc = false;
$fn = false;
$ac = true;
$an = true;
break;
case '2':
$fc = true;
$fn = true;
$ac = true;
$an = true;
break;
}
// Save in one big array, to use in JS later
$show[$rs_incharge['id']]['show_fc'] = $fc;
$show[$rs_incharge['id']]['show_fn'] = $fn;
$show[$rs_incharge['id']]['show_ac'] = $ac;
$show[$rs_incharge['id']]['show_an'] = $an;
}
?>
</select>
<!--<input type="text" class="form-control blank" id="parentid" name="parentid" title="parentid" onblur="capitalize(this.id, this.value);">-->
</div>
</div>
<div class="form-group" id="show_hide_fc">
<label for="function_code" class="control-label col-lg-4">Function Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_code" name="function_code" title="function_code">
</div>
</div>
<div class="form-group" id="show_hide_fn">
<label for="function_name" class="control-label col-lg-4">Function Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="function_name" name="function_name" title="function_name">
</div>
</div>
<div class="form-group" id="show_hide_ac">
<label for="activity_code" class="control-label col-lg-4">Activity Code:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_code" name="activity_code" title="activity_code">
</div>
</div>
<div class="form-group" id="show_hide_an">
<label for="activity_name" class="control-label col-lg-4">Activity Name:</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="activity_name" name="activity_name" title="activity_name">
</div>
</div>
<script>
// Added, add this after the inputs
const fc = document.getElementById('function_code');
const fn = document.getElementById('function_name');
const ac = document.getElementById('activity_code');
const an = document.getElementById('activity_name');
const select = document.getElementById('parentid');
const show = JSON.parse('<?= json_encode($show) ?>');
updateVisibility();
select.addEventListener('change', function () {
updateVisibility();
});
function updateVisibility() {
const currentOption = show[select.options[select.selectedIndex].value];
if (typeof currentOption !== 'undefined' && currentOption !== null) {
if (currentOption.show_fc) {
fc.style.display = '';
} else {
fc.style.display = 'none';
}
if (currentOption.show_fn) {
fn.style.display = '';
} else {
fn.style.display = 'none';
}
if (currentOption.show_ac) {
ac.style.display = '';
} else {
ac.style.display = 'none';
}
if (currentOption.show_an) {
an.style.display = '';
} else {
an.style.display = 'none';
}
} else {
// Hide everything when no known option is selected
fc.style.display = 'none';
fn.style.display = 'none';
ac.style.display = 'none';
an.style.display = 'none';
}
}
</script>
This is my first post here, so please no penalty points for me if there is anything unclear with my question. If so, I will edit or add necessary info.
I have an assignment for creating javascript validation method for html input and select, that validates both fields and removes error message after entering details or selecting drop-down option. And, I am having a problem with the second part which I do not seem to be able to find a solution for, and precisely:
1) error message does not disappear when an option from select is chosen (it works for input)
I was trying few things but obviously I do not see my mistakes and I really hope someone could point me in the right direction here.
And here is the code for validation:
var validations = {
req: function(data){
return (data != '' && data.length > 0);
}
}
$(document).ready(function(){
function addError(fname, error){
$('[name=' + fname + ']').after('<span class="validationError"> ' + error + '</span>');
}
function removeError(fname){
$('[name=' + fname + ']').parent('div').find('.validationError').remove();
}
var map = {};
for(var x in validationRules){
var fname = validationRules[x][0];
if(typeof fname == 'undefined') continue;
if(typeof map[fname] == 'undefined') map[fname] = [];
map[fname].push({
'method' : validationRules[x][1],
'error' : validationRules[x][2]
});
};
for(var x in map){
$('[name=' + x + ']').on('keyup', function(){
var fname = $(this).attr('name'),
validators = map[fname];
removeError(fname);
for(var y in validators){
if(typeof validators[y] == 'function') continue;
if(!validations[validators[y].method]($(this).val())) addError(fname, validators[y].error);
}
});
}
$('#send, #insert').on('click', function(ev){
var isOk = true;
$('.validationError').remove();
for(var x in map){
for(var y in map[x]){
if(typeof map[x][y] == 'function' || !$('[name=' + x + ']').is(':visible')) continue;
if(!validations[map[x][y].method]($('[name=' + x + ']').val())){
addError(x, map[x][y].error);
isOk = false;
}
}
};
return isOk;
});
});
and html form:
<form action="form-handler.php" method="post" class="form-contacts">
<div class="row col-sm-12 form-break1">
<div class="col-sm-3 col-lg-3 form-label">Your name</p></div>
<div class="col-sm-6 col-lg-6">
<input class="textInput" type="text" name="Name" value="" placeholder="Name & Surname" maxlength="50" />
</div>
</div>
<div class="row col-sm-12 form-break1">
<div class="col-sm-3 col-lg-3 form-label">Vehicle Make </div>
<div class="col-sm-3 col-lg-3">
<select name="Vehicle">
<option value=""></option>
<option value="Vehicle 1">Vehicle 1</option>
<option value="Vehicle 2">Vehicle 2</option>
</select>
</div>
</div>
<div class="wrapper sendButtons">
<div class="col-sm-3 col-lg-3"><input id="send" type="submit" value="Send Request"></div>
</div>
</form>
And finally, just before closing body tag, validation rules
<script>
var validationRules = [
// section 1
["Name","req","Please enter your full name & surname"],
["Vehicle","req","Select Vehicle"]
]
</script>
Im trying to display currencies in a dropdown list by setting it's html property of all the items(currencies) I retrieve.
Here is my code:
var currencyDropdownData = "";
currencyDropdownData.length = 0;
if (confirmationData != null)
{
currencyDropdownData = confirmationData.Currencies;
console.log(currencyDropdownData)
var BudgetSelectData = "";
//BudgetSelectData += '<option selected value="-1">Please Select</option>'
for (var currency = 0; currency < currencyDropdownData.length; currency++) {
console.log(currencyDropdownData[currency].Name);
BudgetSelectData += '<option value="' + currencyDropdownData[currency].Id + '">' + currencyDropdownData[currency].CurrencyText + currencyDropdownData[currency].Name + '</option>'
}
console.log(BudgetSelectData);
$('#budgetCurrency').html(BudgetSelectData);
}
Here is the html:
<div class="row rowSpace">
<div class="col-md-12">
<div class="col-md-3">
<label>Budget (Optional)</label>
</div>
<div class="col-md-6">
<div class="col-md-10 col-sm-10 col-xs-11 noPadding">
<select validateme="true" class="form-control fullWidth" id="budgetCurrency" placeholder="€ (Euro)" data-validation="length alphanumeric" data-validation-length="min1">
</select>
</div>
<div class="col-md-2 col-sm-2 col-xs-1 noPadding" linkedval="budgetCurrency"></div>
</div>
</div>
In the console I can see the html is being created correctly and each of the currencies are coming back, however nothing is being displayed in the dropdown list
maybe this is what you looking for
for (var currency = 0; currency < currencyDropdownData.length; currency++) {
console.log(currencyDropdownData[currency].Name);
var option = $("option").attr("value", currencyDropdownData[currency].Id)
.val(currencyDropdownData[currency].CurrencyText + currencyDropdownData[currency].Name);
$('#budgetCurrency').append(option);
}
I have a form where I need such facility where user input some data in textfield and hits enter that time using jquery it should create new controls like new textfield, dropdown menu, textfield. and it works also, but it has a bug like when user input another data and hits enter that time value of previous controls, dropdown and textfield changes to its default.
Here is my code:
<script type="text/javascript">
function addMbo(value){
var div = document.getElementById('mboTable');
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
event.preventDefault();
var divName = document.getElementById('mboName');
var divState = document.getElementById('mboState');
var divProgress = document.getElementById('mboProgress');
divName.innerHTML = divName.innerHTML + "<input class=form-control type=text name=mboName value='" + value + "' id=mboNamw/>"
divState.innerHTML = divState.innerHTML + "<select class=form-control > <option value=1>In Progress </option><option <value=2>Completed</option><option value=3>Cancled</option></select>"
divProgress.innerHTML = divProgress.innerHTML + "<input class=form-control type=text name=progress id=progress />"
document.getElementById('mboNameInput').value = null;
}
}
</script>
HTML code:
<div class="col-sm-4">
<div class="row">
<div class="col-sm-5">
<b>Objectives</b>
</div>
<div class="col-sm-4">
<b>Status</b>
</div>
<div class="col-sm-3">
<b>Compl. %</b>
</div>
</div>
<div class="row">
<div id="mboTable">
<div id="mboName" class="col-sm-5"></div>
<div id="mboState" class="col-sm-4"></div>
<div id="mboProgress" class="col-sm-3"></div>
</div>
</div>
<div class="row" >
<div class="col-sm-5">
<input type="text" id="mboNameInput" class="form-control " onkeydown="addMbo(this.value)" placeholder="Your MBO...">
</div>
</div>
</div>
here is jsfiddle
When you do innerHTML on any element, it will completely destroy what ever content already there inside the elment.
Rather you should appndChild as shown below,
var divName = document.getElementById('mboName');
var mboName = document.createElement("INPUT");
mboName.setAttribute("type", "text");
mboName.setAttribute("class", "form-control");
divName.appendChild(mboName );
you can do the related changes to above code and make your things work.
See below code to add select dropdown.
var divState = document.getElementById('mboState');
var selectData = [{name:"In Progress",value:"1"},{name:"Completed",value:"2"},{name:"Cancelled",value:"3"}];
var selectList = document.createElement("select");
selectList.class = "form-control";
divState.appendChild(selectList);
for (var i = 0; i < selectData.length; i++) {
var option = document.createElement("option");
option.value = selectData[i].value;
option.text = selectData[i].name;
selectList.appendChild(option);
}
I just want to start by saying thanks for your help so far. I have successfully created an ajax request to display data in a dropbox but what is happening is creating a dropbox for each item in the database. where i want it create 1 dropbox with all items in it. and then have the ability to add another dropbox..
here is my new_order.php
<div class="page_forms">
<div class="centered">
<div class="container-fluid">
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="account-wall">
<div class="account-wall-title">
Select Products on Order
</div>
<div class="form-group col-xs-12 col-sm-6 col-sm-offset-3">
Add Product
</div>
<form id="new_order_client_part_2" method="post" action="">
<div id="InputsWrapper">
<!-- This is where the dropbox will be displayed-->
<div style="clear:both"></div>
</div>
<div class="new_order_submit col-xs-12 col-sm-6 col-sm-offset-3">
<input class="form-control" name="new_order_part_2_submit" type="submit" value="Next">
</div>
<div style="clear:both"></div>
</form>
</div>
</div>
</div>
</div>
</div>
this is the product_request.php
<?php
include ("../core/init.php");
$result = mysql_query("SELECT * FROM `product`");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
echo json_encode($data);
?>
this is my main.js
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$.ajax({
url: 'ajax/product_request.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var product_id = row[0];
var product_name = row[1];
$("#InputsWrapper").append('<div class="col-xs-12"><div class="input-group"><span class="order_quantity input-group-btn"><input class="form-control" type="number" placeholder="Quantity"></span><select id="order_product" class="form-control" name="products[]"><option value="'+product_id+'">'+product_name+'</option></select><span class="input-group-btn removeclass"><button class="btn btn-danger" type="button">X</button></span></div></div><div style="clear:both"></div>');
x++;
}
}
});
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
So yeah i know the problem is in my append... it is appending the drop box for each result... I'm really stuck on how else i should write it...
thanks in advance if you can help :)
peter
PHP code is not executed client side, so when you append the dropdown, the PHP is not being executed. A suggestion would be to use AJAX. I know I'm going to get a lot of crap about this down in the comments, but I feel jQuery's AJAX is the simplest to understand. You simply pass an associative array to the AJAX function. Example:
$.ajax({
url: "script.php", //File you wish to execute
method: "GET", //Can be GET or POST
data: "thing=1&thing2=2", //Just like the GET parameters in a URL
success: function(data) {
//Do what you want, data is the returned data from the PHP script
},
});
For example, just taking a quick look at your code, for the "order_product" select you want to add, move the PHP to a different file, AJAX that, and append that as well. You could even put the append in the success function or make another AJAX call for more dependent selects.
Or, if you want to fetch all the data in one call and just add stuff dynamically(not sure if that is what you want, but it seems like it, maybe) you could use jQuery dependent selects. It isn't that difficult to write your own, but if your just looking for a drag-and-drop solution, here is the GitHub: jquery-dependent-selects. Good luck!
I don't see #AddMoreFileBox in your HTML code. Are you missing something here ?
With your problem, I have 2 way to approach.
You can copy first div with class col-xs-12 , then append into #InputsWrapper
With your sql result, you can assign it into javascript variable as
Json in current php file. Then you can add new select with Json
var data = <?php echo json_encode($sql_result);?>;
I just want to start by saying thanks for everyone help... i worked it out.
here is my new_order.php
<div class="page_forms">
<div class="centered">
<div class="container-fluid">
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="account-wall">
<div class="account-wall-title">
Select Products on Order
</div>
<div class="form-group col-xs-12 col-sm-6 col-sm-offset-3">
Add Product
</div>
<form id="new_order_client_part_2" method="post" action="">
<div id="InputsWrapper">
<!-- This is where the dropbox will be displayed-->
<div style="clear:both"></div>
</div>
<div class="new_order_submit col-xs-12 col-sm-6 col-sm-offset-3">
<input class="form-control" name="new_order_part_2_submit" type="submit" value="Next">
</div>
<div style="clear:both"></div>
</form>
</div>
</div>
</div>
</div>
</div>
this is the product_request.php
<?php
include ("../core/init.php");
$result = mysql_query("SELECT * FROM `product`");
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
echo json_encode($data);
?>
this is my main.js
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#AddMoreFileBox"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=0; //to keep track of text box added
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$.ajax({
url: 'ajax/product_request.php', data: "", dataType: 'json', success: function(rows)
{
var product_id = rows[0];
var product_name = rows[1];
var options = $("#order_product_"+ FieldCount +"");
$.each(rows, function() {
options.append($("<option />").val(this.product_id).text(this.product_name));
});
}
});
$("#InputsWrapper").append('<div class="col-xs-12"><div class="input-group"><span class="order_quantity input-group-btn"><input class="form-control" type="number" placeholder="Quantity"></span><select id="order_product_'+ FieldCount +'" class="product_on_order form-control" name="products[]"></select><span class="input-group-btn removeclass"><button class="btn btn-danger" type="button">X</button></span></div></div><div style="clear:both"></div>');
x++;
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
};
return false;
});
});
ALL FIXED AND WORKING CHEERS!!!
peter