1

I am trying to simulate a javascript to choose from the dropdown list below. I am trying this code here but its not working.

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

Am i doing something wrong here? Is my javascript messed up for this layout of code below?

I am 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>

3 Answers 3

5

Do this:

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

In your code you're trying to set a val 2 that doesn't exist. The value you're interested is actually single as you mention in your question.

Here's a demo: http://jsbin.com/eXONuhu/1/

Sign up to request clarification or add additional context in comments.

1 Comment

So i tried your script replacing formselect with srctype and i get this error TypeError: Cannot call method 'val' of null
1

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);

13 Comments

Ah i got an error sayingg TypeError: Cannot call method 'val' of null
You're using jQuery syntax so you need to include the jQuery library. Are you?
Well this is on a website im just trying to make an auto script its already loaded.
Well, my solution works as you can see from the jsFiddle link I posted. You'll need to figure out if you're loading jQuery.
Yes it worked! (function ($) { $('select[name="srctype"]').val('single'); }).call(this, jQuery); worked perfectly.
|
0
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.