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
Related
What I am trying to figure out is how to have an html input field appear when the value of other is selected from a dropdown menu. Right now the values for the dropdown list are coming from the results of a MySQL DB query, which works, but I can not seem to figure out how to get an input to appear when I select the other option.
$query = mysql_query("SELECT type FROM Dropdown_Service_Type"); // Run your query
echo '<select name="service_type">'; // Open your drop down box
echo '<option value="NULL"></option>';
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo '<option value="Other">Other</option>';
echo '</select>';// Close your drop down box
Use javascript, like in the example below. We can add an input field and have it hidden by default, using the style attribute:
<input name='otherInput' id='otherInput' type="text" style="display: none" />
var otherInput;
function checkOptions(select) {
otherInput = document.getElementById('otherInput');
if (select.options[select.selectedIndex].value == "Other") {
otherInput.style.display = 'block';
}
else {
otherInput.style.display = 'none';
}
}
<select onchange="checkOptions(this)" name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<!-- other options from your database query results displayed here -->
<option value="Other">Other</option>
</select>
<!-- the style attribute here has display none initially, so it will be hidden by default -->
<input name='otherInput' id='otherInput' type="text" style="display: none" />
There are 3rd party libraries like jQuery, AngularJS, PrototypeJS, etc., which can be used to make the code simpler by adding shortcut methods for DOM manipulation (though you should read this post). For example, with jQuery, using .on() (for the event handler binding), .show() and .hide() for the input display toggling, etc:
var otherInput;
var serviceTypeInput = $('#service_type');
serviceTypeInput.on('change', function() {
otherInput = $('#otherInput');
if (serviceTypeInput.val() == "Other") {
otherInput.show();
} else {
otherInput.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="service_type" id="service_type">
<option value="NULL"></option>
<option value="43">43</option>
<option value="Other">Other</option>
</select>
<input name='otherInput' id='otherInput' type="text" style="display: none" />
$(function() {
$('#sample').change(function() {
var val = this.value; // get the value of the select.
if (val == 'other') { // if the value is equal to "other" then append input below the select
$('html').append('<input type="text" id="inputOther"/>');
} else { // else then remove the input
$('#inputOther').remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sample">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="other">other</option>
</select>
How do you change the value of a select option when an image is clicked? I have a drop down list populated with dates from a database also I have two images left and right, so when left is clicked - select previous date, when right is clicked use next date in the list.
Any help much appreciated :)
Setting the id of the populated drop down list to be "ddl", and the onClick events for the images to the corresponding functions, this Javascript should do it:
var ddl = document.getElementById("ddl");
function leftImageClicked(){
if(ddl.selectedIndex > 0) ddl.selectedIndex -= 1;
}
function rightImageClicked(){
if(ddl.selectedIndex < ddl.length - 1) ddl.selectedIndex += 1;
}
<script>
function changeDate(option){
var selectList = document.getElementById("list");
if(option == 0){
selectList.selectedIndex++;
}else if (option == 1 && selectList.selectedIndex > 0){
selectList.selectedIndex--;
}
}
</script>
<img src="img1.jpg" onclick="changeDate(0)">
<img src="img2.jpg" onclick="changeDate(1)">
<select id="list">
<option id="1">One</option>
<option id="2">Two</option>
<option id="3">three</option>
<option id="4">Four</option>
</select>
There is room for some improvement here, but this shows the basic idea. Use an on click event handler to change the selected index.
Fully functional example created in JSFiddle: http://jsfiddle.net/whizkid747/eDfZ5/
<div>
<img src="http://icons.iconarchive.com/icons/deleket/button/48/Button-Previous-icon.png" id="img-left-arrow" height="20px" on/>
<select>
<option value="12/1/2013">12/1/2013</option>
<option value="12/1/2014">12/1/2014</option>
<option value="12/1/2015">12/1/2015</option>
<option value="12/1/2016">12/1/2016</option>
</select>
<img src="http://icons.iconarchive.com/icons/deleket/button/48/Button-Next-icon.png" id="img-right-arrow" height="20px"/>
</div>
<script>
$('#img-right-arrow').on('click', function() {
$('select option:selected').next().prop('selected', true) });
$('#img-left-arrow').on('click', function() {
$('select option:selected').prev().prop('selected', true) });
<script>
this weekend i've been trying to use this script To create dependable menus.
It consists of an sql table with three rows: "ID, Master, Name" It later grabs the entries that contain 0 as the "master" and will use the resulting data to populate the first option list
To populate the next selection lists from the database, it uses a combination of the following JS and php:
and the rest of the select lists will populate accordinly.
The problem that i'm having is that After it populates the select lists I would like to have the visitors of the website hit a seach button to perform a search based on the data collected. The problem is that when I submit the form it sends the info stored in the "master" row of the database instead of the info on "name"
I'm Getting
index.php?genre=1&fruit=37&colour=39
Instead of
index.php?genre=Male&fruit=Strawberry&colour=Red
I tried to switch '.$row['name'].' to '.$row['id'].
But that was a no go, I also tried to only use '.$row['id'].' and it just messed up with the forms. Is there anyway I can accomplish what i'm looking for so that i can send the values selected on the fields to the url?
Thanks in advanced for any help on this one.
The behavior that you mentioned is normal as submitting a form automatically sends the value, instead of the text, of the selected option. The switch that you mentioned ('.$row['name'].' to '.$row['id'].)should work fine. If it is messing up the forms, please provide more information on what you mean by messing up the forms.
Otherwise, here is a possible solution. It's not the most elegant solution and is probably best suited for simple forms that do not require further complexities but basically, generate the querystring and redirect manually. This is based on the original example that you linked to at http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html.
JS:
var formObject = {
run: function (obj) {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('http://jquery-dependable-dropdown.ssdtutorials.com/mod/update.php', {
id: id,
value: v
}, function (data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
};
$(function () {
$('.update').live('change', function () {
formObject.run($(this));
});
$('#submitButton').click(function () {
window.location.href = 'test.php?gender=' + $('#gender').find(':selected').text() + '&category=' + $('#category').find(':selected').text() + '&colour=' + $('#colour').find(':selected').text();
});
});
HTML:
<div id="wrapper">
<form id="theForm" action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
<input type="button" id="submitButton" value="submit">
</form>
http://jsfiddle.net/BUJnf/1/
Hope that helps a bit!
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
})
})
Is there a better way to do this jquery code?
Currently I have to use PHP to insert the starting position of the jquery code.
The code is for a country/state list.
If a user picks USA then a state dropdown list is below it, if any other country is selected, then it will show a different text input box and hide the dropdown list.
Now if a user has a country saved into the database already and they are on a page to edit this value, then I have to use PHP to show which should be shown first, either the USA states or the state input.
When a user signs up, by default the USA state list is shown, only if they choose a non usa country if the state list changed to a state input instead.
Hope I made sense. the ultimate goal is to somehow make it completely javascript/jquery and not rely on PHP to set anything
country dropdown list
<select name="country" id="country" class="textarealong signup_good"/>
<option value=1001>Choose a Country</option>
<option value=238>Zimbabwe</option>
...
</select>
USA state dropdown list
<select name="usstate" id="usstate" class="textarealong signup_good"/>
<option value=1001>Choose a State</option>
<option value=238>Florida</option>
...
</select>
NON-USA state INPUT box
<input type="text" id="othstate" name="othstate" id="othstate" value="" class="textarealong signup_good" maxlength="100">
<?PHP
//fix jquery country/state list based on there current saved country/state
if($_SESSION['member_info']['country'] == 224){
//$jquerycountry = "$('#othstate').hide().attr(\"disabled\", \"disabled\");";
$jquerycountry = "$('#othstate').hide().val('');";
}else{
$jquerycountry = "$('#usstate').hide().attr(\"disabled\", \"disabled\");";
}
?>
<script>
$(document).ready(function() {
locationlist();
});
function locationlist() {
<?PHP echo $jquerycountry; // includes country jquery code from above ?>
$('#country').change(function () {
var val = $(this).val();
if (val == 224) {
$('#usstate').val('').show().removeAttr("disabled");
$('#othstate').hide().val('');
} else {
$('#usstate').val('').hide().attr("disabled", "disabled");
$('#othstate').show().removeAttr("disabled");
}
});
}
</script>
Maybe this could be a fine solution for you:
HTML selection and input fields:
<select name="country" id="country" class="textarealong signup_good"/>
<option value=1001>Choose a Country</option>
<option value=238>Zimbabwe</option>
<option value=239>Rwanda</option>
</select>
USA state dropdown list
<select name="usstate" id="usstate" class="textarealong signup_good"/>
<option value=1001>Choose a State</option>
<option value=238>Florida</option>
</select>
<input id="otherstate"/>
Then the jQuery part with some 'ready'-magic: hide the otherstate field and trigger the change event on loading like Greg mentioned already. This makes sure, that if a country was already selected on page load the right form field will be selected:
<script type="text/javascript">
$(document).ready(function () {
$("#otherstate").hide();
$("#country").trigger("change");
});
$("#country").change(function () {
if ($("#country").val() != '1001') {
$("#usstate").hide();
$("#otherstate").show();
} else {
$("#usstate").show();
$("#otherstate").hide();
}
});
</script>
Hopes this will help you! ;)
Could you just do this in ready()?
loctionlist();
$('#country').trigger('change');
(Coming at it from a different angle entirely:)
With all the options/possibilities you're describing here, it might be wise to scrap all the drop-downs and just use an autocomplete text field.