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>
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>
I have a page with two drop-down menus. The option selected in the first drop-down menu controls what is displayed in the second.
The code was nice and easy when the drop-down menus were only used once - but I'm looking to repeat each set of drop-down menus four times.
Drop-down menu one is assigned the ID experience[<?php echo $i; ?>][manufacturer]. Drop-down menu two is assigned the ID experience[<?php echo $i; ?>][type].
Essentially, what I've got is:
<select id="experience[1][manufacturer]">...</select>
<select id="experience[2][manufacturer]">...</select>
<select id="experience[3][manufacturer]">...</select>
<select id="experience[4][manufacturer]">...</select>
... followed by:
<select id="experience[1][type]">...</select>
<select id="experience[2][type]">...</select>
<select id="experience[3][type]">...</select>
<select id="experience[4][type]">...</select>
I'm wondering: what's the best way to get the equivalent of <?php echo $i; ?> into the chunk of JavaScript that's used to output the contents of the second drop-down menu? (I know I can't use PHP directly within JavaScript like this - I just left the <?php echo $i; ?> snippets to indicate where I need to output numbers 1, 2, 3, 4 etc.
Thanks for your help!
Code:
<form>
<?php
$i=1;
while($i<=4) {
?>
<select id="experience[<?php echo $i; ?>][manufacturer]">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
<script type='text/javascript'>
$(document).ready(function() {
$("#experience[<?php echo $i; ?>][manufacturer]").change(function() {
$("#experience[<?php echo $i; ?>][type]").load("get_type.php?choice=" + $("#experience[<?php echo $i; ?>][manufacturer]").val());
});
});
</script>
</select>
<?php
$i++;
}
?>
</form>
Revised code:
<form>
<script type='text/javascript'>
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience["+$(this).attr('data-id')+"][type]").load("get_type.php?choice=" + $(this).val());
});
});
</script>
<?php $i=1;
while($i<=4) { ?>
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
</select>
<?php
$i++;
}
?>
</form>
You should not need to include the script element in your PHP loop.
Instead, you should add a similar class to all common select elements. Something like class="experience"
Then, with a single script element you can attach events to all the selects:
<script type='text/javascript'>
$(document).ready(function() {
$("select.experience").each(function(i,element){
// here element is the actual item from the selected set, i is its index
$(element).on("change", function() {
$("#experience[" + i + "][type]").load("get_type.php?choice=" + $(element).val());
});
});
});
</script>
Instead of repeating the same javascript code 4 times, put it outside your loop and give classes to your select elements and use them as selectors for your jquery code. You could then add an attribute (named data-id for example) to your select elements containg their ids. It would look something like this
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]"></select>
And your javascript code (outside the loop) would look something like this
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience\\["+$(this).attr('data-id')+"\\]\\[type\\]").load("get_type.php?choice=" + $(this).val());
});
});
Note that I used the keyword "this" inside the change event which references to the select element.
Edit: Added backslashes to escape the brackets in the jQuery selector (or else jQuery interprets it as an attribute).
I have a dropdown list(in a php file and without form tag)
print "<select id="animal" onchange="getSelectedItem(this.value)">
<option value = "Dog"> Dog </option>
<option value = "Cat"> Cat </option>
</select>";
and a variable $selAnimal
and a javascript function
function getSelectedItem(opt){
//$selAnimal = opt <- how do i do this?
}
As much as possible I wouldn't like the page to reload so I avoid putting this inside a form and submitting as I select. I can't get to make $.post method work. I know for a fact that this cannot be directly done since php is server side and javascript is client side.
I also thought of putting the selected value inside a hidden component(span or something) and get the value from it. But I have no idea how to get it from the component. I've also seen use of AJAX or jquery but I'm not really knowledgeable enough.
I need to save this value to the php variable since I'll be using it as basis for the options in my second dropdown. For example, if I choose Dog, the dropdown list would have dog breeds as options.
I've spent days looking for possible solutions everywhere. Help would be very much appreciated. Thank you!
here is the solution
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#animal').change(function(){
$.post('loadbreeds.php', { animal:$('#animal').val() },
function(data){
$('#breedList').html(data);
});
});
});
</script>
<form method="post" >
<div id="animalList">
<select id="animal" name="animal">
<option value="">--Select--</option>
<?php if (!empty($animals)) { foreach ($animals as $value) { ?>
<option value="<?php echo $value['animalKey']; ?>"><?php echo $value['animalName']; ?></option>
<?php }} ?>
</select>
</div>
<div id="breedList">
<select id="breed" name="breed">
<option value="">--Select--</option>
</select>
</div>
<input type="submit" value="Submit" />
</form>
code for loadbreeds.php
$animalKey = $_POST['animal'];
$breeds = selectByKey($animalKey); // code for selecting breeds
<select id="breed" name="breed">
<option value="">--Select--</option>
<?php if (!empty($breeds)) { foreach ($breeds as $value) { ?>
<option value="<?php echo $value['breedKey']; ?>"><?php echo $value['breedName']; ?></option>
<?php }} ?>
</select>
You cannot have the variable available to the same file since PHP declares all its variables before the JS even starts. You can however simply redirect the user to a new file where the variable is available.
Use something like this:
function getSelectedItem(opt){
location.href = location.href + "?selAnimal=" + opt;
}
In PHP, now you can use the selAnimal variable to display something different, like this:
$selectedAnimal = $_GET["selAnimal"];
if($selectedAnimal == "dog"){
// Whatever you want to do now
}
A better way would be to use POST with forms, but this should work fine for you as well.
Try the following, to rebuild the second dropdown:
http://jsfiddle.net/kAY7M/59/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
print "<script type=\"text/javascript\">var AnimalTypeList = [\"Dog1,Dog2,Dog3,Dog4\",\"Cat1,Cat2,Cat3,Cat4\"];</script>";
<script type="text/javascript">
$("#animal").change(function () {
var sel = $("#animal").prop("selectedIndex") - 1;
var list = AnimalTypeList[sel].split(",");
var Counter = list.length;
$("#type").children().remove();
for (var i = 0; i < Counter; i++) {
$("#type").append("<option value = '" + list[i] + "'> " + list[i] + "</option>");
}
})
</script>
I could do a pure Javascript only version too, but that is a bit more code.
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
I am trying to show and hide a few form fields depending on the value of one of my select fields. I am looking to use arrays to hold what should be shown and what should not be shown for each select value, to save me from a massive switch statement, but cannot figure out how to do it.
I am using PHP and jQuery. Any help would be great.
Try something like this:
<select id="viewSelector">
<option value="0">-- Select a View --</option>
<option value="view1">view1</option>
<option value="view2">view2</option>
<option value="view3">view3</option>
</select>
<div id="view1">
<!-- content -->
</div>
<div id="view2a">
<!-- content -->
</div>
<div id="view2b">
<!-- content -->
</div>
<div id="view3">
<!-- content -->
</div>
then in the jQuery:
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
});
});
There are a few different ways you could do this. The simplest is to have a few separate fieldsets, each one containing a single group of fields. Then, in jQuery, dependent on the select-menu's value you can show/hide these fieldsets, e.g.
<fieldset id="f1">
<input name="something1" />
<input name="something2" />
<input name="something3" />
</fieldset>
<fieldset id="f2">
<input name="something4" />
<input name="something5" />
<input name="something6" />
</fieldset>
<select name="fieldset-choice">
<option value="f1">Fieldset 1</option>
<option value="f2">Fieldset 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=fieldset-choice]').change(function(){
var fieldsetName = $(this).val();
$('fieldset').hide().filter('#' + fieldsetName).show();
});
// We need to hide all fieldsets except the first:
$('fieldset').hide().filter('#f1').show();
</script>
Note: For the above technique to be entirely unobtrusive you might want to dynamically build the select-menu with the names of all the different fieldsets.
Alternatively you can prefix each fields name with a meaningful prefix, and then hide/show according to that attribute:
<input name="group1-name1" />
<input name="group1-name2" />
<input name="group2-name3" />
<input name="group2-name4" />
<input name="group2-name5" />
<select name="field-choice">
<option value="group1">Group 1</option>
<option value="group2">Group 2</option>
</select>
<script type="text/javascript">
jQuery('select[name=field-choice]').change(function(){
var groupName = $(this).val();
$('input').hide().filter('[name^=' + groupName + ']').show();
});
// We need to hide all fields except those of the first group:
$('input').hide().filter('[name^=group1]').show();
</script>
To fire up the code on load, just add .change(). As shown below...
$(document).ready(function() {
$.viewMap = {
'0' : $([]),
'view1' : $('#view1'),
'view2' : $('#view2a, #view2b'),
'view3' : $('#view3')
};
$('#viewSelector').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
}).change();
});
My 2 cents :
I needed to show/hide fields depending on many previous select value (not only one).
So I add a parent attribute to div fields like this :
<div id="view" parent="none">
<select class=selector id="view">
<option value="0"> -- Make a choice --</option>
<option value="s1">sub 1</option>
<option value="s2">sub 2</option>
<option value="s3">sub 3</option>
</select>
</div>
<!-- you need to define the parent value with the value of parent div id -->
<div id="s1" parent="view">
<!-- if you want to have a selector be sure it has the same id as the div -->
<select class=selector id="s1">
<option value="0">-- Make a choice --</option>
<option value="s1_sub1">sub 1 of s1</option>
<option value="s1_sub2">sub 2 of s1</option>
<option value="s1_sub3">sub 3 of s1</option>
</select>
</div>
<!-- Make the same thing for s2 and s3
Define div s2 here
Define div s3 here
-->
<!-- and finally if that's your final step you put what you want in the div -->
<div id="s1_sub1" parent="s1">
You are inside s1 sub1
</div>
Now the jquery code :
$(document).ready(function() {
$('select[class=selector]').change(function() {
//next div to show
var selectorActive = $(this).val();
//div where you are
var parentValue = $(this).attr("id");
//show active div and hide others
$('div').hide().filter('#' + selectorActive).show();
while (parentValue!="none") {
//then show parents of active div
$('div[id=' + parentValue + ']').show();
//return the parent of div until "none"
parentValue = $('div[id=' + parentValue + ']').attr("parent");
}
});
// print only the first div at start
$('div').hide().filter("#view").show();
});
That's works like a charm and you don't need to define maps
I hope this will help
#Martin Try this
`$('#viewSelector').trigger('change');`
Here is a very simple example:
The purpose is to show A SIMPLE EXAMPLE of how to use an array of values to show/hide fields depending upon the value of a select.
In this demo, I could have used the classNames to show/hide the group of fields all-at-once -- but that's not the purpose of the example -- so the classNames were used only for CSS.
Because the demo uses IDs (with two arrays of these IDs) for the demo, it doesn't matter whether the fields to be hidden are input fields, divs, imgs or what-have-you. The ID identifies whatever-it-is-to-be-hid.
var aPeople = ['bob','sam','ted'];
var aTransport = ['car','bike','truck'];
$('#mySel').change(function(){
$('.alldiv').hide(); //Hide them all to start...
let sel = $(this).val(); //Get selected option value
if ( sel=='ppl' ){
for (let i=0; i<aPeople.length;i++){
$('#' + aPeople[i]).show();
}
}else if ( sel=='tpt' ){
for (let i=0; i<aTransport.length;i++){
$('#' + aTransport[i]).show();
}
}else{
//Choose selected
$('.alldiv').show();
}
});
.alldiv{width:30vw;height:10vh;padding:2vh 2vw;text-align:center;}
.ppl{background:palegreen;}
.tpt{background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="mySel">
<option value="">Choose:</option>
<option value="ppl">People</option>
<option value="tpt">Vehicles</option>
</select>
<div id="bob" class="alldiv ppl">People: Bob</div>
<div id="car" class="alldiv tpt">Vehicle: Car</div>
<div id="truck" class="alldiv tpt">Vehicle: Truck</div>
<div id="sam" class="alldiv ppl">People: Sam</div>
<div id="ted" class="alldiv ppl">People: Ted</div>
<div id="bike" class="alldiv tpt">Vehicle: Bike</div>