简体   繁体   English

jQuery-在选择输入中获取选择的选项的值

[英]jquery - get the value of a selected option in a select input

I'm quite a newbie when it comes to jquery. 关于jQuery,我是一个新手。 I'm using cakePHP and I have a form to register orders for a selected user, the select input for selecting the user looks like this in cakePHP: 我正在使用cakePHP,并且有一个表单可以为所选用户注册订单,用于选择用户的选择输入在cakePHP中如下所示:

echo $this->Form->input('user_id');

and that renders a form with an input like this: 并使用以下输入呈现一个表单:

<label for="OrderUserId">User</label>
<select name="data[Order][user_id]" id="OrderUserId">
    <option value="2"> User 2</option>
    <option value="3"> User 3</option>
</select>

I want to do an ajax call so that, when a user is selected, his info appears in a div. 我想进行ajax调用,以便在选择用户时,他的信息出现在div中。 So far, I have this javascript: 到目前为止,我有这个javascript:

$(document).ready(function(){
    $("#OrderUserId").change(function() {
        $.ajax({
            url: 'users/getData' //here would go the user ID
        });
    });
});

My question is this: how can I get the value of the selected option with jQuery so that I can pass it to the url in the ajax method? 我的问题是:如何使用jQuery获取所选选项的值,以便可以将其传递给ajax方法中的url?

Just use plain js this.value . 只需使用普通js this.value this inside your callback represents the dom element so you would just access its value using .value . 回调中的this代表dom元素,因此您可以使用.value访问它的值。

$(document).ready(function(){
    $("#OrderUserId").change(function() {
         //var user = this.value;
        $.ajax({
            url: 'users/getData/' + this.value //here would go the user ID
        });
    });
});

Fiddle 小提琴

$(document).ready(function(){
    $("#OrderUserId").change(function() {
        var _this=$(this);
        $.ajax({
            url: 'users/getData'+_this.val(); //here would go the user ID
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM