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

时间:2016-08-07 22:39:53

标签: javascript jquery

我正在尝试使用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>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

  // 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

答案 1 :(得分:1)

const form = document.getELementById("sym_form");
for (var element of form.elements) {
    if(element.nodeName === "INPUT" && element.value) {
        // do something with element.value
    }
}

答案 2 :(得分:1)

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>

答案 3 :(得分:0)

您可以使用.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>