Automatically Preselect Dropdown Using Javascript - javascript

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);
}
}
}
//]]>

Related

How to get the value of selected select using localStorage

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;
}

How to make Jquery coded Dynamic Dropdown Menus work in harmony with PHP GET variables

I have a Dynamic Dropdown Menus for 3 Game Types that is coded with jquery and php. For the Game Type Dropdown, if Baseball is selected the corresponding League will show only Baseball Leagues, if Soccer is selected the corresponding League will show only Soccer Leagues and so on.
This was achieved using jquery.
I am forced to use $("#game_type_id").change(); so that for whatever game type is selected, the corresponding league will be shown. But the disadvantage is whatever you choose on the League Dropdown after the page submit the selection never retains, because of the forced execution of $("#game_type_id").change(). But if we're going to check if the selection is correct, I can say yes, thru the php link, such as game_type_id=1&q_lid=64, it changes.
Is there a way to make this work in harmony with the PHP code?
HTML (Smarty PHP Framework)
Game Type:
<select id="game_type_id" name="game_type_id" style="width:100px;margin-bottom:5px; margin-top: 10px;margin-left: 5px;">
<option value="1" {if $game_type_id == 1}selected="selected" {/if}> Baseball</option>
<option value="2" {if $game_type_id == 2}selected="selected" {/if}> Soccer </option>
<option value="3" {if $game_type_id == 3}selected="selected" {/if}> Flexi </option>
</select>
League:
<select name="q_lid" id="q_lid">
<option value="0">-- Select --</option>
{foreach from=$league_list item=league}
<option class="league_group league_group_{$league.game_type_id}" value="{$league.league_id}" {if $q_lid==$league.league_id} selected="selected" {/if}>{$league.league_short_name}</option>
{/foreach}
</select>
<select id="fl_ctg" name="fl_ctg">
<option value="0" > --Flex Category -- </option>
{foreach $f_bet_type as $val}
<option value="{$val.category_id}" {if $fl_ctg == $val.category_id}selected="selected"{/if}>{$val.category_full_name}</option>
{/foreach}
</select>
<input type="submit" id="btn_search" name="btn_search" value="Search" style="cursor:pointer;width:50px;"/>
Js code
$(document).ready(function(){
$(function () {
$("#game_type_id").change();
});
var options = $("#q_lid").children(".league_group").clone();
//Game Type Dropdown
$("#game_type_id").bind("change",function() {
var type = $(this).val();
$("#q_lid").prop("disabled",false);
if(type == 3)
$("#fl_ctg").show();
else
{
$("#fl_ctg").hide();
$("#fl_ctg").val(0);
}
// select league according to game type
$(".league_group").prop('selected', false)
.remove();
options.clone()
.filter('.league_group_'+this.value)
.appendTo('#q_lid')
.first()
.prop('selected', true);
$("#q_lid").change();
});
//League Dropdown
$("#q_lid").bind("change",function() {
var gtype = $("#game_type_id").val();
if(gtype==3)
$("#fl_ctg").show();
else
{
$("#fl_ctg").hide();
$("#fl_ctg").val(0);
}
});
$('#btn_search').click(function()
{
var q_lid = $('#q_lid').val();
var fl_ctg = $('#fl_ctg').val();
var q_str = '';
if(q_lid.length > 0){
q_str += '&q_lid='+q_lid;
}
if(fl_ctg.length > 0){
q_str += '&fl_ctg='+fl_ctg;
}
if(game_type_id.length > 0){
q_str += '&game_type_id='+game_type_id;
}
});
PHP code
if( isset($_GET['q_lid']) && !empty($_GET['q_lid']) ){
$q_lid = mysql_real_escape_string(trim($_GET['q_lid']));
}
if(isset($_GET['fl_ctg']) && $_GET['fl_ctg']<>0)
{
$fl_ctg = mysql_real_escape_string(trim($_GET['fl_ctg']));
}
$smarty->assign('q_lid',$q_lid);
$smarty->assign('fl_ctg',$fl_ctg);
$sql_team_orderby = "league_priority DESC";
$league_data = LeagueClass::getLeagueDetails('', '', '',$sql_team_orderby, '');
$smarty->assign('league_list', $league_data);
$f_sql_category="SELECT * FROM category ";
$f_category_result=Db::getInstance()->queryExecuteFull($f_sql_category, $array = true);
$smarty->assign('f_bet_type', $f_category_result);
You could do this dynamically with only PHP
<?php
$game_type_id = $_GET['game_type_id']; // Game ID
$league_list = array('league1', 'league2', 'league3'); // The list of all leagues
$chosen_league = $_GET['league']; // whatever the league is
?>
Game type
> Baseball
> Soccer
> Flexi
League
<select name="q_lid" id="q_lid">
<option <?php if ($chosen_league == '') echo 'selected' ?> value="" disabled>Select...</option>
<?php
// Output all the league list with the chosen one
foreach($league_list as $option) {
printf(
"<option %s value='%s'>%s</option>\n",
$chosen_league == $option ? 'selected' : '',
$option, $option
);
}
?>
</select>

How do I echo a value (a price) when a bank is selected from a dropdown menu?

Essentially, when I select a bank from the list, I want to display a price next to it. For example if I select “Natwest” from the list it will show £20,000 next to it.
This is what I have so far:
<label>Banks</label>
<select id="myList">
<option value="1">Barclays</option>
<option value="2">HSBC</option>
<option value="3">LIoyds</option>
<option value="4">Natwest</option>
</select>
See thisfiddle
This can be done using Javascript
There is an onchange Event Attribute in HTML which executes a JavaScript when a user changes the selected option of a element
HTML
<label>Banks</label>
<select id="myList" onchange="myFunction()">
<option value="1">Barclays</option>
<option value="2">HSBC</option>
<option value="3">LIoyds</option>
<option value="4">Natwest</option>
</select>
<label id="demo"></label>
JS
function myFunction() {
var x = document.getElementById("myList").value;
if(x==1)
document.getElementById("demo").innerHTML = "£20,000";
else if(x==2)
document.getElementById("demo").innerHTML = "£30,000";
else if(x==3)
document.getElementById("demo").innerHTML = "£40,000";
else if(x==4)
document.getElementById("demo").innerHTML = "£50,000";
}
UPDATE
As #TaJP mentioned in his comments, using switch case would be more efficient.
Here is a fiddle using switch case.
here is a solution with jquery/ajax.
It request a Server-Side-PHP-Script and fetch necessary data (like prices) and display the result next to Select-Field.
HTML Stuff
<label>Banks</label>
<select id="myList">
<option value = "1">Barclays</option>
<option value = "2">HSBC</option>
<option value = "3">LIoyds</option>
<option value = "4">Natwest</option>
</select>
<span id="result"></span>
<script>
$( "#myList" ).change(function() {
// Send the data using post, in PHP you will get $_POST['bankId']
var posting = $.post('banks.php', { bankId: $(this).val() } );
posting.done(function( data ) {
$("#result").empty().append(data);
});
});
</script>
</body>
</html>
PHP Script (banks.php)
<?php
// file banks.php
$arrBankData = array('20,00 EUR','25,00 EUR','30,00 EUR','35,00 EUR');
if($_POST) {
if(isset($arrBankData[$_POST['bankId']]))
echo $arrBankData[$_POST['bankId']];
else
echo "Bank ID not found!";
}
?>

I fail to display the value of a select in JavaScript

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 :)

Update text input on select option change (where both are initially populated from a database)

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);
}

Categories