将输入加入一个字符串

时间:2015-05-28 13:05:03

标签: javascript jquery

我有一个在线调度程序的自定义表单组。我试图找到将输入连接成一个字符串一段时间的最佳方法。我使用了jQuery的map函数,它看起来效果很好。我是否会在移动设备或触摸屏上遇到这种方法的任何问题?

External JSFiddle

$('input, select').on('change', function() {
  var userTime = $('.form-appointment-time select[name=form-hour], select[name=form-minute], input[name=time_format]:checked')
    .map(function() {
      return this.value;
    }).get().join();

  var userDate = userTime.replace(',', ':');

  // For preview
  $('.result').replaceWith('<p class="result">' + userDate + '</p>');
});
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<div class="form-group form-appointment-time">
  <label class="col-sm-2 control-label">Preferred Time:</label>
  <div class="col-sm-10">
    <div class="form-inline">
      <select class="form-control" name="form-hour">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
      </select>
      <select class="form-control" name="form-minute">
        <option value="00">00</option>
        <option value="30">30</option>
      </select>
      <input name="time_format" id="time-am" type="radio" value="AM">
      <label for="time-am">AM</label>
      <input name="time_format" id="time-pm" type="radio" value="PM">
      <label for="time-pm">PM</label>
    </div>
  </div>
</div>

<p class="result"></p>

3 个答案:

答案 0 :(得分:2)

您可以组合,映射,缩小和加入以格式化您的时间。当你到达需要空间的位置时,可以使用reduce来展平数组。

我添加了该字段的样式规则,建议为Виктор Щелкунов

&#13;
&#13;
var timeFields = [{
  text: 'Hour',
  value: 11
}, {
  text: 'Minute',
  value: 59
}, {
  text: 'Second',
  value: 59
}, {
  text: 'Millisecond',
  value: 999
}, {
  text: 'Meridiem',
  value: 'PM'
}];

function formatTime(items) {
  return items.map(function(item) {
    return item.value;
  }).reduce(function(res, item, idx, arr) {
    return (idx !== 4 ? res : [res.join(':')]).concat([item]);
  }, [])
  .join(' ');
}

document.body.innerHTML = formatTime(timeFields);
&#13;
&#13;
&#13;

在行动中

我修改了formatTime函数,以便您可以传入应该有空格的索引。

&#13;
&#13;
$('input, select').on('change', function() {
  var userDate = formatTime($('.form-appointment-time select[name=form-hour], select[name=form-minute], input[name=time_format]:checked').get(), 2);
  
  // For preview
  $('.result').replaceWith('<p class="result">' + userDate + '</p>');
});

function formatTime(items, spaceIndex) {
  return items.map(function(item) {
    return item.value;
  }).reduce(function(res, item, idx, arr) {
    return (idx !== spaceIndex ? res : [res.join(':')]).concat([item]);
  }, [])
  .join(' ');
}
&#13;
select,input{
    width: auto !important;
    display: inline-block !important;
}
&#13;
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<div class="form-group form-appointment-time">
  <label class="col-sm-2 control-label">Preferred Time:</label>
  <div class="col-sm-10">
    <div class="form-inline">
      <select class="form-control" name="form-hour">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
      </select>
      <select class="form-control" name="form-minute">
        <option value="00">00</option>
        <option value="30">30</option>
      </select>
      <input name="time_format" id="time-am" type="radio" value="AM">
      <label for="time-am">AM</label>
      <input name="time_format" id="time-pm" type="radio" value="PM">
      <label for="time-pm">PM</label>
    </div>
  </div>
</div>

<p class="result"></p>
&#13;
&#13;
&#13;

另一种方法

您还可以使用一组停止点来控制何时连接数组中的值。 Array.prototype.shift()是一种非常有用的方法。它将删除数组中的第一个项目以供立即使用。该数组将自动更新。

&#13;
&#13;
Array.multiJoin = function(arr, stops) {
  return arr.reduce(function(res, item, idx) {
      return (
        (stops.length > 1 && idx > stops[1][0]) ||
        (stops.length === 1 && idx === stops[0][0]) ?
          [res.join(stops.shift()[1])] : res
      ).concat([item]);
    }, [])
    .join(stops.length > 0 ? stops[0][1] : '');
}

var timeFields = [
  { text: 'Hour',        value:  11  },
  { text: 'Minute',      value:  59  },
  { text: 'Second',      value:  59  },
  { text: 'Millisecond', value: 999  },
  { text: 'Meridiem',    value: 'PM' }
];

var stops = [
  [0, ':'],
  [2, '.'],
  [3, ' ']
];

function formatTime(items, stops) {
  return Array.multiJoin(
    items.map(function(item) {
      return item.value;
    }), stops);
}

document.body.innerHTML = formatTime(timeFields, stops);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在您的示例中,一个移动设备,select和input元素将 display css属性设置为“block”,并将 width 属性设置为“100” %”。确保这些元素始终为“width:auto”和“display:inline-block”。请参阅移动设备上的this jsfiddle

select,input{
    width: auto !important;
    display: inline-block !important;
}

答案 2 :(得分:1)

您可能希望存储对元素的引用以供稍后重用,因为对于相同的元素一遍又一遍地扫描DOM是昂贵且不必要的。因此,您的代码可以使用以下最小且稍微清晰的代码重写。

talk
//Store the container
var $wrapper = $('.form-appointment-time');
//Store the input elements. This may be useful if at all you wanted to change attributes, such as name etc.
var inputs = [
    "select[name='form-hour']",
    "select[name='form-minute']",
    "input[name='time_format']:checked"
];
//Ensures that only the inputs, selects within the container are considered.
$wrapper.on('change', 'input, select', function() {
    var userTime = $wrapper.find(inputs.join(', '))
    .map(function() {
        return this.value;
    }).get().join(":");
    var userDate = userTime.replace(/:(?!.*:)/g, " ");
    
    // For preview
    $('.result').replaceWith('<p class="result">' + userDate + '</p>');
});