AppleScript - 如果document.getElementById值为null,请输入value

时间:2017-04-05 16:57:26

标签: javascript webforms applescript

第一次问一个问题,让我知道我做错了。我有一个AppleScript,它从Numbers文档中获取值,并使用document.getElementById将它们输入到webform的各个字段中。

它完美无瑕,但现在我想添加一个功能,以便只有 填写一个值,如果webform中的该字段为空。

我对代码的看法是这样的:

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

有人可以告诉我最佳方法来检查document.getElementById值是否为null,然后如何继续?非常感谢!

2 个答案:

答案 0 :(得分:0)

在使用此代码段之前,您必须考虑以下几点:

1-何时触发此代码?定期在click 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/

有几种方法可以直接获取输入文本框值(不将输入元素包装在表单元素中):

  

这些方法返回元素集合,因此请使用[whole_number]   获得所需的出现,第一个元素使用[0]和   第二个使用1等等......

备选方案1:

  

使用document.getElementsByClassName('class_name')[whole_number].value   返回Live HTMLCollection

     

EG。 document.getElementsByClassName("searchField")[0].value;如果是这样的话   您网页中的第一个文本框。

备选方案2:

  

使用document.getElementsByTagName('tag_name')[whole_number].value   这也返回一个实时的HTMLCollection

     

EG。 document.getElementsByTagName("input")[0].value;,如果是这样的话   页面中的第一个文本框。

备选方案3:

  

使用使用CSS的强大document.querySelector('selector').value   选择元素的选择器

     

EG。 {id}选择document.querySelector('#searchTxt').value;   由班级选择的document.querySelector('.searchField').value;   标记名选择document.querySelector('input').value;   按名称

选择document.querySelector('[name="searchTxt"]').value;

答案 1 :(得分: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
相关问题