0

This input select field is generated dynamically, the options will change depending on what the user has selected in the previous fields.

<select name="vehicle">
    <?php $loop = new WP_Query( array( 'post_type' => 'fleet') ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <option class="vehicle-option" value="<? the_title() ?>" <?= $_POST["vehicle"] ==                     the_title('', '', false) ? "selected" : "" ?>>
    <?php the_title(); ?>
    </option>
    <?php endwhile; wp_reset_query(); ?>
</select>

And because these options have been generated dynamically, I’m unable to select that field with Jquery. (I can select it with CSS but I need to apply validation to this field because it's a required field that the user has to select).

The code below won't select it, I’ve also tried adding ID and class tags to and around the field but they all failed.

$('select[name=vehicle]’)………

Because eventually I want to be able to select the options inside this field as well;

$('select[name=vehicle]').change(function(){ 
    if($("select[name=vehicle] option:selected").val() !== "Vehicle preference"){
    //run function
    }
    else{
    //run function
    }
}

2 Answers2

2

You can use event delegation for dynamically created elements:

$(document).on('change', 'select[name = vehicle]', function () {
    if ($(this).find("option:selected").val() !== "Vehicle preference") {
        //run function
    } else {
        //run function
    }
});
Felix
  • 36,929
  • 7
  • 39
  • 54
  • Thanks Felix! Do you know how I can select one of the options without the select field having to change (but perhaps when the submit button is clicked? – user3540018 Apr 16 '14 at 07:21
  • Do you means set the `select` value programmatically without user's interaction? Otherwise I don't understand what you means :/ – Felix Apr 16 '14 at 07:26
  • I need to be able to select that input select field without having to touch it. – user3540018 Apr 16 '14 at 07:27
  • What do I put in between the speech marks and paranthesis in order to be able to say... add a class. $("?").addClass("required") – user3540018 Apr 16 '14 at 07:29
  • You can use `.prop()`: `$('select').prop('selectedIndex', 3);` which set 4th option in your select as selected value – Felix Apr 16 '14 at 07:29
  • I wanna be able to select the – user3540018 Apr 16 '14 at 07:30
0

if you want to select a dynamically generated element try using jquery's 'on' function.(if using jquery version less than 1.7 then use 'live' function)

Shaminder Singh
  • 1,243
  • 2
  • 17
  • 29