How to maintain a persistent state of the drop down? - javascript

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.

Related

php Dropdown Realtime Update

My apologies if this has been answered before but I did do a search and haven't seen any answers for the questions asked in other posts. The answers I did see didn't relate to my question (mostly to do with dropdowns getting results from mysql).
I have a php dropdown list where you need to select a value (1, 2 or 3). Based on what you select, the list should update a variable and show a hidden div tag. Now from the information I gathered it seems like this cannot be done with php alone but requires a javscript or ajax script.
php:
<form>
<select name="options" onchange="{dosomething}">
<option value="0">[Select value]</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
</form>
This should then update this variable and div in REALTIME:
<div id="test" style="display:none">
$answer= 1 + $value
<?php
echo "1 + $value = $answer";
</div>
javascript/ajax:
<script>
function dosomething {
#update $value based on dropdown and do calculation
#unhide div with id "test"
}
</script>
I need to mention that I have no knowledge of javascript or ajax.
If you only need to view the new result in the same page without requesting something to the server add this script below your last div:
<script>
var element = document.getElementsByName('options');
if( element.length > 0 ){
element[0].addEventListener('change',update_text,false);
//element[0].addEventListener('change',function(){update_text(param)},false);
}
function update_text(evt){
console.log(evt);
var first_element = evt.target;
var selection = first_element.options[first_element.selectedIndex].value;
//do math:
selection = +selection + 1; //this cast selection as number and not as String
console.log(selection);
var test = document.getElementById('test');
test.style.display = 'block';
test.innerHTML = `<p>${selection}</p>`;
};
</script>

Run Function on default HTML Select with PHP And 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);

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/

Dynamically set the value of select dropdown using query string paramater

To begin with, I'm new to Javascript.
I have a form with a select element with various options and I do not have access to change the form. There are no id's to the options, but just the values as shown in the code below.
<form>
<select class="country" name="country" id="countryid">
<option value="usa" selected="selected">USA</option>
<option value="canada">Canada</option>
<option value="japan">Japan</option>
<option value="china">China</option>
</select>
</form>
My goal is to populate the field in the above form automatically based on the url parameters.
For example, www.example.com?country=china should populate China in the form field. The following is the javascript code:
<script>
var param1var = getQueryVariable("country");
function displayresult(){
//document.getElementById(param1var).selected=true; //if there was id given in the form field
//cannot use document.getElementByValue(param1var).selected=true;
//document.querySelectorAll('input[value=' + param1var + ']').selected=true; does not work
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
</script>
I cannot use document.getElementById(param1var) because there is no id.
Javascript does not support document.getElementByValue(param1var).
document.querySelectorAll is not working.
Is there a way that I can reference the element using the option value?
Thanks!
You can just do it this way by setting the value of the select element. Also note that value is case sensitive, plus make sure that the function displayresult runs on onload or after the element appeared in the html.
document.getElementById("countryid").value=param1var;
Demo

Select drop down html

I have a main select "main", and a list from 2 till 9, depending the situation, of more selects.
What if I want to change the value in all this secondary selects, with the same value that the main select?. So the main select will change more than 1 select at the same time:
So, I have got the main select:
<select name="main" id="main" onchange="document.getElementById('item').value = document.getElementById('main').value">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
And the next selects are made in php inside a loop, so I will have 2,3,4,5,..,9 selects depending the situation. Each of them with a different name (because I use this name in POST)
<select name=item_".$itemnumber." id="item">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
With this I want to have the possibility to select in one time the option for all the selects, but maintaining the possibility to change only some of the selects.
I made it work like that:
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].id == 'item' && theForm[z].id != 'main'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
But I dont know if thats the best way, I heard here that jQuery would be easier, so I would like to know how to make it in jQuery, please.
What I understand is, you have a <select> dropdown, and on change of the text in this one, you want to change the the selection in one or more of other dropdowns on your screen. Am I right?
If this is the case, then you have to have a javascript function and call this in the onchange of the <select>.
In this javascript function, you have to set the selected value of all the dropdowns you want.
If this is not what you want, Can you please rephrase your question and tell us what you exactly you want?
EDIT
function setElement()
{
var selectedValue = document.getElementById("main").value;
selectThisValue(document.getElementById("child1"), selectedValue);
selectThisValue (document.getElementById("child2"), selectedValue);
}
function selectThisValue(selectElement, val)
{
for ( var i = 0; i < selectElement.options.length; i++ )
{
if ( selectElement.options[i].value == val )
{
selectElement.options[i].selected = true;
return;
}
}
}
Call setElement() in your onchange of the main. This function gets the selected item from the main <select> and selects the items in the other dropdowns that have the same value.
You call the selectThisValue function once for every select you need to change.
Change the ids as per your code.
Never put the same id in all the select elements... ID is supposed to be unique for elements in a page.
change your html to look like
<select id="main" class="master">....</select>
<select id="test1" class="child">....</select>
<select id="test2" class="child">....</select>
<select id="test3" class="child">....</select>
<select id="test4" class="child">....</select>
Class attribute for multiple elements can be the same.
Your function needs to be modified to look like this
(i havent tested this, but should work..)
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].className == 'child'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
by the way, do the options inside these select boxes vary? if so, you'll have to match by value rather than index
EDIT: here's the code i wrote later.. modify it to suit your need
<html>
<head><title>select change cascade</title></head>
<body>
<select id="main" class="master"><option value="1">book</option><option value="2">cd</option></select>
<select id="test1" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test2" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test3" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test4" class="child"><option value="1">book</option><option value="2">cd</option></select>
<script type="text/javascript" src="./selectchange.js"></script>
</body>
</html>
and in selectChange.js
var main = document.getElementById("main");
main.onchange = function (){
sels = document.getElementsByTagName("select");
for(z=0; z<sels.length;z++){
if(sels[z].className == 'child'){
sels[z].selectedIndex = this.selectedIndex;
}
}
}
I don't see any question marks.
The only issue I see is that you should use .selectedIndex instead of .value.
jQuery solution:
$(".selectorClass").each(function(index, selectorToUpdate){
selectorToUpdate.selectedIndex = $('#main').selectedIndex;
});
Put this in a function and call that function for onchange.

Categories

Resources