Javascript confirm()无法正常工作

时间:2013-05-01 13:44:13

标签: javascript forms confirm

我有这个页面,我正在尝试确认输入文本字段与当前日期之间的日期。如果输入字段中的日期晚于当前日期,则需要确认框以确认它们正在记下正确的日期。因此,“确定”按钮需要完成提交数据,“取消”按钮需要将它们返回到AJAX表单。

if($('sdate' > curdate)) {
    confirm("The date you chose " + curdate + "is in the future OK to continue");
}

我还希望'sdate'显示在确认框中而不是curdate,但每当我尝试不再显示该表单时。

4 个答案:

答案 0 :(得分:2)

而不是

$('sdate' > curdate)
你可能想要

$('sdate').val() > curdate

这是日期的比较(作为字符串,但如果日期格式正确,则应该有效,对于输入类型为date或带有标准插件的文本类型的输入)。

请注意,您不使用confirm调用中返回的值。你通常会做类似

的事情
if ($('sdate').val() > curdate) {
    if (confirm("someText")) {
        // do something
    }
}

答案 1 :(得分:1)

你需要这样做:

var date1 = new Date($('#sdate').val());
var date2 = new Date(curdate);
if (date1 > date2 ) {
    confirm("The date you chose " + curdate + "is in the future OK to continue");
}
  • 元素未完全包裹。它应该是这样的$('#sdate')
  • '#'表示ID丢失。不确定,如果它是一个id或类。如果上课,添加一个'。'取代#

答案 2 :(得分:0)

在当前脚本中,confirm()调用实际上没有做任何事情。

你想要做的事情需要以某种形式加入以下内容。

if(confirm("The date you chose " + curdate + "is in the future OK to continue"))
    //Do stuff

按照你发布的内容和@dystroy发布的答案,你可能正在寻找

if($("#sdate").val() > curdate && confirm("The date you chose " + curdate + "is in the future OK to continue")
    //Do stuff

在上面的脚本中,两个条件都存在于一个条件中。根据@dystroy的回答,我已经包含了.val()调用。另一个变化是,假设您正在寻找id =“sdate”的元素,因此选择器包含id符号#

编辑(OP评论后) - Updated based on this stackoverflow post

如果您要阻止表单提交,那么您应该以与此类似的方式将该函数附加到表单

<form name="myForm" onsubmit="return validateMyForm();"> 

绑定事件后,您可以将代码更新为

if($("#sdate").val() > curdate && confirm("The date you chose " + curdate + "is in the future OK to continue")
    return true;
else
    return false;

如果确认返回true且满足日期不等式,则只应提交表格。

答案 3 :(得分:0)

我能够使用此

var d=$('sdate').value;

if(d > curdate)) {

  var dates confirm("The date you chose " + d + "is in the future OK to continue");
  if(!dates) return false;
}