2016-12-10 24 views
0

如果另一個字段的值發生更改,我需要更新一個字段的值。我想要更新的字段包含時間戳,並且其值可能更改的字段包含日期(yyyy-MM-dd)。通過日曆選擇器進行更改,這可能是onchangeoninput事件無法調用該函數的原因。使用日曆選擇器更新另一個onchange輸入值

這裏是我的代碼:

<input required class="short" type="text" id="startdate" name="startdate" value="<?php echo (isset($startdate) ? $startdate : "") ?>" oninput="updateTimestamp();" /> 
    <input required class="short" type="text" id="startdate_u" name="startdate_u" value="<?php echo (isset($startdate_u) ? $startdate_u : "") ?>" /> 
    <a href="#" onclick="cal.select(document.forms['project'].startdate,'anchor','yyyy-MM-dd'); return false;" name="anchor" id="anchor"><img src="images/calendar_icon.png" /></a> 
    <script> 
     var cal = new CalendarPopup(); 
     function popup(mylink, windowname) { 
      if (! window.focus)return true; 
       var href; 
      if (typeof(mylink) == 'string') 
       href=mylink; 
      else 
       href=mylink.href; 
      window.open(href, windowname, 'width=500,height=300,scrollbars=yes,resizable=yes'); 
      return false; 
     } 
     function updateTimestamp() { 
      var startDate = document.getElementById("startdate"); 
      var newTimestamp = Math.round(new Date(startDate.value).getTime()/1000); 
      document.getElementById("startdate_u").value = newTimestamp.toString(); 
     } 
    </script> 

這裏的日曆代碼的鏈接:http://www.mattkruse.com/javascript/calendarpopup/source.html

我沒有使用JQuery。 您的建議是非常感謝:) 整個網站是根據HTML5標準寫 - 我讀oninput應該做的伎倆,然後它不。在Chrome和IE 11上測試。

+0

對於'startDate'和'Math.round(new Date(startdate)'這個變量沒有大寫的** D **,你沒有得到'.value''嘗試'Math。 (新的日期(startDate.value).getTime()/ 1000);' – NewToJS

+0

你是對的,我只是輸入這些解釋錯別字,早些時候我用'.value'和兩個都試過,甚至沒有一個簡單的' alert()'被觸發 – cheeseus

+0

剛試過'Math.round(new Date(startDate.value).getTime()/ 1000);'too - nothing。我認爲問題在於'oninput'事件沒有因爲我使用日曆選擇器更改日期,但不知道如何解決此問題。 – cheeseus

回答

1

此日曆還定義了一個setReturnFunction,它需要函數的名稱才能得到結果。

所以我認爲你需要將它設置爲將接收結果的函數的名稱,填入你的輸入並觸發你可能喜歡的任何其他功能。

喜歡的東西:

<script> 
    function dateSelected(y,m,d){ 
    // Fill in your input as probably it will not be filled. 
    // Trigger any additional functionality 
    updateTimestamp(); 
    var dateField = document.getElementById("startdate"); 
    dateField.value = y + "-" + m + "-" + d; 
    } 

    var cal = new CalendarPopup(); 
    cal.setReturnFunction('dateSelected'); 
    function popup(mylink, windowname) { 
    if (! window.focus)return true; 
    var href; 
    if (typeof(mylink) == 'string') 
    href=mylink; 
    else 
    href=mylink.href; 
    window.open(href, windowname, 'width=500,height=300,scrollbars=yes,resizable=yes'); 
    return false; 
    } 

    function updateTimestamp() { 
    var startDate = document.getElementById("startdate"); 
    var newTimestamp = Math.round(new Date(startDate.value).getTime()/1000); 
    document.getElementById("startdate_u").value = newTimestamp.toString(); 
    } 
    </script> 

注:在代碼中不少東西可以改善,開始與日曆。

相關問題