开发者

Change Form Option through a function with JS or jQuery?

开发者 https://www.devze.com 2023-04-12 15:50 出处:网络
I\'m workin开发者_JAVA百科g on an form based website. <select name=\"foo\" id=\"foo\"> <option value=\"1\">1</option>

I'm workin开发者_JAVA百科g on an form based website.

<select name="foo" id="foo">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

I need to allow options to be saved by users based on previous choices.

My first attempt was to add the following HTML(with php) to the option of the users choice.

selected="selected"

However the site has some functions which change the rest of the form based on the user's choice.

$('#foo').change(function(event) {
....
}

Is it possible to have the option changed via a function(using jQuery or JS)? Thus triggering the function waiting for #foo to be changed?


You could use the .val() method:

$('#foo').val('2');

which will preselct the element with value="2" and also trigger the change event handler. Or with pure javascript:

document.getElementById('foo').value = '2';

And to trigger the change event manually you could do this:

$('#foo').change();


Setting the value will NOT trigger the change event. You can just programatically trigger it by doing the following.

$('#foo').trigger('change');  // this should run the change code. 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号