简体   繁体   English

单击图像时更改下拉选择的值

[英]Change value of dropdown select when image clicked

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: 将填充的下拉列表的id设置为“ddl”,并将图像的onClick事件设置为相应的函数,此Javascript应该这样做:

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. 使用on click事件处理程序更改选定的索引。

Fully functional example created in JSFiddle: http://jsfiddle.net/whizkid747/eDfZ5/ 在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM