jQuery:输入值返回undefined

时间:2014-02-07 12:37:10

标签: jquery text javascript-events input

我正在使用https://github.com/eternicode/bootstrap-datepicker并希望在更改日期时触发ajax调用。

首先要通过插入 - {插入changeDate事件来确定何时更改日期。然后将文本框中的值警告到屏幕...

http://bootstrap-datepicker.readthedocs.org/en/latest/events.html#changedate

这是我的小提琴......

http://jsfiddle.net/MangoMM/nY5C6/3/

HTML

<div class="input-group date">
    <input class="form-control" placeholder="Select Date" readonly="1" 
        data-provide="datepicker" data-date-format="yyyy-mm-dd" 
        data-date-start-date="today()" data-date-autoclose="true" 
        data-date-days-of-week-disabled="[2,4,6,0]" 
        data-date-today-highlight="1" name="appointment[date]" 
        type="text" id="appointment[date]" /> 
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

的jQuery

$(".input-group.date").on('changeDate', function(){
    alert(event.type + " is fired: " + $('#appointment[date]').val());
});

我尝试了各种组合,包括$(this).val()和其他组合,但没有运气......

为什么我的输入值显示为未定义?如何在文本框中获取值?

4 个答案:

答案 0 :(得分:1)

您需要使用两个反斜杠转义[]:\\。

alert(event.type + " is fired: " + $('#appointment\\[date\\]').val());

DEMO

来自Docs

  

使用任何元字符(例如!“#$%&amp;'()* +,。/:;&lt; =&gt;?@ [] ^`{|}〜)作为文字作为名称的一部分,必须使用两个反斜杠进行转义:\\。

此外,您需要将event传递给事件处理程序

完整代码

$(".input-group.date").on('changeDate', function(event){
    alert(event.type + " is fired: " + $('#appointment\\[date\\]').val());
});

答案 1 :(得分:1)

试试这个

console.log($(".form-control").val());

[]是一个属性选择器。

换句话说,$('.form-control[data-provide="datepicker"]').val()有效。

答案 2 :(得分:0)

你使用jsf框架吗? 如果是这样,您可以尝试使用Firebug并检查外观元素ID。

此框架通常会在真实ID之前生成“ form:”。

您可以尝试

$("#form\\:appointment\\[date\\]").val();

答案 3 :(得分:-1)

首先,你需要将事件传递给函数并逃避破解者

$(".input-group.date").on('changeDate', function(event){
   //                                             ^event
    alert(event.type + " is fired: " + $('#appointment\\[date\\]').val());
    //                                                ^^     ^^ escape brackers
});

DEMO