Simulate javascript to select from dropdown

I am trying to simulate javascript to select from the dropdown below. I am trying to use this code here but it doesn't work.

$('select[name="srctype"]').val(2).trigger('change');

      

Am I doing something wrong here? Is my javascript flawed for this code layout below?

I'm trying to choose value="single"

<select name="srctype" class="formselect" onchange="typesel_change()">
    <option value="any" selected="selected">any</option>
    <option value="single">Single host or alias</option>
    <option value="network">Network</option>
    <option value="pptp">PPTP clients</option>
    <option value="pppoe">PPPoE clients</option>
    <option value="l2tp">L2TP clients</option>
    <option value="wan">WAN subnet</option>
    <option value="wanip">WAN address</option>
    <option value="lan">LAN subnet</option>
    <option value="lanip">LAN address</option>
</select>

      

0


source to share


3 answers


Try:

$('select[name="srctype"]').val('single')

      

or



$('select[name="srctype"] option:eq(1)').prop('selected',1)

      

As you noted in your comment, this worked for you:

(function ($) {
    $('select[name="srctype"]').val('single');
}).call(this, jQuery);

      

+1


source


Do it:

$('.formselect').val('single').trigger('change');

      



In your code, you are trying to set a val 2

that does not exist. The value you are interested in is actually single

as you mentioned in your question.

Here is a demo: http://jsbin.com/eXONuhu/1/

+4


source


var myVal = $('select[name="srctype"] option:eq(1)').attr('value');
$('select[name="srctype"]').val(myVal).trigger('change');

      

Or an optimized version

var mySelect = $('select[name="srctype"]');
var myVal = $('option:eq(1)', mySelect).attr('value');
mySelect.val(myVal).trigger('change');

      

Fiddle - http://jsfiddle.net/P6Ayz/1/

0


source







All Articles