CodeIgniter: Multi-select input isn't able to select multiple values - forms

Ironically, form_multiselect() I created didn't work for me. Actually it was created but I couldn't select multiple options. I followed the instructions on the user guide but still not functioning like a multi-select although it looks like one. Any silly mistakes I've made?
This is what the code looks like in web browser's inspect element feature:
<select name="meal_type[]" id="meal_type_id" onfocus="calculateTotal();" onblur="calculateTotal();" onchange="calculateTotal();" multiple="multiple">
<option value="Breakfast_1000">Breakfast</option>
<option value="Dinner_2500">Dinner</option>
<option value="Lunch_2000">Lunch</option>
</select>
This is what I coded in View:
<div class="control-group">
<label for="meal_type" class="control-label">
<i class="icon-glass"></i> Meal Type:
</label>
<div class="controls">
<?php
$js = 'id="meal_type_id" onFocus="calculateTotal();" onBlur="calculateTotal();" onChange="calculateTotal();"';
echo form_multiselect('meal_type[]', $mt_name, set_value('meal_type'), $js);
?>
<?php echo form_error('meal_type'); ?>
</div>
JAVASCRIPT
function calculateTotal() {
var room_type_id = document.getElementById('room_type_id').value;
var room_type_cost = room_type_id.split("_");
var meal_type_id = document.getElementById('meal_type_id').value;
var meal_type_cost = meal_type_id.split("_");
var ext_beds_id = document.getElementById('ext_beds_id').value;
var ext_beds_cost = ext_beds_id.split("_");
var reservation_duration = document.getElementById('reservation_duration').value;
var total_payable = ( parseInt(room_type_cost[1]) + parseInt(meal_type_cost[1]) + parseInt(ext_beds_cost[1]) ) * parseInt(reservation_duration);
document.getElementById('total_amount').value = total_payable;
}

Related

How can i dynamically add an Input select element on click of a button in ember

Am creating an ember application where am in need of dynamicaly adding a select element which will have options fetched from a server. so the select elements look like this. And instead of having all dropdown boxes predefined i need to add them dynamicaly like on a click of a button like( + add more). like
and each of those drop down boxes should contain the datas that is fetched from the server. plus i need a way to get the datas from those dynamically created select fields.
my .hbs for the current drop down page is..
map.hbs
<center><h4>Map</h4></center>
<container class = "cond">
{{#each this.model.sf as |row|}}
<select class = "sel">
{{#each this.model.sf as |sf|}}
<option value = {{sf.attrname}}>{{sf.attrname}}</option>
{{/each}}
</select><br>
{{/each}}
I tried ember-dynamic-fields but its depracted and I couldnt able to use it.. and all other solutions on web or for ember way older versions.. nothing works on ember 4.6 so could anyone helpout?
Using The Platform's native FormData functionality, demo'd here.
I think we can generate any number of inputs based on input data in the following way:
Store the form's state in some variable
conditionally show further select / inputs based on the properties in that form state.
Code-wise, that'd look like this:
{{#if (dataHasValueFor "fieldName")}}
Show previously hidden field
{{/if}}
And of course the devil is in the implementation details, so, a full working example (with sample data I made up -- we can iterate on this if you want for your specific data set, just leave a comment on this post/answer).
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { on } from '#ember/modifier';
import { get } from '#ember/helper';
// This could be your model data from your route
const DATA = {
fruits: [
'apple', 'banana', 'orange', 'mango',
'watermellon', 'avacado', 'tomato?'
],
veggies: ['cocumber', 'tomato?', 'green bean', 'kale', 'spinach'],
peppers: ['carolina reaper', 'habanero', 'jalapeƱo']
}
export default class Demo extends Component {
#tracked formData;
get categories() {
return Object.keys(DATA);
}
handleInput = (event) => {
let formData = new FormData(event.currentTarget);
let data = Object.fromEntries(formData.entries());
this.formData = data;
}
handleSubmit = (event) => {
event.preventDefault();
handleInput(event);
}
isSelected = (name, value) => this.formData?.[name] === value;
<template>
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<label>
Food Category<br>
<select name="category" placeholder="Select...">
<option selected disabled>Select a food group</option>
{{#each this.categories as |name|}}
<option
value={{name}}
selected={{this.isSelected "category" name}}
>
{{name}}
</option>
{{/each}}
</select>
</label>
<hr>
{{#let (get this.formData "category") as |selectedCategory|}}
{{#if selectedCategory}}
<label>
{{selectedCategory}}<br>
<select name={{selectedCategory}}>
<option selected disabled>
Select {{selectedCategory}}
</option>
{{#each (get DATA selectedCategory) as |food|}}
<option
value={{food}}
selected={{this.isSelected selectedCategory food}}
>
{{food}}
</option>
{{/each}}
</select>
</label>
{{/if}}
{{/let}}
</form>
<hr>
FormData:
<pre>{{toJson this.formData}}</pre>
</template>
}
const toJson = (input) => JSON.stringify(input, null, 4);
This demo is interactive here, on limber.glimdown.com
Note that the syntax used here is what will be default in the upcoming Polaris Edition of Ember, and is available via ember-template-imports
Update (after comments)
Demo here
I took some liberties with the how the fields are dynamic, because I think this more easily shows the concept asked about in the question: dynamically showing fields in a form.
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { on } from '#ember/modifier';
import { get } from '#ember/helper';
export default class Demo extends Component {
#tracked formData;
handleInput = (event) => {
let formData = new FormData(event.currentTarget);
let data = Object.fromEntries(formData.entries());
this.formData = data;
}
handleSubmit = (event) => {
event.preventDefault();
handleInput(event);
}
<template>
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<div class="grid">
<label>
Name <input type="checkbox" name='hasName'>
</label>
<label>
Email <input type="checkbox" name='hasEmail'>
</label>
<label>
Alias <input type="checkbox" name='hasAlias'>
</label>
<hr>
{{#if (get this.formData 'hasName')}}
<label>
Name
<input type="text" name="name" class="border" />
</label>
{{/if}}
{{#if (get this.formData 'hasEmail')}}
<label>
Email
<input type="email" name="email" class="border" />
</label>
{{/if}}
{{#if (get this.formData 'hasAlias')}}
<label>
Alias
<input type="text" name="alias" class="border" />
</label>
{{/if}}
</div>
</form>
<hr>
FormData:
<pre>{{toJson this.formData}}</pre>
</template>
}
const toJson = (input) => JSON.stringify(input, null, 4);
And... since it seems you have a lot of fields, you may want to go as dynamic as possible:
demo here
which is the following code:
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<div class="grid">
{{#each FIELDS as |field|}}
<label>
{{field}} <input type="checkbox" name='has-{{field}}'>
</label>
{{/each}}
<hr>
{{#each FIELDS as |field|}}
{{#if (get this.formData (concat 'has-' field))}}
<label>
{{field}}
<input type="text" name={{field}} class="border" />
</label>
{{/if}}
{{/each}}
</div>
</form>
I guess Simple js code did the magic of adding and retriving data.. pity of me after finding out.. And for some dynamic ember formdata the previous answer from nullvox helped out.. so here is the code
.hbs
<table class="table">
<th>
<td>Sf</td>
</th>
<th>
<td>Db</td>
</th>
<tbody id = "map">
</tbody>
</table>
<button class = "btn btn-sm btn-primary" type="button" {{action "submit"}}>Submit</button>
<button class = "btn btn-success btn-sm" onclick = {{action "get"}} type="button">Add another</button>
controller code for creating element
#action
get() {
let div = document.getElementById('map');
let tr = document.createElement('tr');
let td = document.createElement('td');
let td2 = document.createElement('td');
var select = document.createElement('select');
select.setAttribute('class', 'sfselect');
div.appendChild(tr);
tr.appendChild(td);
td.appendChild(select);
for (var i = 0; i < sf.length; i++) {
var option = document.createElement('option');
option.value = sf[i];
option.text = sf[i];
select.appendChild(option);
}
var select2 = document.createElement('select');
select2.setAttribute('class', 'dbselect');
tr.appendChild(td2);
td2.appendChild(select2);
for (var i = 0; i < db.length; i++) {
var option = document.createElement('option');
option.value = db[i];
option.text = db[i];
select2.appendChild(option);
}
}
controller code for getting data
#action submit() {
var sfattr = document.querySelectorAll('.sfselect');
var dbattr = document.querySelectorAll('.dbselect');
var sf = [];
var db = [];
console.log(sfattr.length);
let datas;
for (var i = 0; i < sfattr.length; i++) {
sf[i] = sfattr[i].value;
db[i] = dbattr[i].value;
}
let m1 = sf.toString();
let m2 = db.toString();
$.ajax({
url: 'http://localhost:8080/lorduoauth/Map',
method: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: {
m1: m1,
m2: m2,
},
success: function (response) {
console.log(datas);
alert(response);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('error' + errorMessage);
},
});
}
thus the output looks like this

insert data if not exist in the column using Laravel elequant

I'm developing a doctor's appointment laravel project. the condition is if a user fixes an appointment they can't able to fix the appointment for the same doctor at the same date and time. I tried with firstOrCreate method but doesn't match my condition. here are my conditions
1.if doctors_id AND date AND time already exist then shouldn't insert the data
2.if doctors_id OR date OR time, any three of this already exist then can insert the data
3.if all fields already not exist then insert data
here are the code snippets
In view
<div class="card-body">
<form action="appointment" method="post">
{{ #csrf_field() }}
<select name="doctors" id="" class="form-control">
#foreach ($docList as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select><br><br>
<input type="date" name="date" id="" class="form-control">
<br><br>
<select name="time" class="form-control">
<option value="9-10AM">9-10AM</option>
<option value="10-11AM">10-11AM</option>
<option value="1-2PM">1-2PM</option>
<option value="2-3PM">2-3PM</option>
<option value="3-4PM">3-4PM</option>
</select>
<button type="submit" class="btn btn-primary">Fix Appointment</button>
</form>
</div>
In controller
public function store(Request $request)
{
$uId = Auth::id();
$fixAppointment = Appointment::firstOrNew(['doctors_id'=>$request->doctors,'date'=>request('date')],['time'=>request('time')]);
$fixAppointment->users_id = $uId;
$fixAppointment->save();
}
Here I sorted out the issue by using where condition
In controller
$appointment = Appointment::where('date', '=', request('date'))->where('time','=',request('time'))->where('doctors_id','=',request('doctors'))->first();
if ($appointment === null)
{
$fixAppointment = New Appointment;
$fixAppointment->doctors_id = $request->doctors;
$fixAppointment->users_id = $uId;
$fixAppointment->date = $request->date;
$fixAppointment->time=$request->time;
$fixAppointment->save();
}
here is the link which I referred to find this solution.

function createInnerHTML - how to repeat with other form input?

I have the below code;
.gs
function createInnerHTML() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("WELD DATE LOG");
var namesValues = names.getRange(2,13,names.getLastRow()-1).getValues();
var innerHTML = [];
for (var i=0;i<namesValues.length;i++){
innerHTML.push({value:''+ namesValues[i][0], text:namesValues[i][0]});
};
return innerHTML;
}
.html
<? var innerHTML= createInnerHTML(); ?>
<select name="JOINT" id="JOINT" aria-label="JOINT" aria-required="true" required="">
<option value=""></option>
<? innerHTML.forEach(function(option) { ?>
<option value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>
The purpose is to update the form options by a column in the spreadsheet where I have some related issues:
First, if the cell is blank, I need to remove the option from the form because it reads a blank option in the list
For example, when a user opens the options list in the form, it gives 4 options with two are blank and two with values instead of displaying the two values only
Second, how can I repeat the same function in the same script but with other form questions whether select or checkbox
For example, I have this html form with two input fields:
<? var innerHTML= createInnerHTML(); ?>
<select name="JOINT" id="JOINT" aria-label="JOINT" aria-required="true" required="">
<option value=""></option>
<? innerHTML.forEach(function(option) { ?>
<option value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>
<select name="WS" required>
<option value=""></option>
<option value="WS S01">WS S01</option>
<option value="WS S02">WS S02</option>
<option value="WS S03">WS S03</option>
<option value="WS S04">WS S04</option>
</select>
In the .gs file, I need to repeat the same mentioned function "function createInnerHTML()" with both form inputs
Thanks in advance
if the cell is blank If the cell is blank can be corrected several ways. You could use the filter method on innerHTML or:
function createInnerHTML() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("WELD DATE LOG");
var namesValues = names.getRange(2,13,names.getLastRow()-1).getValues();
var innerHTML = [];
for (var i=0;i<namesValues.length;i++){
if(namesValues[i][0]) {
innerHTML.push({value:''+ namesValues[i][0], text:namesValues[i][0]});
}
};
return innerHTML;
}
how can I repeat the same function in the same script but with other form questions whether select or checkbox
You didn't supply any form information or spreadsheet data, so we don't really know the specifics to answer the question intelligently. Please provide additional information and code requirements.
This is how I generally update a select:
gs:
function getSelectOptions() {
sortOptions();
var ss=SpreadsheetApp.openById(getGlobal('gSSID'));
var sh=ss.getSheetByName('Options');
var rg=sh.getDataRange();
var vA=rg.getValues();
var options=[];
for(var i=0;i<vA.length;i++)
{
options.push(vA[i][0]);
}
return vA;
}
function sortOptions() {
var ss=SpreadsheetApp.openById(getGlobal('gSSID'));
var sh=ss.getSheetByName('Options');
var rg=sh.getRange(2,1,sh.getLastRow()-1,1);
rg.sort({column:1,ascending:true});
}
js:
function updateSelect(vA,id){
var id=id || 'sel1';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
Okay I tried the below codes and they worked:
.html
<? var innerHTML= createInnerHTML1(); ?>
<select name="List1" required="">
<option value=""></option>
<? innerHTML.forEach(function(option) { ?>
<option value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>
<? var innerHTML= createInnerHTML2(); ?>
<select name="List2" required="">
<option value=""></option>
<? innerHTML.forEach(function(option) { ?>
<option value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>
.gs
function createInnerHTML1() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("sheet name");
var namesValues = names.getRange(2,14,names.getLastRow()-1).getValues();
var innerHTML = [];
for (var i=0;i<namesValues.length;i++){
if(namesValues[i][0]) {
innerHTML.push({value:''+ namesValues[i][0], text:namesValues[i][0]});
}
};
return innerHTML;
}
function createInnerHTML2() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("sheet name");
var namesValues = names.getRange(2,11,names.getLastRow()-1).getValues();
var innerHTML = [];
for (var i=0;i<namesValues.length;i++){
if(namesValues[i][0]) {
innerHTML.push({value:''+ namesValues[i][0], text:namesValues[i][0]});
}
};
return innerHTML;
}
And so on you can repeat the same function in the .gs file with many inputs in the .html file. Thanks again Cooper

Opencart get select value to controller for filter

I have page called no.tpl, in this page am displaying customer name in select dropdown
this is the code:
no.tpl
<select name="customer_id" id="customer" style="width: 325px;margin-bottom:10px" class="form-control">
<?php foreach($customerData as $customer){ ?>
<option value=<?php echo $customer['customer_id']?>><?php echo $customer['customer_name']?></option>
<?php }?>
</select>
In controller page i have to filter selected customer list
$queryCustomer = $this->db->query("select customer_id, concat(firstname, ' ',lastname) as name, email from " . DB_PREFIX . "customer where customer_id='6'");
$selectedCustomer = $queryCustomer->row;
$selectedCustomerId = $selectedCustomer['customer_id'];
$selectedCustomerName = $selectedCustomer['name'];
$selectedCustomerEmail = $selectedCustomer['email'];
I want customer_id='6' as selected customer_id. I mean pass the select value to controller page
Try this code in view page
<select name="customer_id" id="input-sales-person" style="width: 325px;margin-bottom:10px" class="form-control">
<?php foreach($customerData as $customer){ ?>
<option id="temp" value=<?php echo $customer['customer_id']?>><?php echo $customer['customer_name']?></option>
<?php }?>
</select>
<input type="submit" id="noOrder" Onclick="return ConfirmDelete();" value="Submit" class="btn btn-primary">
Use this following script
<script type="text/javascript">
$('#noOrder').on('click', function() {
var temp1=$( "#input-sales-person option:selected" ).val();
var temp2=$( "#input-sales-person option:selected" ).text();
document.cookie = "selectedCustomerId=" +temp1;
document.cookie = "selectedCustomerName=" +temp2;
location="index.php?route=sale/no";
});
</script>
In controller pass the customer_id as $selectedCustomerId=$_COOKIE['selectedCustomerId'];
$selectedCustomerId=$_COOKIE['selectedCustomerId']; /*customer_id=6*/
$queryCustomer = $this->db->query("select customer_id, concat(firstname, ' ',lastname) as name, email from " . DB_PREFIX . "customer where customer_id='".$selectedCustomerId."'");

Angular cast select value to int

I have a form with different selects like :
<select [(ngModel)]="selected.isConnected" (ngModelChange)="formChanged()" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
My backend expect to receive an int in the "isConnected" attribute. Unfortunately as soon as I change the value of the select the attribute is cast to a string :
{
isConnected : "0", // 0 expected
}
For standard <input> I could use type="number" but for a <select> I'm clueless.
Is there a way to force angular 2 to cast the data to int ?
Use [ngValue] instead of "value":
<select [(ngModel)]="selected.isConnected" id="etat">
<option [ngValue]="0">Not connected</option>
<option [ngValue]="1">Connected</option>
</select>
If you want cast it within formChanged() method (Which you haven't provided yet).
You should use + symbol as shown below,
formChanged(): void {
selected.isConnected = +selected.isConnected;
...
}
No, sadly you're forced to parse it on your own in the formChanged() method, since you always get a string back from the select.
You could try it with something like this:
formChanged(): void {
selected.isConnected = parseInt(selected.isConnected);
// ...
}
You can send a Number variable to select and assign the value for that select element. Then if you want to capture the value when it changes, you can add (change) event to select and retrieve the value as shown below.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<select value="{{isConnected}}" (change)="printConnected($event.target.value)" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
<div *ngIf="changed">You've selected {{isConnected}}<div>`
})
export class AppComponent {
isConnected : number = 1;
changed : boolean = false;
printConnected(value){
this.isConnected = value;
this.changed=true;
}
}
You can view an example at http://plnkr.co/edit/xO2mrTdpTGufkgXqdhYD?p=preview
I am using reactive bindings and do not want to use [(ngModel)]. Instead I created a piped observable that uses JSON.parse(value) (because +value doesn't handle "null"):
*.component.html:
<div class="col-lg-4 form-group">
<label>Group Type</label>
<select class="form-control" (change)="groupType$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let groupType of filterData.groupTypes" [value]="groupType.id">{{groupType.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group" *ngIf="filteredGroups$ | async as groupOptions">
<label>Group</label>
<select class="form-control" (change)="group$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let group of groupOptions" [value]="group.id">{{group.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group">
<label>Status</label>
<select class="form-control" (change)="status$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let status of filterData.statuses" [value]="status.id">{{status.label}}</option>
</select>
</div>
*.component.ts:
group$ = new BehaviorSubject<string>(null);
groupId$ = this.group$.pipe(
map((groupId: string) => JSON.parse(groupId) as number)
);
groupType$ = new BehaviorSubject<string>(null);
groupTypeId$ = this.groupType$.pipe(
map((typeId: string) => JSON.parse(typeId) as number)
);
status$ = new BehaviorSubject<string>(null);
statusId$ = this.status$.pipe(
map((statusId: string) => JSON.parse(statusId) as number)
);
[ngValue] is intended for objects. It generates an artificial option value even for numeric constants. For those who might be concerned about tests or readability, you can expand two way binding microsyntax
<select [ngModel]="selected.isConnected"
(ngModelChange)="selected.isConnected=$event && +$event" id="etat">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>