dynamic selection option in JS - php

I have a date SELECT/OPTION create by JS.
The code works fine, but when this file post to different page. The SELECT didn't retain the value when I click back button from browser or when I post it back. The day and year become blank. Copy the code and try it in your browser you will understand what I mean.
Any suggestion?
<script>
function populate(s1, s2){
var s1=document.getElementById(s1);
var s2=document.getElementById(s2);
s2.innerHTML="";
if(s1.value==""){
var optionArray=['|Day'];
}
else if(s1.value=="01" || s1.value=="03" || s1.value=="05" || s1.value=="07" || s1.value=="08" || s1.value=="10" || s1.value=="12"){
var optionArray=['|Day'<?PHP for($d=1; $d<32; $d++){echo ", '$d|$d'";}?>];
}
else if(s1.value=="04" || s1.value=="06" || s1.value=="09" || s1.value=="11"){
var optionArray=['|Day'<?PHP for($d=1; $d<31; $d++){echo ", '$d|$d'";};?>];
}
else if(s1.value=="02"){
var optionArray=['|Day'<?PHP for($d=1; $d<30; $d++){echo ", '$d|$d'";};?>];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s2.options.add(newOption);
}
}
function populate_year(s2, s3){
var s2=document.getElementById(s2);
var s3=document.getElementById(s3);
s3.innerHTML="";
if(s2.value==""){
var optionArray=['|Year'];
}
else if(s2.value=="29"){
var optionArray=['|Year'<?PHP for($y=1936; $y<2013; $y=$y+4){echo ", '$y|$y'";};?>];
}
else if(s2.value!=="29"){
var optionArray=['|Year'<?PHP for($y=1933; $y<2013; $y++){echo ", '$y|$y'";};?>];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s3.options.add(newOption);
}
}
</script>
<select id="s1" onchange="populate(this.id, 's2')" name="month" style="width:80px; font-family:arial;">
<option value="">Month</option>
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
<option value="05">May</option>
<option value="06">Jun</option>
<option value="07">Jul</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="s2" onchange="populate_year(this.id, 's3')" name="day" style="width:65px; font-family:arial;">
<option value="">Day</option>
</select>
<select id="s3" name="Year" style="width:80px; font-family:arial;">
<option value="">Year</option>
</select>

The issue is the html for the day and year are dynamically generated, so the value of the last selected index can't be injected into the select boxes (because the select boxes haven't been made yet).
I have two suggestions:
1) I wouldn't populate each select option dynamically. Perhaps have 3 select boxes in the DOM for each of the three different types of day selections (30 days, 31 days, and for February). The JavaScript that executes when selecting a month doesn't populate the select box, but shows the appropriate select box for days and hides the other two. By default, they would all be hidden. You would then repeat something similar for the year select box.
2) If you must dynamically generate your content, I would attempt storing the selected index in Local Storage (or whatever other means tickles your fancy). For example, if someone selects January, 23, 2012.. store this in Local Storage. This could look something like this:
localStorage['dateSelect'] = '01|23|2012';
This is just an example of what you could do. Then, you could read from it upon page load.
var selectedMonth;
var selectedDay;
var selectedYear;
if (localStorage['dateSelect']) {
var storage = localStorage['dateSelect'].split('|');
selectedMonth = storage[0];
selectedDay = storage[1];
selectedYear = storage[2];
}
Let me know if you need any more help :)
Good luck!
-Graham

Related

Pass select option values as url parameter to next page

I have custom registration system based on url parameters.
Step1: I have some buttons and when you click one of the buttons it will pass value to next page, where i'm able to get value by using <?php echo $_GET['step1'];?> (this works fine)
Step2: I want to use just two select boxes (don't want to use form here) and on <a> click I want to pass that selection to url.
Here is my code:
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
Next
So here is what I want to pass to the next page:
http://domain/step1/step2/step3?parameterfromstep1=something&gender=male&color=red
How should I make it? Should I use php on a button click or jquery?
Thanks
<a id="next" href="http://domain/step1/step2?step1=<?php echo $_GET['step1'];?&SELECTboxVALUES>">Next</a>
use below code
$('#next').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
var gender = $('[name="gender"]').val();
var color = $('[name="color"]').val();
if( gender && color ){
window.location.href = url+'?&'+gender+color;
}
});
Well, this is maybe not the best or most beautiful approuch but i think the code below will work for you:
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
Next
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).on('click', '#nextButton',function( event ) {
// Stop default action
event.preventDefault();
window.location.href = $(this).attr('href') + '&gender='+$('select[name="gender"] option:selected').text()
+ '&color='+$('select[name="color"] option:selected').text();
});
</script>

$('body').on('change', '.selector', function() { }); not working as expected for <select> tag jquery

I am new to web development, especially Jquery and Bootstrap. I need to accept date from users on my page, where they have the option to either give only Year or Year & Month or Year, Month & Day. So, instead of using a calendar picker I decided to use 3 <select> tags for this.
My Requirements
Without selecting Year, user shouldn't be able to select either Date or Month
Only after selecting Year, user should be able to select Month and after that, Day.
The html element containing these <select> tags is loaded dynamically through .load() function. Hence, forced to use $('body').on(....)
Kindly refer this JSFiddle to see what I have done.
HTML
<div class="form-inline">
<div class="form-group">
<select class="form-control year">
<option>Year</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
</select>
<select class="form-control month">
<option>Month</option>
</select>
<select class="form-control day">
<option>Day</option>
</select>
</div>
JS
$(function () {
var dd_cal, year, month, day, num_year, num_month, num_days, i;
$('body').on('change', '.year', function () {
year = $(this);
dd_cal = year.parent();
month = dd_cal.find($('.month'));
day = dd_cal.find($('.day'));
num_year = year.val();
if (month.children().length <= 1) { //Only if <select> is empty fill it
month.append('<option value="december">December</option>\n\
<option value="november">November</option>\n\
<option value="october">October</option>\n\
<option value="september">September</option>\n\
<option value="august">August</option>\n\
<option value="july">July</option>\n\
<option value="june">June</option>\n\
<option value="may">May</option>\n\
<option value="april">April</option>\n\
<option value="march">March</option>\n\
<option value="february">February</option>\n\
<option value="january">January</option>');
}
if (num_year == 'Year') { //Remove all Months and Days if default value (i.e."Year") of Year is selected.
month.add(day).children('option:not(:first-child)').remove();
}
});
$('body').on('change', month, function () {
num_month = 13 - month[0].selectedIndex;
num_days = Math.round(((new Date(num_year, num_month)) - (new Date(num_year, num_month - 1))) / 86400000);
if (month.val() == 'Month') { //Remove all Days if default value (i.e."Month") of Month is selected.
day.children('option:not(:first-child)').remove();
}
day.children('option:not(:first-child)').remove();
for (i = num_days; i >= 1; i--) {
day.append('<option value=' + i + '>' + i + '</option>');
}
});
});
For the first time when you see the menus, only year has values. Both Month and Days are empty. Then select only Year and check the other 2 menus, you will find the following issues:
Issues
The Months are filled properly when a Year is selected, but even Days are filled when only Year is selected. This should fill only after any Month is selected.
After selecting Month, if the "default" value of Year is selected (i.e. "Year"), both Months and Days should be emptied, but doesn't happen.
The day.children('option:not(:first-child)').remove(); is used to empty the Days filled previously and fill with new values based on the Month selected (for every new selection). But instead of triggering only for change in Month, this is triggered even after each time the Day is selected. Try selecting a day from the fiddle and you can see that the value always remains as "Day".
Kindly help me with this by modifying my fiddle. Thank you.
P.S.: I do not want to use any kind of plugin or a calendar to accomplish this since it is a pretty simple and direct approach.
try this,
var dd_cal, year, month, day, num_year, num_month, num_days, i;
$('body').on('change', '.year', function() {
year = $('.year');
if($(this).val() == 'Year')
{
$('.month'). children('option:not(:first)').remove();
$('.day'). children('option:not(:first)').remove();
}
else
{
dd_cal = year.parent();
month = dd_cal.find($('.month'));
day = dd_cal.find($('.day'));
if (month.children().length <= 1) {
month.append('<option value="december">December</option>\n\
<option value="november">November</option>\n\
<option value="october">October</option>\n\
<option value="september">September</option>\n\
<option value="august">August</option>\n\
<option value="july">July</option>\n\
<option value="june">June</option>\n\
<option value="may">May</option>\n\
<option value="april">April</option>\n\
<option value="march">March</option>\n\
<option value="february">February</option>\n\
<option value="january">January</option>');
}
}
});
$('body').on('change', '.month', function() {
num_year = year.val();
num_month = 13 - month[0].selectedIndex;
num_days = Math.round(((new Date(num_year, num_month)) - (new Date(num_year, num_month - 1))) / 86400000);
day.children('option:not(:first-child)').remove();
for (i = num_days; i >= 1; i--) {
day.append('<option value=' + i + '>' + i + '</option>');
}
});
});

How to pass option values to a button

I'm trying to store variables from select/option, and then access them from a button to send to a javascript function that would filter some divs on my page.
So far I have it sending the value to "filter()" when the value changes.
Here's my markup:
<select name="Area" onchange="filter(this)">
<option selected>Select</option>
<option value="Austin">Austin</option>
<option value="San Antonio">San Antonio</option>
<option value="Temple">Temple</option>
</select>
<select name="Number" onchange="filter(this)">
<option selected>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<a class="button">Submit</a>
but how do I store the values from all the options, and then send them
all at once to the function?
Edit: In other words, how do I store the value of each option, and only send to the function once they click submit?
If I got it right, without jQuery you may try this:
document.getElementById("button").onclick = function() {
var selects = document.body.getElementsByTagName("select");
var data = [];
for (var i = 0; i < selects.length; i++) {
data.push(selects[i].value);
}
destinyFunction(data);
};
Or you may use jQuery for the sake of simplicity:
$("#jbutton").on("click", function() {
var data = [];
$("select").each(function() {
data.push($(this).val());
});
destinyFunction(data);
});
Fiddle with those two examples here.
Give each of your selects an id attribute, like:
<select name="Number" onchange="filter(this)" id="Number">
...
Then you can get the value of each in javascript by:
var el = document.getElementById('Number');
var value = el.options[el.selectedIndex].value;
As a sidenote, using onchange in HTML markup to attach your event handling is not best practice. This article from quirksmode offers a good explanation of alternative solutions. However, there are major cross-browser considerations to be taken into account, which is why most people prefer to use a Javascript framework so that those are mostly mitigated.

How can i change options in dropdowns if it is generated dynamically?

I do have this script to generate three dropdowns and one text input field for my webform that i have to submit to a database using PHP. This form is HTML but only this part is javascript to populate the fields. I am using this javascript to generate approx 15 sets of these dropdowns and text input fields. (1 set = 3 dropdowns and 1 input text field).
My question is : If user selects an option from first dropdown then the options in the other two dropdowns should change according to the selected option in the first drodown.
What I wanted to is after generating the desired number of sets by selecting the number from the dropdown in this fiddle, it will generate sets od 3 dropdowns and 1 input field dynamically. 
So if someone selects option one from the first dropdown it should change the options in the other dropdowns as well. 
JSFIDDLE
THE SCRIPT:
<script>
$(function() {
$("input[type=button][value=Add]").click(function(e) {
for (i = 0; i < document.getElementById('sel').value; i++) {
e.preventDefault();
var j = 1;
var newDiv = $("<div>").appendTo("#dropbox");
$("<select>").attr("name", "input1_"+j).appendTo(newDiv).append(
$("<option>").val("0").text("Option 1"), $("<option>").val("1").text("Option 2"));
$("<select>").attr("name", "input2_"+j).appendTo(newDiv).append(
$("<option>").val("0").text("Option 1"), $("<option>").val("1").text("Option 2"));
$("<select>").attr("name", "input3_"+j).appendTo(newDiv).append(
$("<option>").val("0").text("Option 1"), $("<option>").val("1").text("Option 2"));
$("<input>").attr("name", "input4_"+j).appendTo(newDiv);
$("<button>").text("Remove").appendTo(newDiv).click(function(e) {
e.preventDefault();
$(this).parent().remove();
})
j++;
}
})
})
</script>
THE HTML:
<form>
<select id="sel">
<option value="" selected="selected"></option>
<option value="01" >01</option>
<option value="02" >02</option>
<option value="03" >03</option>
<option value="04" >04</option>
<option value="05" >05</option>
<option value="06" >06</option>
<option value="07" >07</option>
<option value="08" >08</option>
<option value="09" >09</option>
<option value="10" >10</option>
<option value="11" >11</option>
<option value="12" >12</option>
<option value="13" >13</option>
<option value="14" >14</option>
<option value="15" >15</option>
</select>
<input type="button" value="Add" />
<div id="dropbox"></div>
</form>
Since you use jQuery, I suggest to add a change event to your dropdown. (The linked jQuery docs page contains a full example).
Regarding filling the other 2 drop-downs, you have several options, such as:
Static: Your PHP code that creates the page fills in a javascript array with all possible options needed according to user choice in the 1st dropdown. Then your javascript code can use this array whenever a change event is triggered.
Dynamic: If sub-choices can't be predicted or loaded at page load, use a jQuery ajax request to query the server for options matching user choice. You may also want to read about the JSon data format (supported by PHP using json_encode)
DEMO
I gave the sel and the button an ID and changed the dom access to jQuery
I also use the "i" and "j" now
Assuming you wanted to syncronise the 3 selects, the code could look like this
$(function() {
$("input[type=button][value=Add]").click(function(e) {
e.preventDefault();
for (var i=0,n=$('#sel').val();i<n; i++) {
var newDiv = $("<div>").appendTo("#dropbox");
for (var j=0;j<3;j++) {
var id = "input"+i+"_"+j;
$("<select>")
.attr("id",id)
.attr("name",id)
.on("change",function() {
// set all other select's value to this value
$(this).siblings("select").val(this.value);
})
.append(
$("<option>").val("0").text("Option 1"),
$("<option>").val("1").text("Option 2"))
.appendTo(newDiv);
} // j
$("<input>")
.attr("name", "input"+i+"_"+j)
.appendTo(newDiv);
$("<button>").text("Remove").appendTo(newDiv).click(function(e) {
e.preventDefault();
$(this).parent().remove();
})
} // i
})
})​

Display changing without AJAX

I have 2 drop down lists , and value of the second drop down list should change according to the value selected in first drop down list. The current drop down lists are.
<select name="first">
<option name="a" value="a">a</option>
<option name="b" value="b">b</option>
<option name="c" value="c">c</option>
</select>
<select name="second">
<option name="a1" value="a1">a1</option>
<option name="a2" value="a2">a2</option>
<option name="b1" value="b1">b1</option>
<option name="b2" value="b2">b2</option>
<option name="c1" value="c1">c1</option>
<option name="c2" value="c2">c2</option>
</select>
I want the second drop down to be displayed according to the value selected in First dropdown, ie, if "a" is selected in first then only a1 and a2 should be shown. Also drop down values are pulled from a database
Thanks
There are just limited options to do so
OnChange event
Classic html/javascript/post refresh
One option is to load everything you have in the database in a standard form such as JSON. Then, you'd have to write javascript to build the dropdowns dynamically as the user interacts with each item.
Here is an example of how you'd go about doing it http://jsfiddle.net/9Z5t8/1/
There are some drawbacks. If you have a LOT of data (hundreds of records) to transfer this will be slow, but it's okay for a few records.
You can save the options in a separate array, and insert the appropriate ones when a value is selected: http://jsfiddle.net/KTQ7d/.
var arr = [];
var first_select = document.getElementsByTagName('select')[0]
var second_select = document.getElementsByTagName('select')[1]
var elems = second_select.getElementsByTagName('option');
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].value);
}
first_select.onchange = function() {
second_select.innerHTML = '';
for(var i = 0; i < arr.length; i++) {
if(arr[i][0]
==
first_select.options[first_select.selectedIndex].value) {
var opt = document.createElement('option');
opt.name = arr[i];
opt.value = arr[i];
opt.innerHTML = arr[i];
second_select.appendChild(opt);
}
}
};

Categories