2017-04-05 25 views
0

第一次問一個問題,讓我知道如果我做錯了。我有一個AppleScript從Numbers文檔獲取值,並使用document.getElementById將它們輸入到webform的各個字段中。AppleScript - 如果document.getElementById值爲null,則輸入值

它完美的作品,但現在我想添加一個功能,使其中填入值若在該網頁表單字段爲空。

我對代碼的想法將是這樣的:

if ("document.getElementById('something').value = null) 
      execute javascript ("document.getElementById('something').value = '" & valueToFillIn & "'") 
else 
    move on 

有人可以告訴我的最佳方式來檢查document.getElementByIdnull,然後如何進行?非常感謝!

+0

你做第一次海報罰款。歡迎來到StackOverflow!我只做了一些小的格式改進。某些語言的語法最好可以標記爲代碼,即使是在句子中也是如此(反向換行)。 – trincot

回答

0

下面有一個非常簡單的可替代選擇爲好。修改您的需求。我相信它很好地解釋了這個腳本中正在發生的事情。 else語句不需要「繼續前進」。一旦選中if語句,腳本就會繼續運行,而不需要else,除非您想在該字段有值時執行其他操作。

-- Tested Here -> http://meyerweb.com/eric/tools/dencoder/ 

set fieldValue to getInputById("dencoder") of me 

if fieldValue is "" then 
    inputByID("dencoder", "Im Allowed to Input Text Because You Were Empty") of me 
else 
    say "The Field Was Not Empty" 
end if 


-- Simple Handlers 
-- Retrieve Value of elementById 
to getInputById(theId) 
    tell application "Safari" 
    set output to do JavaScript "document.getElementById('" & theId & "').value;" in document 1 
end tell 
return output 
end getInputById 

-- Input My String to element by Id 
to inputByID(theId, theValue) 
    tell application "Safari" 
    do JavaScript " document.getElementById('" & theId & "').value ='" & theValue & "';" in document 1 
end tell 
end inputByID 
0

在使用此代碼段之前,您必須考慮幾件事情:

1-當此代碼將被觸發?定期點擊eventListener,如下面的示例:

2-您要發佈哪個值?請更具體一些。

document.getElementById("myButton").addEventListener("click", checkInputs); 

function checkInputs() { 
    if (document.getElementById("01").value == ""){ 
     var newValue = document.getElementById("02").value; 
     document.getElementById("demo").innerHTML=newValue; 
    } 
} 

https://jsfiddle.net/azwt542p/2/

有幾種方法來獲取輸入文本框的值直(無包裝形式元素中的input元素):

這些方法會返回元素的集合,所以使用[whole_number] 以獲得所需的出現次數,對於第一個元素使用[0]和對於 第二個使用1,依此類推......

選擇1:

使用document.getElementsByClassName('class_name')[whole_number].value 它返回一個直播的HTMLCollection

EG。 document.getElementsByClassName("searchField")[0].value;如果這是 頁面中的第一個文本框。

備選方案2:

使用document.getElementsByTagName('tag_name')[whole_number].value 也返回現場的HTMLCollection

EG。 document.getElementsByTagName("input")[0].value;,如果這是您的頁面中的第一個文本框,則爲 。

方案3:

,使用功能強大document.querySelector('selector').value它使用CSS 選擇器選擇元素

EG。通過由標記名 document.querySelector('[name="searchTxt"]').value;選擇 類document.querySelector('input').value;選擇的ID document.querySelector('.searchField').value;選擇document.querySelector('#searchTxt').value;按名稱

+0

更具體地說,這個AppleScript將在打開Numbers.app時使用熱鍵來觸發。我想要發佈的值是純文本(字符串)並保存在特定的單元格中。該值位於'C'列中,並且該行是我當前選擇的任何行。然後AppleScript會將Google Chrome打開到網頁表單的頁面,並使用我提供的代碼填寫必填字段。目前,代碼只有'execute javascript'這一行,它工作正常,但現在我希望AppleScript只填寫該字段(如果它當前爲空)。 – mynameisjohn

相關問題