简体   繁体   English

使用DateTimePicker插件时,无法使用jquery获取用户输入的值

[英]Cannot grab the value of the user's input with jquery while using DateTimePicker plugin

Hey StackOverflow wizards! 嘿StackOverflow巫师! I'm not quite sure what I'm doing wrong, but maybe you can help me. 我不太确定我做错了什么,但也许你可以帮助我。

I'm building a giant form wizard with lots of user input. 我正在构建一个包含大量用户输入的巨型表单向导。 The form has multiple tabs and on the first page I have an input where the user chooses a Start Date and an input where a user chooses an End Date. 表单有多个选项卡,在第一页上我有一个输入,用户选择一个开始日期和一个用户选择结束日期的输入。 The last tab is a summary of all of the user's chosen inputs. 最后一个选项卡是所有用户所选输入的摘要。

I'm trying to grab the value of the Start Date and End Date and spit them into a span element on the last tab of the form wizard. 我正在尝试获取开始日期和结束日期的值,并将它们吐出到表单向导的最后一个选项卡上的span元素中。 I'm using the DateTimePicker plugin here . 我在这里使用DateTimePicker插件。

Here is my HTML: 这是我的HTML:

<div class="row">
  <div class="col-md-9">
    <label class="control-label">Start Date</label>
    <p><span id="confirmation-start-date"></span></p>
  </div>
</div>
<div class="row">
  <div class="col-md-9">
    <label class="control-label">End Date</label>
    <p><span id="confirmation-end-date"></span></p>
  </div>
</div>

<div class="row">
  <div class="col-md-9">
    <label class="control-label">Start Date</label>
    <p><span id="confirmation-start-date"></span></p>
  </div>
</div>
<div class="row">
  <div class="col-md-9">
    <label class="control-label">End Date</label>
    <p><span id="confirmation-end-date"></span></p>
  </div>
</div>

And my JQuery: 而我的JQuery:

var projectStartDate = $('#project-start-date').blur(function() {
  $('#project-start-date').data('DateTimePicker').date();
  console.log(projectStartDate);
});
$('#confirmation-start-date').text(projectStartDate);

//get the value of End Date and spit it onto the summary page
var projectEndDate = $('#project-end-date').blur(function() {
  $('#project-end-date').data('DateTimePicker').date();
  console.log(projectEndDate);
});
$('#confirmation-end-date').text(projectStartDate);

With this current code text stating [Object object] gets returned in the 's for those inputs. 使用此当前代码文本,说明[Object object]在这些输入的s中返回。

Console.log also returns an object, rather than a value. Console.log还返回一个对象,而不是一个值。

I'm super new to jquery/javascript and any help is appreciated. 我是jquery / javascript的新手,任何帮助表示赞赏。

Thanks in advance! 提前致谢!

My Full Javascript Code: 我的完整Javascript代码:

< script type = "text/javascript" >
  //Escrow Form Validations
  $().ready(function() {
    $(".no input").radio('check');

    var $validator = $("#wizardForm").validate({
      rules: {
        email: {
          required: true,
          email: true,
          minlength: 5
        },
        first_name: {
          required: false,
          minlength: 5
        },
        last_name: {
          required: false,
          minlength: 5
        },
        price: {
          number: true
        }
      }
    });

    //Tab Control for Form Wizard
    $('#wizardCard').bootstrapWizard({
      tabClass: 'nav nav-pills nav-pills-blue',
      nextSelector: '.btn-next',
      previousSelector: '.btn-back',
      onNext: function(tab, navigation, index) {
        var $valid = $('#wizardForm').valid();

        if (!$valid) {
          $validator.focusInvalid();
          return false;
        }
      },
      onInit: function(tab, navigation, index) {

        //check number of tabs and fill the entire row
        var $total = navigation.find('li').length;
        $width = 100 / $total;

        $display_width = $(document).width();

        if ($display_width < 600 && $total > 3) {
          $width = 50;
        }

        navigation.find('li').css('width', $width + '%');
      },
      onTabClick: function(tab, navigation, index) {
        // Disable the posibility to click on tabs
        return false;
      },
      onTabShow: function(tab, navigation, index) {
        var $total = navigation.find('li').length;
        var $current = index + 1;

        var wizard = navigation.closest('.card-wizard');

        // If it's the last tab then hide the last button and show the finish instead
        if ($current >= $total) {
          $(wizard).find('.btn-next').hide();
          $(wizard).find('.btn-finish').show();
        } else if ($current == 1) {
          $(wizard).find('.btn-back').hide();
        } else {
          $(wizard).find('.btn-back').show();
          $(wizard).find('.btn-next').show();
          $(wizard).find('.btn-finish').hide();
        }
      }
    });
  });

$().ready(function() {
  //Max amount of milestones
  var max_milestone = 5

  // Initial Milestone Count
  var x = 1;

  //function for add milestone button
  //if button.add-milestone is clicked
  $('.add-milestone').click(function(e) {
    //console.log('dope')
    e.preventDefault();
    if (x < max_milestone) { // if the milestone count is smaller than 5
      x++; //increment milestones
      $('.additional-milestones').before('<div class="milestone"><h4>Milestone #1</h4><div class="row"><div class="col-md-5"><div class="form-group"><label class="control-label">Milestone Title</label><input class="form-control" type="text" name="Milestone[' + (x - 1) + '][MilestoneTitle]" placeholder="Dusty Bench" required /></div></div></div><div class="row"><div class="col-md-5"><div class="form-group"><label class="control-label">Deadline</label><input type="text" class="form-control datetimepicker" name="Milestone[' + (x - 1) + '][MilestoneTitle]" placeholder="Deadline" required/></div></div></div><div class="row"><div class="col-md-5"><div class="form-group"><label class="control-label">Milestone Description</label><textarea class="form-control" id="exampleTextarea" name="Milestone[' + (x - 1) + '][MilestoneTitle]" rows="3" required> </textarea></div></div></div><div class="row"><div class="col-md-5"><a class="delete-milestone btn btn-danger"> - Delete This Milestone</a></div></div><hr></div>');
      $('.delete-milestone').click(function() {
        //console.log('dope')
        $(this).parents(".milestone").remove();
      });
    }
  });
  //then
  //populate with milestone form with Milestone+Next Milestone Number

  //Delete Milestone 
});

//Buying extra TB of Storage
//If 'yes' radio dial is chosen
//show TB input and submit
$('.yes input').on('toggle', function() {
  $(".buy-more-storage").show('slow');
  $(".no input").radio('uncheck');
});

$('.no input').on('toggle', function() {
  $(".buy-more-storage").hide('slow');
  $(".yes input").radio('uncheck');
});

///Date-Time Picker Classes
$('.datetimepicker').datetimepicker({
  icons: {
    time: "fa fa-clock-o",
    date: "fa fa-calendar",
    up: "fa fa-chevron-up",
    down: "fa fa-chevron-down",
    previous: 'fa fa-chevron-left',
    next: 'fa fa-chevron-right',
    today: 'fa fa-screenshot',
    clear: 'fa fa-trash',
    close: 'fa fa-remove'
  },
  format: 'MM/DD/YYYY',
});

//Function for flaring error if picked date is before current date
//if(pickedDate <=todaysDate){
//return true;
//}
//else{
//return false;
//}

//If 'Buyer' is chosen from the Role dropdown menu then the buyer's choices are shown
$('#project-role').on('change.states', function() {
  $(".buyer-choices").toggle($(this).val() == 'Payer');
}).trigger('change.buyer-choices');

//If 'Asset-Producer' is chosen from the Role dropdown menu then the Asset Producer's choices are shown
$('#project-role').on('change.states', function() {
  $(".asset-producer-choices").toggle($(this).val() == 'Payee');
}).trigger('change.asset-producer-choices');

//If 'Credit-Card' is chosen from the Payment Options
$('#payment-type').on('change.states', function() {
  $(".credit-card-form").toggle($(this).val() == 'credit-card');
}).trigger('change.credit-card-form');

//If 'Link Bank Account' is chosen from the Payment Options
$('#payment-type').on('change.states', function() {
  $(".link-bank-account").toggle($(this).val() == 'bank-transfer');
}).trigger('change.link-bank-account');

//If 'Credit-Card' is chosen from the Project Setup Fee
$('#projectFeePayment').on('change.states', function() {
  $(".projectFeePaymentCCForm").toggle($(this).val() == 'projectFeePaymentCC');
}).trigger('change.projectFeePaymentCCForm');

//If 'Link Bank Account' is chosen from the Project Setup Fee
$('#projectFeePayment').on('change.states', function() {
  $(".projectFeePaymentBAForm").toggle($(this).val() == 'projectFeePaymentBT');
}).trigger('change.projectFeePaymentBAForm');

//Send Escrow Project button at end of wizard
function onFinishWizard() {
  //Affirmation of project being
  $('#wizardForm').submit(function(e) {
    var postData = $(this).serializeArray();
    var formURL = "<?php echo $portalfqdn; ?>" + $(this).attr("action");
    $.ajax({
      url: formURL,
      type: "POST",
      data: postData,
      success: function(data) {
        //var emailResult = jQuery.parseJSON(data);
        if (data.Message.Code === "00") {
          swal({
            title: "Success!",
            text: "Your new escrow project has been sent for approval! Look out for an alert indicating when your project has been approved!",
            type: "success",
            confirmButtonText: "Ok",
          });
        } else {
          swal({
            title: "Error!",
            text: "There was a problem with your form submission.",
            type: "error",
            confirmButtonText: "Fix Errors",
          });
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        $('#email-search-result').removeClass("success");
        $('#email-search-result').addClass("error");
        $('#email-search-result').html("An error occurred.");
      }
    });
    e.preventDefault(); //STOP default action
  });

  $('#wizardForm').submit(); //Submit  the FORM

  //If there are errors flag this message, change button to go back to form to address these errors 
  //$('.sweet-confirm.btn.btn-info.btn-fill').click(function(){
  //replace this with ajax submit
  //window.location.href='updated-escrow-list.html';
  //$('#wizardForm').submit(); //Submit  the FORM
};


//get the value of project name and spit it onto the summary page
$('.ProjectName').keyup(function() {
  $('#confirmation-project-name').text($(this).val());
});

//Begin get start and end dates of project and spit them onto summary tab
$().ready(function() {
  var projectStartDate;
  var projectEndDate;

  $('#project-start-date').blur(function() {
    projectStartDate = $(this).val();
  });

  $('#project-end-date').blur(function() {
    projectEndDate = $(this).val();
  });

  console.log(projectStartDate);
  console.log(projectEndDate);

  $('#confirmation-start-date').html(projectStartDate);
  $('#confirmation-end-date').html(projectEndDate);
});
//End----------------------------------------------------//

//get the value of project collaborator and spit it onto the summary page
$('.collaborator').keyup(function() {
  $('#confirmation-collaborator').text($(this).val());
});

//get the value of project deliverable description and spit it onto the summary page
$('.ProjectDeliverable').keyup(function() {
  $('#confirmation-project-deliverable').text($(this).val());
});

//get the value of project role and spit it onto the summary page
$('.ProjectRole').change(function() {
  var selectedText = $(this).find("option:selected").text();
  $('#confirmation-project-role').text(selectedText);
});

//if .ProjectRole is Buyer then show chosen payment method

//if .ProjectRole is asset-producer then show chosen payment recieving method

//get the value of project amount and spit it onto the summary page
$('.ProjectAmount').keyup(function() {
  $('#confirmation-project-amount').text($(this).val());
  console.log($('#confirmation-project-amount').text());
});

var projectAmount = parseInt($('#confirmation-project-amount').text());
console.log(projectAmount);

//search for a user by email address to see if they have a Stratuscore account
$('#email-search').click(function(e) {
  if ($('#ProjectPartner').val() === '') {
    return false;
  }
  var postData = {
    Email: $('#ProjectPartner').val(),
    ApiAction: "find-user-by-email"
  }

  var formURL = "<?php echo $portalfqdn; ?>account-api.php";
  $.ajax({
    url: formURL,
    type: "POST",
    data: postData,
    success: function(data) {
      //var emailResult = jQuery.parseJSON(data);
      if (data.Message.Code === "00") {
        $('#email-search-result').removeClass("error alert alert-danger");
        $('#email-search-result').addClass("success alert alert-success");
      } else {
        $('#email-search-result').removeClass("success");
        $('#email-search-result').addClass("error alert alert-danger");
      }
      $('#email-search-result').html(data.Message.Description);
      $('#email-search-result').show();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      $('#email-search-result').removeClass("success");
      $('#email-search-result').addClass("error");
      $('#email-search-result').html("The user you are searching for wasn't found. Please check the email entered and try again.");
    }
  });
  e.preventDefault(); //STOP default action
}); < /script>

SOLUTION

After much frustration at myself for being a javascript novice, I realized I had a scope issue on my hands and instead wrote functions to handle the DOM updating and passed the variables as parameters to those functions. 在成为一名javascript新手后,我感到非常沮丧,我意识到我手上有一个范围问题,而是编写了处理DOM更新的函数,并将变量作为参数传递给那些函数。 Works for now! 现在工作!

//Begin get start and end dates of project and spit them onto summary tab
function updateStartDate (projectStartDate) {
    $('#confirmation-start-date').html(projectStartDate);
    console.log(projectStartDate);
}

function updateEndDate (projectEndDate) {
    $('#confirmation-end-date').html(projectEndDate);
    console.log(projectEndDate);
}

$('#project-start-date').blur(function() {
    var projectStartDate = $(this).val();
        //console.log(projectStartDate);
    updateStartDate(projectStartDate);
});

$('#project-end-date').blur(function() {
    var projectEndDate = $(this).val();
        //console.log(projectEndDate);
    updateEndDate(projectEndDate);
});

One of the great things about jQuery is that almost all its methods return the element on which they're called, thus allowing you to chain a bunch of them together. 关于jQuery的一个好处是它几乎所有的方法都返回它们被调用的元素,因此允许你将它们串起来。 However, because the methods almost always return an element , something like this... 但是,因为这些方法几乎总是返回一个元素 ,就像这样......

var projectStartDate = $('#project-start-date').blur( ... );

... is just going to set projectStartDate = $('#project-start-date'); ...只是要设置projectStartDate = $('#project-start-date'); , rather than its value. 而不是它的价值。 I've created a brief example to demonstrate this here . 我已经创建了一个简短的例子来证明这一点


If you want to set projectStartDate equal to the value of this field, consider something like the following... 如果要将projectStartDate设置projectStartDate等于此字段的 ,请考虑以下内容...

var projectStartDate;
var projectEndDate;

$('#project-start-date').blur(function() {
    projectStartDate = $(this).val();
});

$('#project-end-date').blur(function() {
    projectEndDate = $(this).val();
});

$('#confirmation-start-date').html(projectStartDate);
$('#confirmation-end-date').html(projectEndDate);

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

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