Buttons instead of select

2019-06-10 07:04发布

问题:

I'm working on a site and i want to use icons to select travel modes, i have a working function but it only works with a selection input. Is there a way to modify it to be used with buttons?

Thanks in advance!

Function:

function calcRoute() {
  var selectedMode = document.getElementById("mode").value;
  var request = {
      origin: thuis,
      destination: kabk,
      // Note that Javascript allows us to access the constant
      // using square brackets and a string value as its
      // "property."
      travelMode: google.maps.TravelMode[selectedMode]
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });

HTML - Select input

<select id="mode" onchange="calcRoute();">
    <option value="DRIVING">Driving</option>
    <option value="WALKING">Walking</option>
</select>

HTML - Button input (?)

<form id="mode">
    <input type="button" onchange="calcRoute();" value="DRIVING">
    <input type="button" onchange="calcRoute();" value="WALKING">
</form>

回答1:

There is no onchange event for buttons. Use the onclick event instead

<form id="mode">
    <input type="button" onclick="calcRoute(this);" value="DRIVING" />
    <input type="button" onclick="calcRoute(this);" value="WALKING" />
</form>

Edit And you have to adjust your calcRoute function

From

function calcRoute() {
   var selectedMode = document.getElementById("mode").value;
   //...

To

function calcRoute(btn) {
    var selectedMode = btn.value;
    // ...


回答2:

function calcRoute(ev) {
    var ev = ev || window.event,
        btn = (ev.target || ev.srcElement);
    var selectedMode = btn.value;  //"this" will return the element in the demo
    var request = {
        origin: thuis,


<form id="mode">
            <!--Use onClick-->
    <input type="button" onclick="calcRoute(ev);" value="DRIVING" />
    <input type="button" onclick="calcRoute(ev);" value="WALKING" />
</form>

:) WORKING DEMO: http://jsfiddle.net/DerekL/T7NrF/