简体   繁体   中英

Change value of a select list using onclick in href

I want to change the select box value using the onClick function of .

 <form>
      <select id="action">
         <option value="a">Add</option>
         <option value="b">Delete</option>
      </select>
 </form>

<a href="#" onClick="">Add</a> 
<a href="#" onClick="">Delete</a> 
 <form>
      <select id="action">
         <option value="a">Add</option>
         <option value="b">Delete</option>
      </select>
 </form>

<a href="#" onClick="document.getElementById('action').value='a'">Add</a> 
<a href="#" onClick="document.getElementById('action').value='b'">Delete</a> 

OR U can also call this Java Script function for doing this =

function changeval()
{

if(document.getElementById('action').value =='b')
document.getElementById('action').value='a'
else
document.getElementById('action').value='b'

}

<a href="#" onClick="changeval()">Add</a> 
<a href="#" onClick="changeval()">Delete</a> 

I used a jquery .click and gave an id to the select element This is the html code

<select id="carsList">
  <option value="volvo" id="#volvoOption">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi" id="#audiOption">Audi</option>
</select>

<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRgoru_AtWqrY6DWtmVlOvtYoxpdGHlheWUKgn0jpy0R7Z2VjjjDBh78cx1" id="volvoLogo">
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQBKzqqECaAC5n-cij4sToayeEAjQqAzYcIrRDj1MeP5vo5OlUCvq_CPWHx" id="audiLogo">

And this is the jquery code I used

$( document ).ready(function() {

    $("#volvoLogo").click(function(){
          $("#carsList option[value='volvo']").attr('selected', 'selected');
    });

    $("#audiLogo").click(function(){
         $("#carsList option[value='audi']").attr('selected', 'selected');
    });
});

I think this is where you are looking for:

<script type="text/javascript">
function changeValue(selectBox, value) {
  selectedItem = selectBox[selectBox.selectedIndex];
  selectedItem.value = value;
}
</script>

In the onclick you place"

    changeValue(document.getElementById("action"), "your value");

from: http://www.webdeveloper.com/forum/showthread.php?t=160118

<form>
  <select id="action">
     <option value="a">Add</option>
     <option value="b">Delete</option>
  </select>
</form>

<a href="#" onClick="action.value='a'">Add</a> 
<a href="#" onClick="action.value='b'">Delete</a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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