JavaScript, calculate a populated cell from dropdown - javascript

By choosing the version of the product, a price populates the cell of "unit" ... working good so far.
But when I choose the quantity "Qt", I wanted the field "Price" to be populated by multiplying (unit*Price).
enter image description here
function showVersions() {
var selectBox = document.getElementById('gcard');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == 'nvidia') {
document.getElementById("nvidiaversion").style = "visibility: visible;";
} else if (userInput == 'amd') {
document.getElementById("amdversion").style = "visibility: visible;";
}
return false;
}
function itemPrice1() {
var nvidiaItem = document.getElementById('nvidiaversion');
var nvidiaInput = nvidiaItem.options[nvidiaItem.selectedIndex].value;
if (nvidiaInput == 'gtx300') {
var gtx300 = document.getElementById("unit");
gtx300.innerHTML = 300;
} else if (nvidiaInput == 'fgt4000') {
var fgt4000 = document.getElementById("unit");
fgt4000.innerHTML = 1000;
}
return false;
}
function itemPrice2() {
var amdItem = document.getElementById('amdversion');
var amdInput = amdItem.options[amdItem.selectedIndex].value;
if (amdInput == 'amd20') {
var amd20 = document.getElementById("unit");
amd20.innerHTML = 369;
} else if (amdInput == 'krt30') {
var krt30 = document.getElementById("unit");
krt30.innerHTML = 200;
}
return false;
}
function quantity() {
var quantity = document.getElementById('quantity');
var qtInput = quantity.options[quantity.selectedIndex].value;
var unit = document.getElementById("unit").value;
if (qtInput == "1") {
var qt1 = document.getElementById("price");
qt1.innerHTML = 1 * unit;
} else if (qtInput == "2") {
var qt2 = document.getElementById("price");
qt2.innerHTML = 2 * unit;
}
return false;
}
<table>
<tr>
<th> Items </th>
<th> Unit </th>
<th> Qt </th>
<th> Price </th>
</tr>
<tr>
<td name="items">
<div>
<select name="gcard" id="gcard" onchange="return showVersions();">
<option value="nvidia">NVIDIA</option>
<option value="amd">AMD</option>
</select>
</div>
<div>
<select name="gcard" id="nvidiaversion" style="visibility: hidden;" onchange="itemPrice1();">
<option value="gtx300">GTX 300</option>
<option value="fgt4000">FGT 4000</option>
</select>
</div>
<div>
<select name="gcard" id="amdversion" style="visibility: hidden;" onchange="itemPrice2();">
<option value="amd20">AMD 20</option>
<option value="krt30">KRT 30</option>
</select>
</div>
</td>
<td id="unit">
</td>
<td name="quantity">
<div>
<select name="quantity" id="quantity" onchange="quantity();">
<option value="0">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</td>
<td id="price">
</td>
</tr>
</table>
I believe something is missing im the"function quantity", but i can't get it.
NB : I need to make it work without using arrays.

td does not have value, try textContent.
Change:
var unit = document.getElementById("unit").value;
To:
var unit = document.getElementById("unit").textContent;
function showVersions(){
var selectBox = document.getElementById('gcard');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == 'nvidia') {
document.getElementById("nvidiaversion").style="visibility: visible;";
} else if (userInput == 'amd') {
document.getElementById("amdversion").style="visibility: visible;";
}
return false;
}
function itemPrice1(){
var nvidiaItem = document.getElementById('nvidiaversion');
var nvidiaInput = nvidiaItem.options[nvidiaItem.selectedIndex].value;
if (nvidiaInput == 'gtx300'){
var gtx300 = document.getElementById("unit");
gtx300.innerHTML = 300;
}else if (nvidiaInput == 'fgt4000'){
var fgt4000 = document.getElementById("unit");
fgt4000.innerHTML = 1000;
}
return false;
}
function itemPrice2(){
var amdItem = document.getElementById('amdversion');
var amdInput = amdItem.options[amdItem.selectedIndex].value;
if (amdInput == 'amd20'){
var amd20 = document.getElementById("unit");
amd20.innerHTML = 369;
}else if (amdInput == 'krt30'){
var krt30 = document.getElementById("unit");
krt30.innerHTML = 200;
}
return false;
}
function quantity(){
var quantity = document.getElementById('quantity');
var qtInput = quantity.options[quantity.selectedIndex].value;
var unit = document.getElementById("unit").textContent;
if (qtInput == "1"){
var qt1 = document.getElementById("price");
qt1.innerHTML = 1*unit;
}else if (qtInput == "2"){
var qt2 = document.getElementById("price");
qt2.innerHTML = 2*unit;
}
return false;
}
<table>
<tr>
<th> Items </th>
<th> Unit </th>
<th> Qt </th>
<th> Price </th>
</tr>
<tr>
<td name="items">
<div>
<select name="gcard" id="gcard" onchange="return showVersions();">
<option value="nvidia">NVIDIA</option>
<option value="amd">AMD</option>
</select>
</div>
<div>
<select name="gcard" id="nvidiaversion" style="visibility: hidden;" onchange="itemPrice1();">
<option value="gtx300">GTX 300</option>
<option value="fgt4000">FGT 4000</option>
</select>
</div>
<div>
<select name="gcard" id="amdversion" style="visibility: hidden;" onchange="itemPrice2();">
<option value="amd20">AMD 20</option>
<option value="krt30">KRT 30</option>
</select>
</div>
</td>
<td id="unit">
</td>
<td name="quantity">
<div>
<select name="quantity" id="quantity" onchange="quantity();">
<option value="0">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</td>
<td id="price">
</td>
</tr>
</table>

Related

How to sort list in javascripts as Alpha then numeric?

I wanted to sort a list of sele ctions values as alphabets order fallowed by Numerical characters when i do default sort numeric values come on top then alphabetical order i want list as alphaticals then numberics
function add() {
var frm = document.getElementById('formAdmin');
var selectedChnls = frm.selectedAssignedChnlOrgList;
var activChnls = frm.activeChnl;
var inactivChnls = frm.inactiveChnl;
var activeAssignedChnlOrgList = frm.activeAssignedChnlOrgList
for (i = 0; i < activChnls.length; i++) {
if (activChnls[i].selected == true) {
var opt = document.createElement('option');
opt.value = activChnls[i].value;
opt.innerHTML = activChnls[i].label;
activChnls[i].disabled = true;
activChnls[i].selected = false;
selectedChnls.appendChild(opt);
}
}
sortSelect();
}
function sortSelect() {
let frm = document.getElementById('formAdmin');
let selElem = frm.selectedAssignedChnlOrgList;
let tmpAry = new Array();
for (let i = 0; i < selElem.options.length; i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (let i = 0; i < tmpAry.length; i++) {
let op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
<form name="adminForm" id="formAdmin" method="post" action="http://localhost:7003/ccrSrc/initAdmin.do">
<table style="margin-top: -15px" cellspacing="0" cellpadding="0" border="0" width="760">
<tbody>
<tr bgcolor="#EEEEEE">
<td width="800" valign="top" style="margin:0px; padding: 0px;">
<table class="orgtable">
<tbody>
<tr>
<td class="tabletitle2" width="40%" nowrap="">Available Orgs:</td>
<td class="tabletitle2" width="20%"> </td>
<td class="tabletitle2" width="40%" nowrap="">Assigned Orgs:</td>
</tr>
<tr>
<!--Available Organizations-->
<td width="40%" class="bodytext6">
<div id="Status1" style="cursor:default; display: inline;">
<select id="" name="activeChnl" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%">
<option value="1">Accountancy, Banking and Finance</option>
<option value="2">Animal and Plant Resource</option>
<option value="3">Business, Consulting and Management</option>
<option value="4">Charity and Voluntary Work</option>
<option value="5">Creative Arts and Design</option>
<option value="6">Energy and Utilities</option>
<option value="7">Engineering and Manufacturing</option>
<option value="8">Enviromemt amd Agriculture</option>
<option value="9">Healthcare</option>
<option value="10">Hospitality and Events Management</option>
<option value="1000013677">4L Accountancy, Banking and Finance</option>
<option value="1000012499">1763615 Creative Arts and Design</option>
<option value="1000015252">2540722 Energy and Utilities</option>
<option value="1000013677">1863615 Healthcare</option>
</select>
</div>
</td>
<td align="center" width="20%" class="tabletitle2" nowrap="">
<br><br><br><br>
<a id="btnAdd" type="button" style="font-size:20" onclick="javascript:add();">Add >></a><br><br><br>
</td>
<td width="40%" class="bodytext6">
<select name="selectedAssignedChnlOrgList" multiple="multiple" size="25%" style="overflow-x:scroll;width:100%"></select>
</td>
</tr>
<tr>
<td></td>
<td>
</td>
<td align="right">
<button id="cancel" style="width:75px;" type="button" onclick="javascript:loadUserOrgAction();">Cancel</button>
<button id="save" style="width:75px;" type="button" onclick="javascript:loadUserOrgAction();">Save</button>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</form>
i want same order when it added on right side of the page as alphabetical order first then numerics after all alphabetics
You can use below function to sort by value:
function sortSelect() {
let frm = document.getElementById('formAdmin');
let selElem = frm.selectedAssignedChnlOrgList;
let tmpAry = new Array();
for (let i = 0; i < selElem.options.length; i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = parseInt(selElem.options[i].value);
}
tmpAry.sort(compareByValue);
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (let i = 0; i < tmpAry.length; i++) {
let op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
function compareByValue(a, b) {
return a[1] - b[1];
}
return;
}
this way :
any question(s) ?
const
adminForm = document.forms['adminForm']
, arrActiv = Array.from( adminForm.activeChnl.options )
, arrAssigned = []
;
adminForm.btnAdd.onclick = () =>
{
Array.from( adminForm.activeChnl.selectedOptions ).forEach( opt =>
{
let
key = arrActiv.findIndex( el => el===opt ) // get original option index
, elm = opt.cloneNode(true) // clone option
;
opt.disabled = true
arrAssigned.push({ key,elm })
})
if (adminForm.activeChnl.selectedOptions.length > 0 )
{
adminForm.activeChnl.selectedIndex = -1 // unselect anything
arrAssigned.sort((a,b)=>parseInt(a.key)-parseInt(b.key) ) // sort
arrAssigned.forEach( row => // reorganize the select 2 order
{
adminForm.selectedAssignedChnlOrgList.appendChild( row.elm ) // what a name!
})
}
}
select {
height : 30em;
width : 22em;
}
<form name="adminForm">
<table>
<tr>
<td>
<select name="activeChnl" multiple >
<option value="1">Accountancy, Banking and Finance</option>
<option value="2">Animal and Plant Resource</option>
<option value="3">Business, Consulting and Management</option>
<option value="4">Charity and Voluntary Work</option>
<option value="5">Creative Arts and Design</option>
<option value="6">Energy and Utilities</option>
<option value="7">Engineering and Manufacturing</option>
<option value="8">Enviromemt amd Agriculture</option>
<option value="9">Healthcare</option>
<option value="10">Hospitality and Events Management</option>
<option value="1000013677">4L Accountancy, Banking and Finance</option>
<option value="1000012499">1763615 Creative Arts and Design</option>
<option value="1000015252">2540722 Energy and Utilities</option>
<option value="1000013677">1863615 Healthcare</option>
</select>
</td>
<td> <button name="btnAdd" type="button">Add</button> </td>
<td>
<select name="selectedAssignedChnlOrgList" multiple >
</select>
</td>
</tr>
</table>
</form>

how can i store the value that i select from drop down and checkbox in the hidden filed?

<script>
var mainlist=document.form.seleField;
//var valuelist=document.form.seleValue
//var value=new Array();
var parent = document.getElementById("id1");
var value=[]
value[0]=""
value[1]=["Monthly|M", "Bi-Weekly|BW", "Weekly|W", "Daily|D"]
value[2]=["Monday|1", "Tuesday|2", "Wednesday|3", "Thursday|4", "Friday|5", "Saturday|6", "Sunday|7"]
value[3]=["> 100|100","> 300|300", "> 500|500", "> 700|700", "> 1000|1000", "> 1500|1500", "> 2000|2000" , "> 5000|5000"]
/* function updatevalue(selectedvaluegroup){
valuelist.options.length=0
if (selectedvaluegroup>0){
for (i=0; i<value[selectedvaluegroup].length; i++)
valuelist.options[valuelist.options.length]=new Option(value[selectedvaluegroup][i].split("|")[0],
value[selectedvaluegroup][i].split("|")[1])
}
}
*/
function updatevalue(selectedvaluegroup){
parent.innerHTML = "";
if(selectedvaluegroup ==2){
for (var i=0; i<value[selectedvaluegroup].length; i++){
var chkbox = document.createElement("input");
chkbox.type = "checkbox";
chkbox.name = "day[]";
chkbox.value = value[selectedvaluegroup][i].split("|")[1];
parent.appendChild(chkbox);
var text = document.createElement("span");
text.innerHTML = value[selectedvaluegroup][i].split("|")[0];
parent.appendChild(text);
}
}
else if(selectedvaluegroup > 0){
var select = document.createElement("select");
parent.appendChild(select);
for ( i=0; i<value[selectedvaluegroup].length; i++){
var option = document.createElement("option");
option.value = value[selectedvaluegroup][i].split("|")[1];
option.text = value[selectedvaluegroup][i].split("|")[0];
select.add(option);
}
}
}
</script>
<table border="0" width="100%">
<!-- START ADD FORM -->
<form name="form" action="<?$PHP_SELF?>" method="post" onsubmit="return chkField.exec();">
<tr bgcolor="#ffffff">
<td>
<input id="txtSupplierNo" name="txtSupplierNo" size="6" maxlength="6" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$_GET['primaryID']?>" readOnly>
</td>
<td>
<input id="txtSupplier" name="txtSupplier" type="text" size = "60" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$objSupp->Supplier?>" readOnly>
</td>
</tr>
<tr bgcolor="#3399CC">
<td class="tfvNormal" id="lblField">Criteria</td>
<td class="tfvNormal" id="lblValue" colspan="3">Parameter</td>
</tr>
<tr bgcolor="#ffffff">
<td>
<select class='selectBox' name="seleField" id="seleField" onChange="updatevalue(this.selectedIndex)" tabindex="<?=++$tabindex?>">
<option value="">select a rule</option>
<option value="OrderFrequency">Order Frequency</option>
<option value="OrderDay">Order Day</option>
<option value="MinimumOrder">Minimum Order Amount</option>
</select>
</td>
<td>
<!--<select class='selectBox' name="seleValue" id="seleValue" tabindex="<//?=++$tabindex?>"></select>-->
<div id="id1">
</div>
</td>
<td align="center" colspan="2">
<input type="image" src="../../../image/add.gif" name="buttSubmit" id="buttSubmit" value="Add" style="cursor: hand;" onClick="MM_showHideLayers('Layer1','','show')" alt="Add Records" <?=$Permission?> >
</td>
</tr>
</form>
<!-- END ADD FORM -->
i have a problem to get the data and store in database.
i have two select options which are dropdown and checkbox.
i use javascript to make the checkbox and only checkbox selection can store the data in the database.
if (($_POST['buttSubmit_x'] >= 0) && ($_POST['seleField'])){
$Field = trim($_POST['seleField']);
$Value = trim($_POST['seleValue']);
$Value = '';
foreach($_POST['day'] as $selected){
$Value .= trim($selected) . "|";
}
$SupplierNo = $_POST['txtSupplierNo'];
$Supplier = $_POST['txtSupplier'];
$CreateUser = $_SESSION['userID'];
$ModifyUser = $_SESSION['userID'];
$CreateDate = date("Y-m-j");
$CreateTime = date("H:i:s");
if($Field != 'OrderDay'){
$objchEx = SQL_QUERY("SELECT * FROM SupplierEx WHERE Field='$Field' and SupplierNo='$SupplierNo'");
if($objchEx->Value && $Value <> $objchEx->Value){
$chkPara = 1;
echo"<script>";
echo"alert('Duplicate $Field ! Kindly delete the existing Parameter.');";
echo"</script>";
}
}
<table border="0" width="100%">
<!-- START ADD FORM -->
<form name="form" action="<?$PHP_SELF?>" method="post" onsubmit="return chkField.exec();">
<tr bgcolor="#ffffff">
<td>
<input id="txtSupplierNo" name="txtSupplierNo" size="6" maxlength="6" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$_GET['primaryID']?>" readOnly>
</td>
<td>
<input id="txtSupplier" name="txtSupplier" type="text" size = "60" class="txbDisplay" tabindex="<?=$tabindex++?>" value="<?=$objSupp->Supplier?>" readOnly>
</td>
</tr>
<tr bgcolor="#3399CC">
<td class="tfvNormal" id="lblField">Criteria</td>
<td class="tfvNormal" id="lblValue" colspan="3">Parameter</td>
</tr>
<tr bgcolor="#ffffff">
<td>
<select class='selectBox' name="seleField" id="seleField" onChange="updatevalue(this.selectedIndex)" tabindex="<?=++$tabindex?>">
<option value="">select a rule</option>
<option value="OrderFrequency">Order Frequency</option>
<option value="OrderDay">Order Day</option>
<option value="MinimumOrder">Minimum Order Amount</option>
</select>
</td>
<td>
<!--<select class='selectBox' name="seleValue" id="seleValue" tabindex="<//?=++$tabindex?>"></select>-->
<div id="id1">
</div>
</td>
<td align="center" colspan="2">
<input type="image" src="../../../image/add.gif" name="buttSubmit" id="buttSubmit" value="Add" style="cursor: hand;" onClick="MM_showHideLayers('Layer1','','show')" alt="Add Records" <?=$Permission?> >
</td>
</tr>
</form>
<!-- END ADD FORM -->
<script>
var mainlist=document.form.seleField;
//var valuelist=document.form.seleValue
//var value=new Array();
var parent = document.getElementById("id1");
var value=[]
value[0]=""
value[1]=["Monthly|M", "Bi-Weekly|BW", "Weekly|W", "Daily|D"]
value[2]=["Monday|1", "Tuesday|2", "Wednesday|3", "Thursday|4", "Friday|5", "Saturday|6", "Sunday|7"]
value[3]=["> 100|100","> 300|300", "> 500|500", "> 700|700", "> 1000|1000", "> 1500|1500", "> 2000|2000" , "> 5000|5000"]
function updatevalue(selectedvaluegroup){
parent.innerHTML = "";
if(selectedvaluegroup ==2){
for (var i=0; i<value[selectedvaluegroup].length; i++){
var chkbox = document.createElement("input");
chkbox.type = "checkbox";
chkbox.name = "day[]";
chkbox.value = value[selectedvaluegroup][i].split("|")[1];
parent.appendChild(chkbox);
var text = document.createElement("span");
text.innerHTML = value[selectedvaluegroup][i].split("|")[0];
parent.appendChild(text);
}
}
else if(selectedvaluegroup > 0){
var select = document.createElement("select");
parent.appendChild(select);
for ( i=0; i<value[selectedvaluegroup].length; i++){
var option = document.createElement("option");
option.value = value[selectedvaluegroup][i].split("|")[1];
option.text = value[selectedvaluegroup][i].split("|")[0];
select.add(option);
}
}
}
</script>
Please check the below example .Hope it helps
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var valueBtn = document.getElementById('valueBtn');
foo.addEventListener('change', function () {
bar.value = this.options[this.selectedIndex].value;
}, true);
valueBtn.addEventListener('click', function () {
console.log(bar.value)
}, true);
<select id="foo">
<option>select option</option>
<option>a</option>
<option>b</option>
</select>
<input style="display:none " type="text" id="bar">
<input type="button" id="valueBtn" value="Click and check console">

Loop through dynamically generated HTML elements with the same Class and build objects with their data

I am trying to collect data from a table that is dynamically generated on a button click. As you will see below, the button creates a new text box and a multiselect drop down. Currently, my code will only grab the first value from both the textbox and the dropdown.
My end goal is to create an object of key/values that will look like this:
{"group 1":[multiselect value, multiselect value], "group 2": [multiselect value, multiselect value, multiselect value], "group 3": [multiselect value, multiselect value]}
Below is my current code. Any guidance is appreciated!
function servicePackageAdd()
{
var serviceName = document.getElementById('servicePackageText').value;
var serviceList = document.querySelectorAll('.service');
var serviceGroupName = [];
for (var i = 0; i < serviceList.length; i++)
{
serviceGroupName.push(serviceList[i].querySelector('input.packageGroupName').value);
var sourceType = document.querySelector('select#multiple-checkboxes');
var serviceArray = [];
for (i = 0; i < sourceType.selectedOptions.length; i++)
{
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
var groupName = {};
groupName[serviceGroupName] = serviceArray;
ungroupedServiceArray = [];
}
}
document.getElementById('addGroup').onclick = duplicate;
function duplicate()
{
var original = document.getElementById('addService');
var rows = original.parentNode.rows;
var i = rows.length - 1;
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
}
var divs = ["addService"];
var visibleDivId = null;
function toggleCheckbox(divId)
{
if(visibleDivId === divId)
{
visibleDivId = null;
} else
{
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs()
{
var i, divId, div;
for(i = 0; i < divs.length; i++)
{
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId)
{
div.style.display = "block";
}
else
{
div.style.display = "none";
}
}
}
function servicePackageName()
{
var servicePackageName = document.getElementById('servicePackageText').value;
var servicePackageNameBold = servicePackageName.bold().fontcolor('#337ab7');
document.getElementById('servicePackageInputName').innerHTML = servicePackageNameBold;
}
<div>
<div class="servicePackageCreation">
<h2><b>Service Package Administration</b></h2>
<br>
<span><p><b>Create Service Package: </b></p><p id="servicePackageInputName"></p></span>
<div class="form-group">
<input type="text" class="form-inline" id="servicePackageText" minlength= 1 placeholder=" Service Package Name" required>
<button type="button" class="btn btn-primary" onclick="toggleCheckbox('addService'); servicePackageName();" id="addGroupsAndServices">Next</button>
</div>
<table>
<tr id="addService" class="service" style="display:none">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName"/>
</td>
<td>
<span><b>Add Services</b></span>
<select id="multiple-checkboxes" multiple="multiple">
<?php echo $servicehtml ?>
</select>
</td>
</tr>
<tr>
<td>
<button id="addGroup" class="btn btn-primary" onclick="duplicate()">Add More</button>
</td>
</tr>
</table>
<button type="button" class="btn btn-success test1234" onclick="confirmAddButton()" id="adminBulkConfirm">Create</button>
<br>
<br>
</div>
Using Object.values Array#map and Array#reduce.
const services = document.querySelectorAll(".service");
const res = Object.values(services)
.map((service, i) => {
const inputText = service.querySelector('.packageGroupName').value;
return {
[inputText]: [...service.querySelectorAll('option:checked')].map(o => Number(o.value))
}
})
.reduce((a, c) => ({ ...a,...c}), {});
console.log(res);
table {
display: none;
}
<table>
<tr class="service">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName" value="Banana" />
</td>
<td>
<span><b>Add Services</b></span>
<select class="multiple-checkboxes" multiple="multiple">
<option value="1" selected>12</option>
</select>
</td>
</tr>
<tr class="service">
<td>
<span><b>Service Group Name</b></span>
<input type="text" name="servicetype" id="packageGroupName" class="packageGroupName" value="Orange" />
</td>
<td>
<span><b>Add Services</b></span>
<select class="multiple-checkboxes" multiple>
<option value="2" selected>2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
<button class="btn btn-primary" onclick="duplicate()">Add More</button>
</td>
</tr>
</table>

mapping data in different tables choice

I'm working on a project on data mapping. Some details are explained in other subject :
Splice data in array
Concerning recovery of select values, I'm using JQuery to stock them in array.
When these values are recovered, I would like according to mapping choice, complete existing table. The problem is that how can I detect number of columns before insertion in database.
This following error returned to me every time :
SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1
Query result :
PDO->prepare('INSERT INTO gestion (firstName,lastName,mail) VALUES
(\'test\',\'jean\',\' marc\',\'marc\')')
var choiceFields = [];
var contentChoiceFields = [];
$('#selectFields').multipleSelect({
filter: true,
onClick: function(view)
{
choiceFields.push(view.value);
var length = choiceFields.length - 1;
if (view.checked === false)
{
choiceFields = jQuery.grep(choiceFields, function(value)
{
return value !== view.value;
});
}
contentChoiceFields = choiceFields;
console.log(contentChoiceFields);
$('.selectChoiceFields').val(contentChoiceFields);
},
onCheckAll: function()
{
/*var contentSelect = "";
$('#selectFields').each(function()
{
contentSelect = $(this).val();
choiceFields.push(contentSelect);
});
contentChoiceFields = contentSelect;*/
choiceFields = []; // delete all previous values
var options = document.querySelector('#selectFields');
for(var i=0;i<options.length;i++)
{
choiceFields.push(options[i].text);
contentChoiceFields = choiceFields;
}
$('.selectChoiceFields').val(contentChoiceFields);
},
onUncheckAll: function()
{
choiceFields = [];
$('.selectChoiceFields').val('');
}
});
$(".mapping").on('click', function(event) {
var data = [];
var mapping = $(this).closest('th').text();
$('th input:checked').each(function(index,element) {
var currentCell = element.parentNode;
$('td:nth-child(' + (currentCell.cellIndex+1) + ')').each(function(i,el) {
if($(el).text().match(/^([a-zA-Z]+)(\d+)([a-zA-Z]+)$/))
{
data.push("'" + $(el).text() + "'");
}
else if($(el).text().match(/^(\d+)/))
{
var value = parseInt($(el).text());
data.push("'" + value + "'");
}
else
{
data.push("'" + $(el).text() + "'");
}
});
});
var content = data;
console.log(content);
$('.choiceData').val(content);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://rawgit.com/wenzhixin/multiple-select/master/multiple-select.js"></script>
<link rel="stylesheet" href="https://rawgit.com/wenzhixin/multiple-select/master/multiple-select.css">
</head>
<body>
<div class="select-box">
<label for="selectFields"><span class="label-FieldChoice">Choice fields</span></label>
<select id="selectFields" multiple="multiple" style="display: none;">
<option value="id">id</option>
<option value="username">username</option>
<option value="username_canonical">username_canonical</option>
<option value="email">email</option>
<option value="email_canonical">email_canonical</option>
<option value="enabled">enabled</option>
<option value="salt">salt</option>
<option value="password">password</option>
<option value="last_login">last_login</option>
<option value="confirmation_token">confirmation_token</option>
<option value="password_requested_at">password_requested_at</option>
<option value="roles">roles</option>
<option value="lastName">lastName</option>
<option value="firstName">firstName</option>
</select>
</div>
<table class="table table-striped table-hover" id="tableContent">
<tbody>
<tr>
<th>lastName<input name="lastName" class="mapping" id="lastName" type="checkbox">
</th>
<th> firstName<input name="firstName" class="mapping" id="firstName" type="checkbox">
</th>
<th> âge<input name="âge" class="mapping" id="âge" type="checkbox">
</th>
<th> phoneNumber<input name="phoneNumber" class="mapping" id="phoneNumber" type="checkbox">
</th>
<th> mail<input name="mail" class="mapping" id="mail" type="checkbox">
</th>
</tr>
<tr>
<td class="mappingContent">test</td>
<td> marc</td>
<td> 21</td>
<td> 0265412369</td>
<td> marc.test#bla.fr</td>
</tr>
<tr>
<td class="mappingContent">jean</td>
<td>marc</td>
<td>28</td>
<td>0692123456</td>
<td>marc.jean#orange.fr</td>
</tr>
</tbody>
</table>
</body>
</html>
if($choiceMapping === "completion")
{
if($session->get('tableChoice') == "user")
{
$password = password_hash('test', PASSWORD_DEFAULT);
$content = $cnx->prepare("INSERT INTO ".$session->get('tableChoice')." "."(".$selectChoiceFields[0].", enabled, password, roles, lastName, firstName) VALUES (".$choiceData.",1, '".$password."', 'a:1:{i:0;s:1:\"0\";}', 'test', 'test')");
$content->execute();
$addFlash = $this->addFlash('success', "Completed recording !");
}
else
{
$content = $cnx->prepare('INSERT INTO '.$session->get('tableChoice').' ('.$selectChoiceFields[0].') VALUES ('.$choiceData.')');
$content->execute();
$addFlash = $this->addFlash('success', "Completed recording !");
}
}
else
{
$content = $cnx->prepare('Truncate '.$session->get('tableChoice'));
$content->execute();
$sql = $cnx->prepare('INSERT INTO '.$session->get('tableChoice').' ('.$selectChoiceFields[0].') VALUES (:choiceData)');
$sql->bindValue(':choiceData', $choiceData);
$sql->execute();
$addFlash = $this->addFlash('success', "Completed recording !");
}
result of $selectChoiceFields :
array(1) { [0]=> string(15) "firstName,lastMail,mail" }
result of $choiceData :
string(30) "'test','jean',' marc','marc'"

how to change rows and columns of table based on select id option value?

How can I change the number of rows and columns of a html table with the input text, based on the value selected in the select Id option?
like
Number of Models : 1,2,3,4
Number of items per Model :(this is the table that takes the input values and this needs to change the number of rows or columns of the table based on the value selected in the 'Number of Models'), this is the code i have:
<table>
<tr>
<th>Number of Models:<title="Number of Models"></th>
<td><select id="numberofmodels" onkeyup="NumberOfModels()" name="Number of Models">
<option >1</option >
<option >2</option >
<option >3</option >
<option >4</option >
<option >5</option >
<option >6</option >
</select></td>
</tr>
<tr>
<th>Number of items per model:</th>
<td>
<table border="1">
<tr>
<td>
<input id="itemsmodel" onkeyup="ItemsModelValidate()" type="text" maxlength="50" > <br>
</td>
</tr>
</table>
can somebody give me the javascript function ItemsModelValidate() to make this work ?
I have the following javascript function for other purpose, can this be edited to achieve that ?
function ItemsModelValidate(){
$itemsmodel = document.getElementById("itemsmodel").value;
if(!/^[0-9]+$/.test($itemsmodel)) {
alert();
}
}
function NumbersOfModels(){
$numberofmodels = document.getElementById("numberofmodels").value;
if(!/^[0-9]+$/.test($numberofmodels)) {
alert();
}
}
You can use something like this:
<html>
<body>
<table>
<tr>
<th>Number of Models:</th>
<th>
<select id="NumberOfModels" name="Number of Models">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</th>
</tr>
<tr>
<th>Number of items per model:</th>
</tr>
<tr>
<td>
<table border="1">
<tbody id="itemsmodel"></tbody>
</table>
</td>
</tr>
</table>
<script type="text/javascript">
var models = document.getElementById("NumberOfModels");
var modelsTable = document.getElementById("itemsmodel");
models.addEventListener("change", drawModels, false);
function drawModels(){
var modelsNum = parseInt(models.value);
var curModels = modelsTable.rows.length;
if (modelsNum > curModels) {
var delta = modelsNum - curModels;
for(var i = 0; i < delta; i++) {
var rowElement = document.createElement("tr");
var cellElement = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("maxlength", "3");
input.addEventListener("keyup", drawItems, false);
cellElement.appendChild(input);
rowElement.appendChild(cellElement);
modelsTable.appendChild(rowElement);
}
} else {
while(modelsTable.rows.length > modelsNum){
var row = modelsTable.rows[modelsTable.rows.length - 1];
modelsTable.removeChild(row);
}
}
}
function drawItems(){
var row = this.parentNode.parentNode;
var val = this.value;
var isNum = /^\d+$/.test(val);
if(isNum){
var curCells = row.cells.length - 1;
var cellsNum = parseInt(val);
if(cellsNum > curCells){
var delta = cellsNum - curCells;
for(var i = 0; i < delta; i++) {
var cellEl = document.createElement("td");
cellEl.innerText = "Lorem ipsum";
row.appendChild(cellEl);
}
} else {
while(row.cells.length > cellsNum + 1) {
var cell = row.cells[row.cells.length-1];
row.removeChild(cell);
}
}
}
}
drawModels();
</script>
</body>
</html>

Categories

Resources