尝试将所有输入值转换为字符串、jquery或javascript

Trying to get all input value into string, jquery or javascript

本文关键字:字符串 jquery javascript 转换 输入      更新时间:2023-09-26

我正在尝试使用jquery或javascript将所有输入值获取到字符串(1,2,3,4(中,并忽略空值。非常感谢。

<form id="sym_form">
			 <input type="text" class="as_sym" id="sym_1" value="1">
			 <input type="text" class="as_sym" id="sym_2" value="2">
			 <input type="text" class="as_sym" id="sym_3" value="3">
			 <input type="text" class="as_sym" id="sym_4" value="4">
			 <input type="text" class="as_sym" id="sym_5" value="">
		 </form>

  // string to keep the result
  var output = "";
  // iterate over all inputs with class 'as_sym' inside the '#sym_form'
  $('#sym_form > input[class=as_sym]').each(function(){
    // only inputs with non-empty values                                                                                                        
    if ($(this).val() != "") {
      // the first value doesn't have a comma in front of it
      // subsequent values do have a comma in front of them
      if (output == "") {
        output += $(this).val();
      } else {
        output += "," + $(this).val();
      }
    }
  });
  // here do whatever you want with the 'output' variable
const form = document.getELementById("sym_form");
for (var element of form.elements) {
    if(element.nodeName === "INPUT" && element.value) {
        // do something with element.value
    }
}

var $inputs = $('#sym_form .as_sym');
var result ="";
$.each($inputs, function(i, v) {
   var val = $(this).val();
   result += val;
  });
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sym_form">
			 <input type="text" class="as_sym" id="sym_1" value="1">
			 <input type="text" class="as_sym" id="sym_2" value="2">
			 <input type="text" class="as_sym" id="sym_3" value="3">
			 <input type="text" class="as_sym" id="sym_4" value="4">
			 <input type="text" class="as_sym" id="sym_5" value="">
		 </form>
<p id="result"></p>

您可以使用.querySelectorAll()选择所有"#sym_form .as_sym"元素,Array.prototype.forEach()Function.prototype.call()input事件附加到每个元素,在input事件中将每个"#sym_form .as_sym"元素的内容值连接到字符串,使用.split().join()在每个字符或结果字符串之间包括逗号,字符

var inputs = document.querySelectorAll("#sym_form .as_sym");
Array.prototype.forEach.call(inputs, function(input) {
  input.addEventListener("input", function(e) {
    for (var i = 0, val = "", len = inputs.length; i < len; i++) {
      val += inputs[i].value;
    }
    console.log(val.split("").join(","))
  })
})
<form id="sym_form">
  <input type="text" class="as_sym" id="sym_1" value="1">
  <input type="text" class="as_sym" id="sym_2" value="2">
  <input type="text" class="as_sym" id="sym_3" value="3">
  <input type="text" class="as_sym" id="sym_4" value="4">
  <input type="text" class="as_sym" id="sym_5" value="">
</form>