How do I prepopulate the value of Select List in Bootstrap? - sql

I am using bootstrap framework to create a simple form that will be used to edit a SQL db record. To be concise, I have only posted a small snippet of code, a Select List input only. How do I automatically set a specific value from the list? I expected that I could use
<select class="form-control" id="..... value="Option1">
but that did not work. My ultimate outcome is to set the value using a SQL query.
<!--- Location Drop Down--->
<form class="form-horizontal" role="form" method="post" action="post_record.php">
<div class="form-group">
<label for="inputLocation" class="col-sm-2 control-label">Location</label>
<div class="col-sm-4">
<select class="form-control" id="inputLocation" name="inputLocation" value="Option1">
<option value="0">Please Select</option>
<option value="1">Option1</option>
<?php
$servername = "localhost";
$username = "*********";
$password = "*********";
$dbname = "**********";
// Create Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//Check connection
if (!$conn) {
trigger_error("Connection failed: " . mysqli_connect_error());
}
if ($conn) {
echo "success";
}
$stmt = "SELECT DISTINCT `ACT_LOCATION` FROM `actual_data`";
$result = mysqli_query($conn,$stmt) or die(mysqli_error());
while(list($category) = mysqli_fetch_row($result)){
echo '<option value="'.$category.'">'.$category.'</option>';
}
?>
</select>
</div>
</div>

Add attribute selected="selected" for the <option> that you want to be default selected option :
<option value="1" selected="selected">Option1</option>

Related

Jetstream User Profile Update: problems passing $input[] field using Livewire form input

I added some custom fields to the User Model and it stores them perfectly during registration (country_id, city_id, and state_id), but I am having problems with the profile management/update:
The fields seem to update only when using the jetstream components as input but NOT when I use my dropdown select option input
<x-jet-input id="cap" type="text" class="mt-1 block w-full" wire:model.defer="state.cap" />
So for instance this would update the $input['cap'] key but the "country_id" field from my livewire script does not update the $input['country_id'] ...
<select wire:model="selectedCountry" id="country_id" name="country_id">
<option value="{{$user->country_id}}"> {{$user->country->name}} </option>
#foreach($countries as $country)
<option value="{{$country->id}}"> {{$country->name}} </option>
#endforeach
</select>
<x-jet-input-error for="country_id" class="mt-2" />
To display or hide fields for instance I update the variables such as $SelectedCountry
The Country/City/State fields are displayed using a livewire script that hides or shows a given select dropdown and runs queries only when needed (if a Country has states/regions, it shows them otherwise it shows only the cities from the selected country etc).
If I submit though, the $input['country_id'] key is not changing though and it just keeps the previous value with which I registered.
I assume the jetstream component would do using wire:model.defer="state.country_id" for instance but again I can not use it because is just a text input... any ideas? 😬
Update-Profile-information-Form
...
<div class="col-span-6 sm:col-span-4">
<x-jet-label for="cap" value="{{ __('Postal Code') }}" />
<x-jet-input id="cap" type="text" class="mt-1 block w-full" wire:model.defer="state.cap" />
<x-jet-input-error for="cap" class="mt-2" />
</div>
<div class="col-span-6 sm:col-span-4">
<x-jet-label for="address" value="{{ __('Address') }}" />
<x-jet-input id="address" type="text" class="mt-1 block w-full" wire:model.defer="state.address" />
<x-jet-input-error for="address" class="mt-2" />
</div>
<div class="col-span-6 sm:col-span-4">
#livewire('edit-address', ['user' => Auth::user()])
</div>
...
edit-address.blade.php (view)
<div>
...
<x-jet-label for="country_id" value="{{ __('Country') }}" />
<select wire:model="selectedCountry" id="country_id" name="country_id">
<option value="{{$user->country_id}}"> {{$user->country->name}} </option>
#foreach($countries as $country)
<option value="{{$country->id}}"> {{$country->name}} </option>
#endforeach
</select>
<x-jet-input-error for="country_id" class="mt-2" />
</div>
...
EditAdress.php (livewire script)
class EditAddress extends Component
{
public $countries;
public $states;
public $cities;
public $selectedCountry = null;
public $selectedState = null;
public $selectedCity = null;
public $test = null;
public $user = null;
public function mount(User $user, $selectedCity = null){
$this->countries = Country::all();
$this->states = collect();
$this->cities = collect();
$this->selectedCity = $selectedCity;
if (!is_null($selectedCity)) {
$city = City::with('state.country')->find($selectedCity);
if ($city) {
/*if ($this->states->isEmpty()===1){
$this->cities = City::where('country_id', $this->selectedCountry);
}*/
$this->cities = City::where('state_id', $city->state_id)->get();
$this->states = State::where('country_id', $city->state->country_id)->get();
$this->selectedCountry = $city->state->country_id;
$this->selectedState = $city->state_id;
}
}
}
public function render()
{
return view('livewire.edit-address');
}
public function updatedSelectedCountry($country)
{
;
$this->states = State::where('country_id', $country)->get();
$this->selectedState = NULL;
if(!$this->states->count()){
$this->cities = City::where('country_id', $country)->get();
}
}
public function updatedSelectedState($state)
{
if (!is_null($state)) {
$this->cities = City::where('state_id', $state)->get();
}
else{
$this->cities = City::where('country_id', $this->selectedCountry);
}
}
}

Inserting into the db with PDO

<form action="uploads.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload</legend><br/>
Title: <input type="text" name="name" id="name" class="name" required> <br/><br/>
<textarea name="description" rows="6" cols="35" maxlength="120"></textarea><br/>
<input type="file" id="file" name="file[]" required multiple> <br/>
<input type="submit" id="submit" name="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will appear here.
</div>
<?php
// configuration
$dbhost = "localhost";
$dbname = "blog";
$dbuser = "root";
$dbpass = "pass";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$name = 'name';
$mime = 'mime';
$data = 'data';
$size = 'size';
$description = 'description';
$created = 'created';
$url = 'url';
// query
$sql = "INSERT INTO videos (name,mime,data,size,description,created,url) VALUES (:name,:mime,:data,:size,:description,:created,:url)";
$q = $conn->prepare($sql);
$q->execute(array(':name'=>$name,
':mime'=>$mime,
':data'=>$data,
':size'=>$size,
':description'=>$description,
':created'=>$created,
':url'=>$url));
?>
I'm not so good with PDO, I can get videos to upload to my db, but I can't take in a name or anything. It just shows: name, description, size is 0 and etc. I've watched a few tutorials, but none of them show how to add it by what the user names it or describes it as, only what they put into the values goes to the database. I've also searched around on here and many other websites, but no luck.

how to set selected dropdown list in html

this is my code for dropdown list,plz guide me.
<div class = "form-inline">
<label class = "">Situation</label>
<select selected="" name="sit" id="situ" class='form-control'style="margin-left: 30px; width: 145px;">
<option value="" >select</option>
<?
if ($situation != '') {
$revise = $situation;
}
foreach ($revise as $row):
?>
<option value="<?= $row['id']; ?>"><?= $row['situation']; ?></option>
<? endforeach; ?>
</select>
</div>
For the item you want selected for a dropdown list, add the attribute selected.
Eg.
<select>
<option value="0">0</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
</select>
In this case, 1 will be selected.
To get the value of this dropdown after form submit, it depends on the method of your form being POST or GET.
In this example, I'm assuming it's POST. <form method="POST">
<div class = "form-inline">
<label class = "">Situation</label>
<select selected="" name="sit" id="situ" class='form-control'style="margin-left: 30px; width: 145px;">
<option value="" >select</option>
<?
if (isset($_POST['sit']))
$selected = $_POST['sit'];
if ($situation != '') {
$revise = $situation;
}
foreach ($revise as $row):
$selectedHTML = '';
if (isset($selected) && $row['id'] == $selected)
$selectedHTML = ' selected="selected"';
?>
<option value="<?= $row['id']; ?>"<?= $selectedHTML; ?>><?= $row['situation']; ?></option>
<? endforeach; ?>
</select>
</div>
You can try something like this.
if (isset($_POST['sit']))
$selected = $_POST['sit'];
What this does is check if $_POST['sit'] value is found. If yes then we'll make that $selected, else we'll leave it.
$selectedHTML = '';
if (isset($selected) && $row['id'] == $selected)
$selectedHTML = ' selected="selected"';
And then in the foreach loop, we will first initialize $selectedHTML as empty string. It will not add anything to <option> unless it got its value changed.
We will check if $selected is defined or not and if it is, we will check if the current value of $row['id'] within the foreach loop is equal to the submitted value which is $selected. If so, we will set $selectedHTML which will add selected="selected" only to the current <option>.

Updating select box with Ajax, JavaScript and Webmatrix

I'm very new to Ajax.
What I'm trying to achieve, I would imagine, is fairly common. I have 2 dropdown boxes, referencing my database, these are called "area" and "resort". The idea is that when i choose and area from the first boxes, it ONLY shows resorts within that area in the second box.
Here is my form:
<div id ="homepage-form-div" class="row">
<form id ="homepage-form"action=" /Search1.cshtml">
<div class="span3">
<label>Area:</label>
<select name="area">
<option value="">Any</option>
#foreach(var row in qlistarea){
<option value="">#row.AreaName</option>
}
</select>
</div>
<div class="span3">
<label>Resort:</label>
<select name="resort">
<option value="">Any</option>
#foreach(var row in qlistresort){
<option value="">#row.ResortName</option>
}
</select>
</div>
<button type="submit" class="btn btn-default" value="Submit" style="p">Go!</button>
</form>
</div>
I thought it might be useful to see my current SQL code:
var listarea = "SELECT DISTINCT AreaName FROM ResortInfo";
var qlistarea = db.Query(listarea);
var listresort = "SELECT DISTINCT ResortName FROM ResortInfo";
var qlistresort = db.Query(listresort);
I'm guessing I'll need to somehow add a "+ WHERE AreaName = something" to the second query, dependant on the result of the AJAX call right?
Ok, you are using Razor syntax? Lets the show begin. And hey, arent you the same guy?
First I will tell you the basics of what I use.
I use the click keyup or change events.
I update the content of the body on ajax calls.
You need some basic tutorials buddy! Learn ASP.NET, then Learn jQuery Ajax! That will be simple.
My humble request to you:
Buddy please atleast once search for the code, before pasting it here. You will get alot of downvotes and might get blocked for posting more questions here. Please search for questions first. However this is the code.
Ok, to create the code:
I am going to post the code that works for me. Ok?
Here is the main page content:
#{
Layout = "~/_SiteLayout.cshtml";
}
<script>
$(document).ready(function () {
$('#area').change(function () {
$.ajax({
url: "testtworesult",
data: "type=resortupdate&resval=" + $('#area').val(),
success: function (data) {
$('#resort').html(data);
}
});
});
$('.btn').click(function () {
$.ajax({
url: "testtworesult",
data: "type=submit&area=" + $('#area').val() + "&res=" +
$('#resort').val(),
success: function (data) {
$('#result').html(data);
}
});
});
});
</script>
<div id ="homepage-form-div" class="row">
<div class="span3">
<label>Area:</label>
<select id="area">
<option value="">Any</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<div class="span3">
<label>Resort:</label>
<select id="resort">
<option value="">Any</option>
<option value="Love">Love</option>
<option value="Hate">Hate</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Submit" style="p">Go!</button>
<div style="font-weight: bold; margin-top: 20px;" id="result"></div>
</div>
Then the ajax page:
#{
var db = Database.Open("StayInFlorida");
var getresortval = Request.QueryString["resval"];
var type = Request.QueryString["type"];
var res = Request.QueryString["res"];
var area = Request.QueryString["area"];
var listresort = "SELECT DISTINCT ResortName FROM ResortInfo WHERE AreaName = '#0'";
var qlistresort = db.Query(listresort, getresortval);
if(type == "resortupdate") {
if(getresortval == "Kissimmee") {
Response.Write ("<option value='kissimmee'>Kissimmee</option");
}
if(getresortval == "Davenport") {
Response.Write("<option value='davenport'>Davenport</option");
}
} else if(type == "submit") {
Response.Write(#"You selected the Resort!<br>
Your area was: " + area + #".<br>
And your resort was: " + res + #". Hope you have a great trip!");
}
}
This won't save the content in Database, you will need to use INSERT INTO for that. Then you will require SELECT * FROM to select the data. I have simply used Response.Write().
Good luck.
For the AJAX call, you need a function AJAX can call which houses the Resort query after the user selects an Area. I'm not familiar with Razor or Webmatrix, so here's a pseudo-function (based on PHP) that you might be able to translate to your environment:
if (isset($_POST['area'])) set_resort(); /*AJAX will set $_POST['area'], then do function that returns output to AJAX*/
. . .
function set_resort() {
var listresort = "SELECT DISTINCT ResortName FROM ResortInfo WHERE AreaName = " $_POST['area']; /*make sure you escape that variable, however you do that in your syntax*/
var qlistresort = db.Query(listresort);
var resortArray = array(); /*or however you make arrays in your syntax*/
#foreach(var row in qlistresort){
resortArray[] = #row.ResortName; /*append each resort name to array*/
}
echo json_encode(#resortArray); /*JSON is preferred way to echo array back to AJAX*/
}
Your HTML would look like...
<div id ="homepage-form-div" class="row">
<form id ="homepage-form"action=" /Search1.cshtml">
<div class="span3">
<label>Area:</label>
<select id="areaSelect" name="area"> <!-- add an ID for easier jQuery selection -->
<option value="">Any</option>
#foreach(var row in qlistarea){
<option value="">#row.AreaName</option>
}
</select>
</div>
<div class="span3">
<label>Resort:</label>
<select id="resortSelect" name="resort"> <!-- add an ID for easier jQuery selection -->
<option value="">Any</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Submit" style="p">Go!</button>
</form>
</div>
Finally, your jQuery AJAX call would be like:
$('#areaSelect').on('change', function() {
var str = $(this).serialize();
$.ajax({
type: 'POST',
url: /*URL of your page*/
dataType: 'json',
data: str,
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown + '\n' + textStatus);
},
success: function(msg) {
$.each(msg, function(index, value) {
$('#resortSelect').append('<option value=' + index + '>' + value + '</option>'; /*add each resort from the set_resort() query to the resort select input*/
});
});
});

How to pass id from a dynamic dropdown menu selection?

<?php
include ("Includes/DB_config.php");
//Define dropdown menu
echo "<select name=\'ProjectName\'>\n";
echo "<option value=\"NULL\">Select your project</option>\n";
//Select data from the database
$result = mysql_query("SELECT ProjectID,ProjectName FROM tb_project");
//Fetch data & Populate dropdown menu
while($row=mysql_fetch_array($result))
{
$pjt_id = $row['ProjectID'];
$pjt_name = $row['ProjectName'];
echo "<option value=\"$pjt_id\">$pjt_name</option>\n";
}
echo "</select>";
?>
Edit
You can use javascript to achieve this.
JAVASCRIPT
function upperCase(x)
{
var e = document.getElementById("editButton");
e.href = "/www/gdis_sys_test/Project_Setup_Display.php?id=" + x;
}
HTML
<select onchange="upperCase(this.value)">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="4">Value 4</option>
</select>
<a id="editButton" href="/www/gdis_sys_test/Project_Setup_Display.php?id=1">Edit</a>
Example: http://jsfiddle.net/brenjt/WaA92/