简体   繁体   中英

How to execute function on 'select` element with javascript/jquery

I am trying to set the default value of a dropdown box which looks like this:

         <select id="schedule_timeslot" name="timeslot">
            <option name="8-10" class="schedule_time" value="0" id="ts0">8am - 10am</option>
            <option name="10-12" class="schedule_time" value="1" id="ts1">10am-12pm</option>
            <option name="12-2" class="schedule_time" value="2" id="ts2" >12pm - 2pm</option>
            <option name="2-4" class="schedule_time" value="3" id="ts3">2pm - 4pm</option>
            <option name="4-6" class="schedule_time" value="4" id="ts4" >4pm - 6pm</option> 
        </select>

Based on a URL that looks like this:

http://localhost:8888/wordpress/wp-admin/admin.php?page=Add_Customer&type=add&id=21&date=11/15/2013&timeslot=d3_0

The dropdown has timeslots which a user can select to when booking an appointment. The URL has the timeslot value ( timeslot=d3_0 ). To do this I was going to add selected="selected" attribute to the respective <option> . The problem I'm having is that I can't figure out how to execute the algorithm on the selection using jQuery or JavaScript.

I tried using some of the jQuery function like .load() and .on , but all these need an event (click, mouseover, etc).

So my question is, how do I execute a function on the element I need to? I should also add that I am doing this in a plugin that I'm creating for Wordpress.

I'm not sure I quite =understand but check out the following jQuery and let me know if it helps

//This listens for when a different option is selected
$('select#schedule_timeslot').change(function() {
    var selectedOptionValue = $(this).val();  //0,1,2 .. etc
    var selectedId = $(this).attr("id");
});

To programmably select a desired option

$('select#schedule_timeslot').val(desiredValueStr);

Not sure if i understand correctly your question but:

For example, to select a default value of zero makes this

$( document ).ready(function() {
  $("schedule_timeslot").val("0")
});

Edit 1:

Maybe someyhing like this;

  $( document ).ready(function() {

  var qs = GetQSParameterByName("timeslot");

     if(qs !=null){
     $("schedule_timeslot").val(qs ) // your value

     }
});

    // read query string from url
     function GetQSParameterByName(name) {

        var match = RegExp('[?&]' + name.toLowerCase() + '=([^&]*)')
              .exec(window.location.search.toLowerCase() );

        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    }

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