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

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

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>

How to create a text box after selecting an option from drop-down list?

I'm trying to create a drop-down list with four options such that if I select the 4th option, I want a text box created so that I can get the value typed in that box using "$_GET"
Something like this;
<select name="value">
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
<!-- And a 4th one -->
</select>
And if the 4th one is selected, a box should appear like this;
<input type="text" name="firstname">
Edit;
My current code;
<script>
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='sortby']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "byDefindex"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "defindex"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
</script>
<form action="<?php $_PHP_SELF ?>" method="GET">
Select:
<br />
<select name="sortby">
<option value="playHours">Play Hours</option>
<option value="lastLogin">Last Login</option>
<option value="byDefindex">By Defindex</option>
</select>
<br />
<input type="submit" />
</form>
If your 4th option is this:
<option value="value4">Option 4</option>
You can use jQuery to display the field.
Put your field in a <div>
<div id="field"><input type="text" name="firstname"></div>
Now,
<script type="text/javascript">
$(document).ready(function(){
$('input[name="value"]').change(function(){
var v = $('input[name="value"]').val();
if(v=="value4") $('#field').show();
else $('#field').hide();
})
})
This is usually done via javascript; something like this (by using popular JavaScript library, jQuery) :
jQuery(function($){ //calling the code inside braces when document loads and passing jQuery object as '$' parameter;
$("select[name='value']").change(function(){ //binding an event that fires every time select value changes
var select = $(this); //caching select, which value was changed
if(select.val() === "value4"){ //checking if we selected the right option
$("<input>").attr({type: "text", name: "firstname"}).appendTo(select.parent()); //creating new input element object, setting its value to "value4" and appending to select parent element or wherever you want it
}
});
});
Hope that helps. You can find more here jQuery site
I'm not certain this is what you're asking, but it seems you're wanting to add new lines to your select list?
I often do something similar to this for adding new options to lists. The first option would be 'add a new record', like this:
<select name="value">
<option value="-1">Add New Option</option>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
</select>
Note that the value for "add new" is -1... you could put anything here, but it should be something that would never show up in the other options, so your javascript knows what to do when it is selected.
Add a 'onchange' to the select box like this:
<select name="value" onchange="if(this.value == -1) addOption(this);">
Note that if the selected option is -1, then a javascript function is called. It references itself (this), so that your function knows who called it.
Then create a function that allows adding a new option:
function addOption(theSelectElement){
// create a text box, underneath the select box:
var newInput=document.createElement('input');
newInput.type='text';
theSelectElement.parentNode.insertAfter(newInput,theSelectElement);
}
You'll want to add more code to this function so that the new text field has a name and perhaps an ID.
Hope this helps, or at least points you in the right direction.

dynamic selection option in JS

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

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

Multiple Drop-Down Menus Based on Selected Value of First Drop-Down

I have been searching for similar questions but they are a little different to what I am looking for.
Basically, this is what I am aiming to implement:
Have a first drop-down list filled with values, e.g. :
<form>
<select id="tags" name="tags">
<option value="agent" selected="selected">agent</option>
<option value="extension">extension</option>
<option value="fileversion" >fileversion</option>
<option value="pages">pages</option>
</select>
Then, in a second drop-down list, show options dependant on what was selected, for example, if agent is selected, the operators would be = or != since it is text. For fileversion there would be 4 operands, =, !=, > and <.
Lastly, there would be a third drop-down with values also dependant on the initially selected option.
For example, when agent is selected, the options would be pdf, word, excel, ppt etc. and others it would just be a text box to type in rather than exhaust all possible values.
In the end this will be used to search a database but it is a big db and the searches are too slow so I'm thinking the values for the options will be stored in an array rather than pulled directly.
As you can see, it's fairly tricky :/ any help at all is much appreciated.
Thanks,
Martin
EDIT:
Found the answer for those who happen to be looking for the same answer:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/dropdown.js"></script>
</head>
<body>
<form>
<select id="tags" name="tags">
<option value="tags" selected="selected">tags</option>
<option value="agent">agent</option>
<option value="extension">extension</option>
</select>
<select name="operands">
<option>operands</option>
</select>
</form>
</body>
</html>
dropdown.js:
$(document).ready(function() {
$tags = $("select[name='tags']");
$operands = $("select[name='operands']");
$tags.change(function() {
if ($(this).val() == "agent") {
$("select[name='operands'] option").remove();
$("<option>=</option>").appendTo($operands);
$("<option>!=</option>").appendTo($operands);
}
if ($(this).val() == "extension")
{
$("select[name='operands'] option").remove();
$("<option>.pdf</option>").appendTo($operands);
$("<option>.doc</option>").appendTo($operands);
}
if ($(this).val() == "tags")
{
$("select[name='operands'] option").remove();
$("<option>operands</option>").appendTo($operands);
}
});
});
try something like this, a data object filled with the corresponding data..
var data = {
agent: [
["=", "!="], //values that are shown in 1st dropdown when agent is selected
["a", "b"] //values that are shown in 2nd dropdown when agent is selected
]
extension: [
["pdf", "doc"], //values that are shown in 1st dropdown when extension is selected
["c", "d"] //values that are shown in 2nd dropdown when extension is selected
]
}
and for the HTML
<select id="tags" name="tags">
<option value="agent" selected="selected">agent</option>
<option value="extension">extension</option>
<option value="fileversion" >fileversion</option>
<option value="pages">pages</option>
</select>
<select id="dropdown2" name="dropdown2">
</select>
<select id="dropdown3" name="dropdown3">
</select>
Now listen for changes on the tags dropdown and get the options from the data object (example using jquery)
$("#tags").change(function() {
setDropDown1(data[$(this).val()][0]);
setDropDown2(data[$(this).val()][1]);
});
pass the data to a function like this to create the dropdown options
function setDropDown1(data) {
$("#dropdown1").html(""); //clear options
for (var i = 0; i < data.length; i++) {
$("#dropdown1").append("<option value='" + data[i] + "'>" + data[i] + "</option>");
}
}
var selectionObject = {
agent = ["=","!="],
fileversion = ["=","!=",">","<"],
...
}
$('form select#tags').click(function(){
comboBoxSelection = $(this).val();
secondDropDownvalues = selectionObject[comboBoxSelection];
....
});
In pseudo code should be something like that

Categories