使用getElementsByClassName将多个值更改为String

时间:2019-10-14 07:20:36

标签: javascript laravel indexing

因此我用以下数字获得了4个值作为数字:

    <h3 class="u-text-size-h6"> </h3>
    <div class="js-numstepper tiempo">
    <input  class="tiempos" type="number" min="0" max="60">
    </div>
</div>

和:

var tiempoInstruccion = document.getElementsByClassName('tiempos');

然后我想将所有值都转换为字符串,因为我有一个仅对文本使用数字的功能。

我尝试过:

var stringTiempo = tiempoInstruccion.toString(); 并尝试使用循环将其停顿

即时通讯的主要问题在于此功能:

var tiempoInstruccion = document.getElementsByClassName('tiempos');
var seleccionTiempo = [];

for (var i = 0; i < tiempoInstruccion.length; i++) {
        var element = tiempoInstruccion[i].toString();

        var strSel = element.options[element.selectedIndex].text;
        seleccionTiempo.push(strSel);
    }

我需要将这些值推送到此数组 var seleccionTiempo = []

还尝试更改 element.options[element.selectedIndex].text;element.options[element.selectedIndex].value;

我收到此消息: TypeError: element.selectedIndex is undefined

,由于数组不是字符串,因此确定其原因。

3 个答案:

答案 0 :(得分:1)

您可以使用以下功能提取输入值

var tiempoInstruccion = [];
var seleccionTiempo = [];

function updatevalues(){
  var tiempoInstruccion = document.getElementsByClassName('tiempos');
  seleccionTiempo = [];
  for(var i=0;i<tiempoInstruccion.length;i++){
    var val = tiempoInstruccion[i].value;
    if(val.length>0){
      seleccionTiempo.push(val);
    }
  }
  console.log(seleccionTiempo);
}
<div>
  <h3 class="u-text-size-h6"> </h3>
   <div class="js-numstepper tiempo">
    <input  class="tiempos" type="number" min="0" max="60">
  </div>
</div>
<div>
  <h3 class="u-text-size-h6"> </h3>
   <div class="js-numstepper tiempo">
    <input  class="tiempos" type="number" min="0" max="60">
  </div>
</div>
<div>
  <h3 class="u-text-size-h6"> </h3>
   <div class="js-numstepper tiempo">
    <input  class="tiempos" type="number" min="0" max="60">
  </div>
</div>
<div>
  <h3 class="u-text-size-h6"> </h3>
   <div class="js-numstepper tiempo">
    <input  class="tiempos" type="number" min="0" max="60">
  </div>
</div>
<div>
  <input type="button" value="Update" onclick="updatevalues()">
</div>

答案 1 :(得分:0)

我在ur数组中放入了一些自定义值。然后使用javascript map函数遍历所有项目,然后将它们压入新数组,使它们成为字符串

var tiempoInstruccion = [56,67,57,52];
var seleccionTiempo = [];

tiempoInstruccion.map( item => {
  seleccionTiempo.push(item.toString());
})
console.log(seleccionTiempo)

希望有帮助。

答案 2 :(得分:0)

tiempos是一个文本框,而不是一个选择框。您可以访问文本框中的options属性。使用此One它将起作用

var tiempoInstruccion = document.getElementsByClassName('tiempos')[0] .value.toString();