Run Function on default HTML Select with PHP And Javascript - javascript

I try to Run Default Function on HTML Select, but Default Function doesn't works for Default Selected Value, But it Works On User Select
<?php
$status_selected = 'A002';
?>
<!-- HTML Select 1 -->
<select id="state" class="l" name="state" onchange="Func()">
<option value="A001" <?php if($status_selected == "A001") echo "selected"; ?> data_item=" , StateA003 One, A003 State Two, A003 State Three">A001</option>
<option value="A002" <?php if($status_selected == "A002") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A002</option>
<option value="A003" <?php if($status_selected == "A003") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A003</option>
</select>
<!-- HTML Select 2 -->
<label for="city">Item : </label><select id="city" name="item" class="l" onchange="onSelected()">
<script>
function Func() {
var city = document.getElementById('item');
var state = document.getElementById('state');
var val=state.options[state.selectedIndex].getAttribute('data_item');
var arr=val.split(',');
item.options.length = 0;
for(i = 0; i < arr.length; i++) {
if(arr[i] != "") {
item.options[item.options.length] = new Option(arr[i],arr[i]);
}
}
}
function onSelected() {
var item = document.getElementById('item').value;
var state = document.getElementById('state').value;
console.log('Parent : ' + state+ ', Item : ' + item);
}
</script>
it load HTML Select One And then Select Item in HTML Select Two, But HTML Select Two Works Only By Manual User Select And Not Works For Default Programatically Value
Whole Of Codes Above Are On PHP File.
How i can fix it ?

Not sure if it is relevant, but maybe you want a chained select box? If not, please clarify your question, it's very hard to follow.
EDIT: So the real issue is selecting the right option by code. In that case, this is a duplicate of How do I programmatically set the value of a select box element using javascript?.
In your onload script(or just after the functions if the script is at the bottom of the page), also run Func(), then set the value for #city:
Func();
var state = document.getElementById('state'),
city = document.getElementById('city'),
selectedCity = state.getAttribute('data-selected-city');
if(selectedCity) {
city.value = selectedCity;
}
You need to store the selected city somewhere, my suggestion is to add it to the select:
<select id="state" data-selected-city="new-york">
<!--and so on--->
</select>
NOTE: setting a data attribute in HTML5 should begin with data-, not an underscore. So it's data-item="", not data_item="". That will give you a warning when running HTML validator.

Put Out Of PHP Tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
On Script Tag Put :
$(function() {
$("#state").on("change", Func());
});
After :
item.options[item.options.length] = new Option(arr[i],arr[i]);
put the code :
$(item).prop("selectedIndex",i);

Related

how to use the same drop down list in different web pages

I have the following drop down list and I would like to use it in several pages
<form action = "Unser Team.php" method = "post" name = "test">
<div class = "custom-select">
<div class = "select">
<select id ="custom-select" name = "custom-select" style="width:200px;" onchange = " this.form.submit();">
<option <?php if ($_POST['custom-select'] == 'Abteilung auswählen') print 'selected '; ?>value="Abteilung auswählen">Abteilung auswählen</option>
<option <?php if ($_POST['custom-select'] == 'TL-311') print 'selected '; ?> value="TL-311">TL-311</option>
<option <?php if ($_POST['custom-select'] == 'TP-271') print 'selected '; ?> value="TP-271">TP-271</option>
<option <?php if ($_POST['custom-select'] == 'TP-310') print 'selected '; ?> value="TP-310">TP-310</option>
<option <?php if ($_POST['custom-select'] == 'TP-270') print 'selected '; ?> value="TP-270">TP-270</option>
</select>
</div>
</div>
when the user selects an option I save it and I would like to see in the next page the option that has been selected is preselected and for its use the following code
in the home page:
var file;
function myFunction()
{
var mylist = document.getElementById("custom-select");
var mytext = mylist.options[mylist.selectedIndex].text;
window.file = mytext;
return window.file;
}
window.onload = function() {
var getInput = window.file;
localStorage.setItem("files",getInput);
}
for the other pages:
var myFile = localStorage.getItem("files");
window.onload = function() {
var ddValue= localStorage.getItem('files');
var dd= document.getElementById('custom-select');
for(var i = 0;i < dd.options.length;i++){
if(dd.options[i].value == ddValue ){
dd.options[i].selected = true;
break;
}
}
}
with this the selected value in the home page is preselected in the next pages but the problem is that with this code I can not change the selected value i the drop down list in other pages. can please somebody help me?
I am new in web programming.
First of all, welcome to Stackoverflow!
As pointed out by misorude, it might be wise to utilize the PHP session. When you switch from one page to another, without a form's submit, you will lose the $_POST variable. Which I believe is your problem here?
What happens when you you use sessions however, is that the client saves an ID as cookie. Every time it communicates with your server, it supplies this "session_id". This way the server will be able to grab the right session variables for that client.
Using sessions is fairly easy, call session_start(); at the top of your script. From there on you can use $_SESSION["var_name"] = "value";
For more details on the topic, you might want to read this article on w3Schools.

How to get the value of the selected item in drop down and pass it without using $_POST

I need to get the value of the selected items on the first dropdown because on the second drop down the list that will be shown will depend on the value from the first drop down. Here's my coding. By the way I am using PHP.
In here I am displaying the list of region, then when region is already selected the province that are only under that region should be displayed in the second drop down.
First drop down:
<p><b>Region:</b>
<select class="w3-select" name="region" id="region_value"
onChange="myFunction()" required>
<option value="">--- Select Region ---</option>
<?php
$Region = $FormModel->RegionList();
foreach($Region as $RegionList) {
?>
<option id="option" value="<?php echo $RegionList['region_code']?>"><?php
echo $RegionList['region_name'] ?> </option> </p>
<?php } ?>
</select>
Second drop down:
<p><b>Province:</b>
<select class="w3-select" name="province" id="demo" required>
<option value="">--- Select Province ---</option>
<?php
$Province = $FormModel->ProvinceList();
foreach($Province as $ProvinceList) {
?>
<option value="<?php echo $ProvinceList['prov_code']?>"> <?php echo
$ProvinceList['prov_name'] ?> </option> </p>
<?php } ?>
</select>
I have a java script here getting the value of the selected items but I don't know how to pass it as an attribute to set the value as the region code.
I have a setter and getter in which I will set first the region code and in my query I am getting the value of the region code. But it's not working.
<script>
function myFunction() {
var x = document.getElementById("region_value").value;
$FormModel = new Form(x);
}
</script>
Here's my query where I get the list of province.
public function ProvinceList(){
$region = $this->getRegion();
$sql = "SELECT prov_code,psgc_prv, prov_name FROM lib_provinces WHERE
region_code='$region' ORDER BY prov_name";
$this->openDB();
$this->prepareQuery($sql);
$result = $this->executeQuery();
$recordlist = array();
$trash = array_pop($recordlist);
foreach($result as $i=>$row){
$row_data = array(
"prov_code"=>$row["prov_code"],
"psgc_prv"=>$row["psgc_prv"],
"prov_name"=>$row["prov_name"]
);
$recordlist[$i] = $row_data;
}
$this->closeDB();
return $recordlist;
}
I would be a great help if someone can answer me in this work around.Thanks!
If fetching all the provinces at once is an option you should do this via javascript.
You need to have all the items in a javascript variable and fill you select with these values.
OnChange you should filter the values using only the ones that applies
<script>
var optionItems;
var values = <?php echo json_encode($ProvinceList) ?>;
refreshOptions(values);
function refreshOptions(listItems, x) {
x = x || 0;
var sel = document.getElementById('demo');
sel.innerHTML = "";
for(var i = 0; i < listItems.length; i++) {
if ((x == 0) || (listItems[i].psgc_prv == x)) {
var opt = document.createElement('option');
opt.innerHTML = listItems[i].prov_name;
opt.value = listItems[i].prov_code;
sel.appendChild(opt);
}
}
}
function myFunction() {
var x = document.getElementById("region_value").value;
refreshOptions(values, x);
}
</script>
The second drop down would be just
<select class="w3-select" name="province" id="demo" required>
</select>
This implies stop filtering in the php query to the database
$sql = "SELECT prov_code,psgc_prv, prov_name FROM lib_provinces ORDER BY prov_name";
See this feedle with a working example (without the php)
https://fiddle.jshell.net/7k18euhw/3/
Edit since there is a new request of having another select level
If you have a lot o municipalities the approach of getting all of them in the same way as in Provinces is not a good idea. In that case you will need use ajax to fetch them.
This is what you need to do:
Having an accesible url that receives a province id as param and returns a json with the list of municipaties
Depending on how are you using php are many ways to do this for example if you have a framework you should have a controller is is just vainilla php should be something like this.
mun-list.php
echo json_encode($FormModel->ProvinceList($_GET['prov_id']));
get the onChange event for provinces (in the same way that you are doing with regions) and make a ajax call to the service that you jus created.
As already Kaja suggested you should use jquery to do this (http://jquery.com/)
function onProvChange() {
var prov_id = $("#prov_select").val();
$.ajax({
url: 'mun-list.php?prov_id='+prov_id,
type: 'GET',
success: function(data) {
//without a lot of detail this should populate in the way you did before
refreshMunicipalities(data);
}
});
}
You can do it without it but is harder, take a look at this post.How to make an AJAX call without jQuery?
By using Ajax you can fix. I have used jquery and php
For an example
$("#region_value").change(function() {
region_value= $("#region_value").val();
$.ajax({
url: 'ProvinceList URL',
data: { region_value: region_value },
type: 'POST',
success: function(data) {
var json = JSON.parse(data); \\ I have used JSON to parse data
$('#demo').empty(); // clear the current elements in select box
$('#demo').append('<option value=>Select province</option>');
for (row in json) {
$('#demo').append('<option value='+json[row].prov_code+'>'+json[row].prov_name+'</option>');
}
}
});
});

Calculate sum of select fields in a dynamic form

I have a problem that it's been haunting me for a few days already, I have a dynamic select field where the user pick an ingredient from the DB and if he wants to add more ingredients he just click on 'Add' button and another select field is created, all select fields show its name and price(as text) and there's an input text field( basePrice) that should have the sum of every select created
Select field
<select name="ingredienteId[]" id="ingredienteId" onchange="DoMath()">
<?php foreach($ingredientes as $ingrediente) {
$essaEhATorta = $torta['ingredienteId'] == $ingrediente['id'];
$selecao = $essaEhATorta ? "selected='selected'" : "";
?>
<option value="<?=$ingrediente['id']?>" <?=$selecao?>>
<?=$ingrediente['nome']?> <?=$ingrediente['price']?>
</option>
<?php } ?>
</select>
Dynamic select field
$('#add').click(function() {
var newSelect = $('<label>Ingrediente</label> <select name="ingredienteId[]" id="ingredienteId" class="form-control"> <?php foreach($ingredientes as $ingrediente) {$essaEhATorta = $torta["ingredienteId"] == $ingrediente["id"];$selecao = $essaEhATorta ? 'selected="selected"' : "";?> <option value="<?=$ingrediente["id"]?>" <?=$selecao?>><?=$ingrediente["nome"]?><?=$ingrediente["preco"]?> </option><?php } ?> </select>')
$('#notas').append(newSelect);
});
basePrice input text field
<input class="form-control" type="text" value="<?=$torta['precoBase']?>" name="precoBase" id="basePrice"/>
As I said before, the select option has the name/price of the product as text, <?=$ingrediente['nome']?><?=$ingrediente['price']?>, so as I only wanted the price I came up with this code:
DoMath()
function DoMath(){
var e = document.getElementById("ingredienteId");
var finalPrice= e.options[e.selectedIndex].text;
var noLetterPrice = finalPrice.replace(/[^0-9,"."]/g,'');
var result = parseFloat(noLetterPrice);
document.getElementById("basePrice").value = result;
View
Part of my code is in portuguese but I hope u guys understand
As you can see the conversion part works but I have no idea how to make the sum part work, I have tried a few things but nothing seems to work
Instead of taking value and find price using regex will create issue when options names contains some digital values.
In Jquery we can provide any custom attribute to any field.So take that price in one of custom attribute in option.It will be very easy.
Just try below code
Select Field HTML Structure
<input type="button" name="add" id="add" value="Add" />
<input class="form-control" type="text" value="0" name="precoBase" id="basePrice"/>
<div id="notas">
<div id="ing_div">
<label>Ingrediente</label>
<select name="ingredienteId[]" class="baseingredient">
<option value="" ing-price="0"> Select Price</option>
<?php
foreach ($ingredientes as $ingrediente) {
$essaEhATorta = false;
$selecao = $essaEhATorta ? "selected='selected'" : "";
?>
<option value="<?= $ingrediente['id'] ?>" <?= $selecao ?> ing-price="<?= $ingrediente['price'] ?>">
<?= $ingrediente['nome'] ?> <?= $ingrediente['price'] ?>
</option>
<?php } ?>
</select>
</div>
</div>
In above HTML i have taken Price in ing-price attribute.
Javascript Code
<script>
$(document).on("click",'#add',function() {
var newSelect = $('#ing_div').clone();
newSelect.find("select[name='ingredienteId[]'").val();
$('#notas').append(newSelect);
});
$(document).on("click",".baseingredient",function(){
tot=0;
$(".baseingredient").each(function(){
tot+=parseFloat($(this).find("option:selected").attr("ing-price"));
})
$("#basePrice").val(tot);
});
</script>
You should use .on() instead of .click() and onchange, like this:
$(document).on('click','#add',function(){
var newSelect = $('<label>Ingrediente</label> <select name="ingredienteId[]" id="ingredienteId" class="form-control"> <?php foreach($ingredientes as $ingrediente) {$essaEhATorta = $torta["ingredienteId"] == $ingrediente["id"];$selecao = $essaEhATorta ? 'selected="selected"' : "";?> <option value="<?=$ingrediente["id"]?>" <?=$selecao?>><?=$ingrediente["nome"]?><?=$ingrediente["preco"]?> </option><?php } ?> </select>')
$('#notas').append(newSelect);
});
$(document).on('change','#ingredienteId',function(){
// calculate sum of every select fields
});
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().
From the documentation of .on():
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
You can use each() inside your script, which totals the cost of ingredients, when a select field has been changed.
We have to assign first class tag for your select inputs.
<select class="ing" .....
Have it also to the "to be appended" select inputs.
var newSelect = $('<label>Ingrediente</label> <select class="ing" .....
Using each(), we can run through all the select fields that has class tag of ing:
$(document).on("change", ".ing", function(){ /* WHEN A SELECT FIELD HAS CHANGED */
var total = 0;
$('.ing').each(function() { /* RUN ALL SELECT FIELD */
total = total + parseInt($(this).val()); /* SUM UP ALL */
});
$("#basePrice").val(total); /* CHANGE THE VALUE OF BASE PRICE FIELD */
});
I prefer having
$(document).on("change", ".ing", function(){
rather than your previous
function DoMath(){
function due to the dynamically appended select fields.
Here is a jsfiddle (example) that you can look up to.

js change select name based on option selection

I have a dynamic drop down menu where options are loaded from database, Now i need to change the attribute every time different option is selected from the drop down menu.
To achieve this I am trying to use js in my opinion suitable to do the job but unfortunately I find it difficult and cannot come up with a correct solution, actually i dont know how to start it.
Here is my PHP code that dynamicly generates drop down menu:
$opt = '<select id="Forex" name="" style="display: none">';
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = '';
while($result = mysqli_fetch_assoc($query)){
if($timestamp < $result['endingDate']){
$opt2 .= '<option id="'.$result['id'].'" value="'.$result['startingDate'].'">'.$result['course'].'</option>';
}
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Could some one suggest a solution a at least give me a link to a article that covers this problem
You can add "onchange" event and change the name whatever you like:
$('#Forex').change(function(){
var val = $(this).val(); // you can get the value of selected option
//you can process your conditions here
$(this).attr('name', 'your_choice_name'); // this will change the name attribute
});
or you can do this from javascript
<select id="Forex" name="abc" onchange="changeAttr(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script type="text/javascript">
function changeAttr(ele)
{
var val = ele.value;
var n = "";
if(val == 1){
n = 'xyz';
} else if(val == 2){
n = 'abc';
}
ele.setAttribute('name', n);
}
</script>
Hope this will help you what you want...
Use jquery, with a "onChange" event that will change the attribute you want with the selected item in the list.
jQuery get value of select onChange
Hei!
Not sure if I understood you, but you can use jQuery to manipulate attributes on change event.
For event http://api.jquery.com/change/
To change atribute http://api.jquery.com/attr/

How to maintain a persistent state of the drop down?

I am making a simple web app that has drop down list in the first page in a form tags.
Now when I change the value in the dropdown the form is submitted. On the onchange I have made call to create a query string custom JS function of the selected Index.
Now I want the drop down list to maintain its state; keep the last selected value selected after submission.
How can I do this?
You add the selected attribute with any (e.g. blank) value to the you want to keep selected.
The getQueryValue function is a bit unoptimized and would probably be better accomplished with a regular expression match to get the value, but I just typed it out like this so you could see what it was doing.
<html>
<head>
<script type="text/javascript">
function setSelections()
{
document.myForm.mySelect.value = getQueryValue("mySelect");
};
function getQueryValue(key)
{
var queryString = window.location.search.substring(1);
var queryParams = queryString.split("&");
for(var i = 0; i < queryParams.length; i++)
{
if(queryParams[i].indexOf("=") > 0)
{
var keyValue = queryParams[i].split("=");
if(keyValue[0] == key)
{
return keyValue[1];
}
}
}
return null;
}
</script>
</head>
<body onload="setSelections();">
<form name="myForm" action="" method="get">
<select id="mySelect" name="mySelect" onchange="document.myForm.submit();">
<option value="Opt1">Option 1</option>
<option value="Opt2">Option 2</option>
<option value="Opt3">Option 3</option>
<option value="Opt4">Option 4</option>
</select>
</form>
</body>
</html>
Depends on how your page is dealt with after submission, if it goes to a PHP/Perl or whatever language to rebuild the page, then put the drop down options into a script and loop through them.
Something like this is pretty common place
for($i = 0; $i < 10; $i++){
echo "<option value='{$i}' ";
($i == $_POST['dropdownname'])? echo "selected='selected'":"";
echo ">{$i}</option>";
}
You could pass a hidden form variable to the next posted page. Using a simple Javascript function that loops through the options of the selection drop-down list, if any of the options match the hidden value, then set its selected sttribute.

Categories

Resources