How to hide and show the input box with the condition? - javascript

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>

Related

PHP Post saving data from 2 seperate forms (one showing on click) getting data from one form and adding it to the second one

I am building my first aplication with backend and I am stuck. I have a calculator that takes user input and calculates on click. That button that calls a calc function is also a submit button but I cannot put it in the form because it reloads the page on click. What I want it to do is to show a modal with a contact form on click, which it does. After that when the user fills out the form I want to build a email with both the data that was inputed in the calculator and the data from contact form. However I do not know how to save the data inputed into the calculator, as of now I store it in a object iwth arrays. Is there a way to get that data and connect it to the data from contact form so when the user clicks contact me it builds an email with both data inputed in calculator and with data from contact form? I would very much appreciate any help from You.
Here is my code so far (please note that for now I was only using PHP to see what data is being saved)
<?php
// $message_sent = false;
echo "<pre>";
print_r($_POST);
// if(isset($_POST["name"], $_POST["email"]) && $_POST["email"] !="" ) {
// if(isset($_POST["btnSend"])){
// if(filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
//Submit Form; Email Vars
// $userName = $_POST['name'];
// $userEmail = $_POST['email'];
// $userPay = $_POST['payment'];
// $truckNum = $_POST["truckNum"];
// $truckKm = $_POST["truckKm"];
// $euro = $_POST["euro"];
// $weight = $_POST["weight"];
// // Email main
// $to = "mail#gmail.com";
// $subject = "New contact - " .$userName;
// $body = "<html>
// <body style=\"margin:auto; padding:10px; text-align:center; background-color:#ededed;\">
// <div style=\" padding:10px; background-color:#fff; margin:auto; text-align:center; \">
// <h2>Nowy Użytkownik</h2>
// <h4>Mail:</h4><p>'.$userMail.'</p>;
// <h4>Imię:</h4><p>'.$userName.'</p>;
// <h4>Metoda płatności:</h4><p>'.$userPay.'</p>;
// <h4>Ilość tirów:</h4><p>'.$truckNum.'</p>;
// <h4>Ilość kilometrów:</h4><p>'.$truckKm.'</p>;
// <h4>Klasa wagi:</h4><p>'.$truckNum.'</p>;
// <h4>Klasa spalania:</h4><p>'.$truckNum.'</p>
// <h2>Legenda</h2>
// <ul>
// <li>A: 7,5t do 12t </li>
// <li>B: 12 do 18t</li>
// <li>C: > 18t z 3 osi</li>
// <li>D: > 18t z 4 lub więcej osi</li>
// </ul>
// </div>
// </body>
// </html>";
// //Email Headers
// $headers = "MIME-version 1.0" ."\r\n";
// $header .= "Content-Type:text/html; charset=ISO-8859-1" ."\r\n";
// //Additional headers
// $headers .= "From:" .$name. "<".$email.">". "\r\n";
// mail($to, $subject, $body, $headers);
// $message_sent = true;
// }
// }}
echo '</pre>';
?>
// HTML forms (contact form it appears on click on button in calculator it is inside a modal)
<form action="index.php" method="POST" class="modal__inputs">
<div class="modal_input_section">
<legend for="name" class="modal_label">Podaj swoje imię</legend>
<input type="text" id="modal_input1" class="modal_input" name="name" >
</div>
<div class="modal_input_section">
<legend for="email" class="modal_label">Podaj swój E-mail</legend>
<input type="email" id="modal_input2"class="modal_input" name="email" >
</div>
<div class="modal_input_section">
<legend for="payment" class="modal_label">W jak sposób dokonywane były płatności</legend>
<select id="modal_input3"class="madal_input select_imput" name="payment" >
<option value="Toll" class="option1">Toll Collect</option>
<option value="UTA" class="option2">UTA ONE</option>
<option value="TELE" class="option3">TELEPASS</option>
<option value="inne">Inne</option>
</select>
</div>
<button type="submit" id="btnSend" name="btnSend" class="modal__action modal_button_positive">Prosze o kontakt!</button>
</form>
// caclulator
<form action="index.php" method="POST" class="inputs">
<div class="input_item">
<h3 class="calculator__header_item">Jakiej klasy emisji spalin posiadasz samochody ciężarowe?</h3>
<select name="euro" id="select_euro" class="input_itemA" required>
<option value="E6" class="option1">Euro 6</option>
<option value="E5" class="option2">Euro 5</option>
<option value="E4" class="option3">Euro 4</option>
<option value="E3" class="option4">Euro 3</option>
<option value="E2" class="option5">Euro 2</option>
<option value="E1" class="option6">Euro 1</option>
</select>
</div>
<div class="input_item">
<h3 class="calculator__header_item">Ile posiadasz samochodów ciężarowych we wskazanej klasie emisji spalin?
</h3>
<h3 class="error">Ta liczba nie moze równać się zero!</h3>
<input name="truckNum" type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" name="number_of_trucks[" placeholder="L. Ciężarówek" id="input_item_truck" class="input_itemA" required>
</div>
<div class="input_item">
<h3 class="calculator__header_item">Jaka jest dopuszczalna masa całkowita wskazanych w uprzednich pytaniach samochodów ciężarowych?<h3>
<select name="weight" id="input_item_dmc" class="input_itemA" required>
<option value="A" class="optionA">7,5t do 12t</option>
<option value="B" class="optionB">12 do 18t</option>
<option value="C" class="optionC">> 18t z 3 osi</option>
<option value="D" class="optionD">> 18t z 4 lub więcej osi</option>
</select>
</div>
<div class="input_item">
<h3 class="calculator__header_item">Ile średnio kilometrów w miesiącu, na terenie Niemiec, pokonuje pojedynczy samochód ciężarowy w tej klasie? </h3>
<h3 class="error">Ta liczba nie moze równać się zero!</h3>
<input name="truckKm" type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null" name="number_of_km" placeholder="Przejechane km" id="input_item_km" class="input_itemA" required>
</div>
</form>
<button type="button" id="add_input" class="btn_new">+ dodaj kolejne auta</button>
<button type="submit" id="button_calc" name="btnCalc" class="btn_intput" >Oblicz</button>
// javaScript
let userData = {
initalData: {
liczbaTirow: [],
spalanie: [],
waga: [],
liczbaKm: [],
zwrotEuro: [],
},
imie: "",
email: "",
płatność: "",
};
function calcTruck() {
for (let obj of objArr) {
const eurVal = obj.eur.value;
const dmcVal = obj.dmc.value;
const truckNoVal = obj.truckNo.value;
const truckKmVal = obj.truckKm.value;
const val = values[eurVal + dmcVal];
const result = val * truckNoVal * 11 * truckKmVal;
finalResult += result;
span.textContent = parseInt(finalResult);
userData.initalData.liczbaTirow.push(truckNoVal);
userData.initalData.spalanie.push(eurVal);
userData.initalData.waga.push(dmcVal);
userData.initalData.liczbaKm.push(truckKmVal);
userData.initalData.zwrotEuro = parseInt(result);
}
// console.log(userData);
}
function sendInfo(e) {
if (modalEmail.value === "" || modalSelect.value === "") {
showError();
modal.style.display = "block";
return;
} else {
userData.imie = modalName.value;
userData.email = modalEmail.value;
userData.płatność = modalSelect.value;
modal2.style.display = "block";
// backdrop.style.display = "none";
console.log(userData);
}
}

Fields Added Via Javascript not posting Data into $POST

I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">
You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];
FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.

PHP & Ajax - how to transfer value of textarea to textbox when value is not empty

I want to transfer the value of my textarea to my textbox automatically when the value of the textbox is fetch. how can I do it? here is my code thank you.
<?php
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
</form>
///////////////////////////////TEXT AREA///////////////////////
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br>
<input class="btn btn-primary btn-lg" type="submit" name="btnSubcode"></input>
there is my code, so the value comes in the textarea. so when the value is set i want an automatic transfer on the textbox.
I'm not sure what you mean by textbox. If you're wanting to copy the value of the textarea to another element (I'll assume with id='textbox'), do this:
$('#scanned-QR').change(function() {
var textToTransfer = $(this).val(); // get text from textarea
$('#textbox').val(textToTransfer); // set other element's value
});
I assumed that you are trying to transfer the text area value to all input text boxes. And here is the code will transfer data when click on submit.
$('.btn-primary').click(function(){
let scannedQR = $('#scanned-QR').val();
if(scannedQR != '') {
$('input').val(scannedQR);
} else {
alert('please scan the QR code and submit');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" id="card-code" value='sample' class="form-control">
</div>
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='sample2' class="form-control" maxlength="3">
</div>
</form>
<br><br>
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea>
<button class="btn btn-primary btn-lg" type="button" name="btnSubcode">Submit</button>

select option display input block and enter value that count and display another inptut value auto

I have a HTML form that is for payment status in my panel. In this form if i select payment status Advance Paid Then displays The another input box that i can enter for the advanced paid price. There is another input box is available that is remaining price if i entered the value of advance paid the remaining price should be display the remaining value using java script. If I choose payment status is Null then display total price in remaining price input box and if i choose Paid then display 0 in remaining price input box...all things run good ...but only one thing is not working that is if i enter the value of advance price the remaining price is not displyed. Here is my HTML Code
<div class="col-md-6">
<div class="form-group">
<label>Final Total</label>
<input type="text" value="100" name="total" id="Ftotal" class="form-control" >
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="paymentstatus">Payment Status</label>
<select class="form-control" name="paymentstatus" style="height: 40px;" onchange="yesnoCheck(this);">
<option value=""> ---Select Payment Status---</option>
<option>Advance</option>
<option>Null</option>
<option>Paid</option>
</select>
</div>
</div>
<div class="col-md-6" id="ifYes" style="display: none;">
<div class="form-group">
<label for="advancepaid">Advanced Paid</label>
<input type="text" name="advancedPiad" id="advancedPiad" onKeyUp="remaining()" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="remainingammount">Remaining Ammount</label>
<input type="text" name="remaining" id="remaining" class="form-control remaining" >
</div>
</div>
this is my javascript
function yesnoCheck(that) {
if (that.value == "Advance") {
document.getElementById("ifYes").style.display = "block";
} else {
document.getElementById("ifYes").style.display = "none";
}
if (that.value == "Null") {
a = Number(document.getElementById('Ftotal').value);
document.getElementById('remaining').value = a;
}
if (that.value == "Paid") {
a = 0;
document.getElementById('remaining').value = a;
}
}
function remaining()
{
a = Number(document.getElementById('Ftotal').value);
b = Number(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}
Try
document.getElementsByClassName("remaining")[0].value = c;
document.getElementsByClassName gives you the array of the elements with the class name specified. In your case just set the value of first element.
Try to use js parseInt() method to convert it into integer
function remaining()
{
a=parseInt(document.getElementById('Ftotal').value);
b = parseInt(document.getElementById('advancedPiad').value);
c = a - b;
document.getElementsByClassName("remaining").value = c;
}

Change value of dropdown with javascript

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>

Categories