I'm trying to get the value of selected select using localStorage.getItem() but it gives me an error.
Here is my select:
<div class="field">
<label>Work Area</label>
<select class="ui fluid dropdown work_area" id="work_area" name="work_area">
<option selected value="">Select Work Area.</option>
<?php selectWorkArea(); ?>
</select>
</div>
Here is my PHP function
function selectWorkArea(){
$conn = New Connection;
$sql = "SELECT DISTINCT work_area FROM machine ORDER BY work_area ASC";
$qry = $conn->select($sql,NULL,'0129180857');
while($row= $qry->fetch(PDO::FETCH_OBJ)){
$work_area = $row->work_area;
echo "<option data-value='$work_area' >$work_area</option>";
}
}
here is my Javascript
var select = document.querySelector(".work_area");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected) {
select.value = lastSelected;
}
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('workarea', lastSelected);
}
And i got this error:
Error image click here
But when i tried to change my select into this it works totally fine
<div class="field">
<label>Work Area</label>
<select class="ui fluid dropdown work_area" id="work_area" name="work_area">
<option selected value="">Select Work Area.</option>
<option data-value="1">1</option>
<option data-value="2">2</option>
</select>
</div>
click here to see the image
I solved this problem by removing the data in the data-value attribute. And after, i tried to refresh the page and the value of select is removed. that is not good. the solution is modify the javascript, here is the modification:
Javascript code:
$('#work_area').val(localStorage.workarea);
localStorage.setItem('workarea','');
var select = document.querySelector(".work_area");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected) {
select.value = lastSelected;
}
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem('workarea', lastSelected);
}
html code:
<div class="field">
<label>Work Area</label>
<select class="ui fluid dropdown work_area" id="work_area" name="work_area">
<option selected value="">Select Work Area.</option>
<?php selectWorkArea(); ?>
</select>
</div>
PHP function code:
function selectWorkArea(){
$conn = New Connection;
$sql = "SELECT DISTINCT work_area FROM machine ORDER BY work_area ASC";
$qry = $conn->select($sql,NULL,'0129180857');
while($row= $qry->fetch(PDO::FETCH_OBJ)){
$work_area = $row->work_area;
echo "<option value='$work_area' >$work_area</option>";
}
}
Check for null before use.
if (localStorage.getItem("select") === null) {
var lastSelected = localStorage.getItem('select');
select.value = lastSelected;
}
Related
I have two dropdown here and i have issue with Task Type dropdown.
i need a JS to call function categoryChange , search and select a option $Task_type = Value.From.DB, when <?php if ($update == true): ?>
I just start to learning PHP and buil a website for my self and i don't know so much about JS at this point.
HTML Code:
<!-- Start Category and task type code-->
Category:<select id="continent" name="category" onchange="categoryChange(this);" class="form-control" required>
<option value="empty">Select a Category</option>
<option value="Support">Support</option>
<option value="Workplace">Workplace</option>
<option value="New Employee">New Employee</option>
<option value="Resigned Employee">Resigned Employee</option>
<option value="Installation">Installation</option>
<option value="Meetings">Meetings</option>
<option value="Update/Maintenance">Update/Maintenance</option>
<option value="Test">Test</option>
<option value="New Projects">New Projects</option>
<?php if ($update == true): ?>
<script type="text/javascript">
function setSelectedIndex(s, valsearch) {
// Loop through all the items in drop down list
for (i = 0; i < s.options.length; i++) {
if (s.options[i].value == valsearch) {
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
setSelectedIndex(document.getElementById("continent"),"<?php echo $category; ?>");
</script>
<?php endif ?>
</select>
Task Type:<select id="category" name="task_type" class="form-control" required>
<option value="0">Select a Task Type</option>
<?php if ($update == true): ?>
<script type="text/javascript">
categoryChange("<?php echo $category; ?>");
</script>
<?php endif ?>
</select>
JS Code:
//<![CDATA[
// array of possible countries in the same order as they appear in the category selection list
var categoryLists = new Array(4)
categoryLists["empty"] = ["Select a category"];
categoryLists["Support"] = ["Fast Support", "Remote Desktop", "Printer Maintenance"];
categoryLists["Workplace"] = ["Move Desk", "New Employee preparation"];
categoryLists["New Employee"] = ["Create User"];
categoryLists["Resigned Employee"]= ["Disable user", "Delete user"];
categoryLists["Installation"]= ["Meeting rooms", "Defect Desk/Table", "Prepare Devices", "Reinstallation computer", "Power loss / server breakdown", "New headset"];
categoryLists["Meetings"]= ["IT Internal Meeting", "IT Education"];
categoryLists["Update/Maintenance"]= ["Monthly", "Software Maintenace", "Vmware", "Server OS upgrades/Migrations", "Server Physical upgrades"];
categoryLists["Test"]= ["Windows 10", "Software"];
categoryLists["New Projects"]= [" (Lasernet, Skype, Bitabiz, Astrow)", "Investigate new projects", "New IT securities/scripts"];
/* categoryChange() is called from the onchange event of a select element.
* param selectObj - the select object which fired the on change event.
*/
function categoryChange(selectObj) {
// get the index of the selected option
var idx = selectObj.selectedIndex;
// get the value of the selected option
var which = selectObj.options[idx].value;
// use the selected option value to retrieve the list of items from the categoryLists array
cList = categoryLists[which];
// get the category select element via its known id
var cSelect = document.getElementById("category");
// remove the current options from the category select
var len=cSelect.options.length;
while (cSelect.options.length > 0) {
cSelect.remove(0);
}
var newOption;
// create new options
for (var i=0; i<cList.length; i++) {
newOption = document.createElement("option");
newOption.value = cList[i]; // assumes option string and value are the same
newOption.text=cList[i];
// add the new option
try {
cSelect.add(newOption); // this will fail in DOM browsers but is needed for IE
}
catch (e) {
cSelect.appendChild(newOption);
}
}
}
//]]>
From my device table, I have device id, device name and image id and my drop down currently displays the the respective devices. How can I display the image id that is respective to the device selected on. I've tried messing around the code but I'm still going no where.
<select class = "form-control" id="changeDevice" name="changeDevice" >
<option value= " -- select a device -- " disabled selected value> -- select a device -- </option>
<?php
foreach($device as $devicedrop){
?>
<option value="<?php echo $devicedrop['id'] ?>">
<?php echo $devicedrop['name'] ?> </option>
<?php
}
?>
</select>
<input type = "text" id="text"></input>
<script>
$('#changeDevice').find('option:selected').text();
var text = $(this);
$('#text').prop(text);
</script>
take 'selectedIndex' property of select element. and...
<script>
var device = $('#changeDevice');
var selectedIndex = device.prop('selectedIndex');
var text = $('option', device).eq(selectedIndex).text().trim();
$('#text').val(text);
</script>
---- Edit
Well. It's you again Lotse. :)
You can store your data into DOM element (option) like...
<?php
$rows = ...;
foreach($rows as $row) {
printf('<option value="%d" data-image-id="%d" data-image-name="%s" data-device-name="%s">%s</option>', $row['id'], $row['image_id'], $row['device_name'], ...);
}
?>
this code generate HTML as
<select id="#device_option">
<option value="1" data-image-id="32" data-image-name="sample-01.jpg" data-device-name="some name">...</option>
...
</select>
then, now you can pick up any data from jQuery's $.data(key) function.
<script>
$(function() {
$('device_option').on('change', function() {
var options = $('option:selected', this); // take care when multiselect on
var val = $(this).val(); // or options.val()
var image_id = options.data('image-id');
var image_name = options.data('image-name');
var device_id = options.data('device-name');
var text = options.text().trim();
// you can poll data from DOM
});
});
</script>
http://www.w3schools.com/tags/att_global_data.asp
https://api.jquery.com/selected-selector/
https://api.jquery.com/data/
I have a list of countries. I use the GeoNames's function for detect the country where we are and display it in the list. It works.
However, I'd like to retrieve this value, I try to display it but only the first value appears.
Code :
<!-- Code HTML countries list -->
<select id="countrySelect" name="country">
<?php
$reponse = $bdd->query('SELECT * FROM pays');
echo '<OPTION VALUE="">Pays</OPTION>';
while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC))
{
echo '<OPTION VALUE="'.$donnees["id_pays"].'">'.$donnees["pays"].'</OPTION>';
echo $donnees["pays"];
}
?>
Code Javascript :
function setDefaultCountry() {
var countrySelect = document.getElementById("countrySelect");
for (i=0;i< countrySelect.length;i++) {
if (countrySelect[i].value == geonamesUserIpCountryCode) {
countrySelect.selectedIndex = i;
}
}
}
/* I want to display the country selected here !!!!!!*/
var c = document.getElementById("countrySelect");
alert(c.options[c.selectedIndex].text);
i made a little change to your code, for demonstration purposes.
The way to do it is to set an OnChange Event on the Select.
If you then choose an option, it will fire the event.
function setDefaultCountry() {
var countrySelect = document.getElementById("countrySelect");
for (i = 0; i < countrySelect.length; i++) {
if (countrySelect[i].value == geonamesUserIpCountryCode) {
countrySelect.selectedIndex = i;
}
}
check();
}
function check() {
var sele = document.getElementById("countrySelect");
alert(sele[sele.selectedIndex].text);
}
<!-- Code HTML countries list -->
<select id="countrySelect" name="country" onchange="check()">
<OPTION VALUE="Test1">test1</OPTION>
<OPTION VALUE="Test2">test2</OPTION>
<OPTION VALUE="Test3">test3</OPTION>
<OPTION VALUE="Test4">test4</OPTION>
<OPTION VALUE="Test5">test5</OPTION>
EDIT:
just add the following in your body.onload routine:
setDefaultCountry();
Greetz :)
A dropdown select box is populated from a database and the selected option is matched against a variable $comp_cntry currently on the page:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
Then later on a telephone prefix (dialling code) box is populated from the same database, matching the dialling code to the country:
<?php
// Get Dialling Codes
$telephone_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country = $tq['country_name'];
// Show Prefix
if ($country == $comp_cntry) {
$prefix = $tq['dialling_code'];
}
}
?>
<input type="text" name="telephone_prefix" value="+<?=$prefix?>" readonly>
How, using JavaScript, can I get the telephone prefix to automatically change on page when a new option is chosen from the country dropdown? I have no real knowledge of JavaScript at all, unfortunately, but assume I would need to somehow convert my PHP associated array in to JSON so that I can use it?
I know I haven't provided any JavaScript code to show that I've made a start on this part of the problem, but if someone could point me in the right direction that would be swell.
Disclaimer: please ignore my terrible use of the mysql_ extension
I would add a data attribute (here it might be called data-prefix) to the element, like
<option value='country' data-prefix='+44'/>
and get this when the onChange event is fired for the select. In jQuery you could do something like
$('[name="country"]').change(function(){
$('[name="telephone_prefix"]').val($(this).find(':selected').data('prefix'));
});
which would update the value accordingly.
I would say the best way of doing this would be joining the two PHP codes like this:
<select name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $cq['dialling_code'];
// Select Current Country
echo "<option data-prefix='{$prefix}' value='{$country}' ";
if($country == $comp_cntry) echo "selected";
echo ">{$country}</option>";
}
?>
</select>
<input type="text" name="telephone_prefix" value="" readonly>
And this would return a list of the countries in a dropdown each with a data-prefix attribute of the appropriate prefix that they have.
We would then need to trigger jQuery on change and update the value, and this would look something like:
$("select[name=country]").on('change', function() {
var prefix = $("option:selected", this).attr('data-prefix');
$("input[name=telephone_prefix]").attr('value', prefix);
})
And this would have the following effect: http://jsfiddle.net/Tm75y/1/
I hope that's what you need.
Simply pass the prefix as an attribute of the select options:
<select id="country-select" name="country">
<option value="--" disabled>Please Select...</option>
<option value="--" disabled>- - - - -</option>
<?php
// Populate Country Dropdown
$country_query = mysql_query("SELECT country_name, dialling_code FROM ukipdata.ukip_countries
ORDER BY country_name ASC");
while ($cq = mysql_fetch_assoc($country_query)) {
$country = $cq['country_name'];
$prefix = $tq['dialling_code'];
// Select Current Country
if ($country == $comp_cntry) {
?>
<option value"<?=$country?>" prefix="<?=$prefix?>" selected><?=$country?></option>
<?php
}
else {
?>
<option value"<?=$country?>"><?=$country?></option>
<?php
}
}
?>
</select>
<input id="prefix-input" type="text" name="telephone_prefix" value="" readonly>
JAVASCRIPT
Then add a change handler to your select to get the prefix attribute of the selected option and set the text input:
$(function(){
$("#country-select").change(function(){
var prefix = $(this).find("option:selected").attr("prefix");
$("#prefix-input").val(prefix);
});
});
My suggestion would be to saving a javascript object which maps countries to phone codes, so when your country select has a change, you can trigger a change to the telephone prefix via javascript.
So let's assume you have a map (associative array) in javascript that is something like this:
$country_to_phone_prefix_map = array(
'country name A' => 'phone prefix A',
'country name B' => 'phone prefix B',
...
);
This could be built in your query while loop:
$country_to_phone_prefix_map = array();
while ($tq = mysql_fetch_assoc($telephone_query)) {
$country_to_phone_prefix_map[$tq['country_name']] = $tq['dialing_code'];
}
Then when rendering the page, inject this map into javascript
<script type="text/javascript">
var countryToPhonePrefixMap = <?php echo json_encode($country_to_phone_prefix_map); ?>;
</script>
Now, you build a change event listener on the country dropdown to change the value:
$('select[name="country"]').change(function() {
// get phone prefix from map
var selectedCountry = $(this).val();
var phonePrefix = countryToPhonePrefixMap[selectedCountry];
// change value of telephone prefix input
$('input[name="telephone_prefix"]').val(phonePrefix);
}
i have a select input that get options from database retailer_id, what i need it, when the admin select a retailer on this select input, i'll have a new one with the retailer_slug, and then, when the admin create or update, will sen to database the retailer_id and the retailer_slug on hidden input. my code is:
EDITED
<select class="textbox2" id="retailer_id" name="retailer_id">
<option value="">--- Please select store ---</option>
<?php
$sql_retailers = smart_mysql_query("SELECT * FROM cashbackengine_retailers WHERE status='active' ORDER BY title ASC");
while ($row_retailers = mysql_fetch_array($sql_retailers))
{
if ($retailer_id == $row_retailers['retailer_id']) $selected = " selected=\"selected\""; else $selected = "";
echo "<option data-slug=\"".$row_retailers['slug_title']."\" value=\"".$row_retailers['retailer_id']."\"".$selected.">".$row_retailers['title']."</option>";
}
?>
</select>
<input type="text" name="slug" id="slug" value=""/>
<script type="text/javascript">
$(document).ready(function() {
$('#retailer_id').on('change', function() {
var $selected = $('#retailer_id option:selected');
$('input[name=slug]').val($selected.data('slug'));
});
});
</script>
If I understand correctly, this is one thing you could do:
PHP
<select class="textbox2" id="retailer_id" name="retailer_id">
<option value="">--- Please select store ---</option>
<?php
$sql_retailers = smart_mysql_query("SELECT * FROM cashbackengine_retailers WHERE status='active' ORDER BY title ASC");
while ($row_retailers = mysql_fetch_array($sql_retailers))
{
if ($retailer_id == $row_retailers['retailer_id']) $selected = " selected=\"selected\""; else $selected = "";
echo "<option data-slug=\"".$row_retailers['retail_slug']."\" value=\"".$row_retailers['retailer_id']."\"".$selected.">".$row_retailers['title']."</option>";
}
?>
</select>
<input type="hidden" name="retailer_slug"/>
jQuery
$('#retailer_id').on('change', function() {
var $selected = $('#retailer_id option:selected');
$('input[name=retailer_slug]').val($selected.data('slug'));
});
So basically, the idea here is that you save the retailer_slug value as a data- attribute on each <option>. Then when the selected option is changed, the retailer_slug value is copied over to the hidden input.