如何将文本框的值赋予脚本中的变量?

时间:2015-11-30 06:24:00

标签: javascript

我写了一个像这样的剧本

function calculateDiff(){

    _start = "1:00 PM";
    _end = "1:00 AM";

    _start_time = parseAMDate(_start);
    _end_time = parseAMDate(_end);

    if (_end_time < _start_time){
        _end_time = parseAMDate(_end,1);
    }

    var difference= _end_time - _start_time;

    var hours = Math.floor(difference / 36e5),
        minutes = Math.floor(difference % 36e5 / 60000);
    if (parseInt(hours) >= 0 ){
        if (minutes == 0){
            minutes = "00";
        }
        alert(hours+":"+minutes);
    }
}
function parseAMDate(input, next_day) {

    var dateReg = /(\d{1,2}):(\d{2})\s*(AM|PM)/;

    var hour, minute, result = dateReg.exec(input);

    if (result) {
        hour = +result[1];
        minute = +result[2];

        if (result[3] === 'PM' && hour !== 12) {
            hour += 12;
        }
    }
    if (!next_day) {
        return new Date(1970, 01, 01, hour, minute).getTime();
    }else{
        return new Date(197var start = document.getElementById("usr1").value;
  var end = document.getElementById("usr2").value;0, 01, 02, hour, minute).getTime();
      }
   }

这里,对于_start和_end,我已经给出了值,我希望这些值应该来自一个文本框,因为我已经编写了像

这样的代码
<form action="calculateDiff()">
Select  start time:<input type="time" name="usr1">
 Select  end time: <input type="time" name="usr2">
<input type="submit">
</form>

当我在文本框(usr1)中选择时间时,如何获得脚本功能的时间? 请帮助我

3 个答案:

答案 0 :(得分:1)

我建议在输入字段中添加id属性:

<form action="calculateDiff()">
    Select  start time:<input type="time" name="usr1" id="startTime">
    Select  end time: <input type="time" name="usr2" id="endTime">
    <input type="submit">
</form>

现在我们可以使用document.getElementById直接访问html元素:

var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;

document.getElementById("usr1")将返回HTML文本字段对象本身,它有一些属性。其中一个是value,表示文本字段内的内容(您甚至可以使用javascript更改它)。

在此处阅读有关输入元素的更多信息:

答案 1 :(得分:0)

试试这个

_start = document.getElementsByName('usr1')[0].value; //It will fetch the value of the first element in the DOM with the name usr1
_end = document.getElementsByName('usr2')[0].value; //It will fetch the value of the first element in the DOM with the name usr2

答案 2 :(得分:0)

你可以像这样获得输入值

var _start = document.getElementsByName("usr1")[0].value;
var _end = document.getElementsByName("usr2")[0].value;