Trying to combine all value from jquery.each function

梦想与她 提交于 2021-01-27 19:17:47

问题


Look at my code, I am trying to combine all value from the jquery.each to a string like this ok,good, and then passed to ajax value. Appreciate. or array('ok','good') acceptable also

var global = {
    "44":["onset","frequency"],
    "45":["onset"]
};
var $val = global[44];
            
jQuery.each( $val, function( key ,value) {		
    var value = $('#'+value).val();			
});
var $combine = ;//not sure how to combine all value like this (ok,good), or array(ok,good) acceptable also
var data= {
    action: 'check_first',
    AjaxFrontNonce : ajax_csky.AjaxFrontNonce,
    combine : $combine
}
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">

回答1:


Try this working snippet

var global = {
  "44": ["onset", "frequency"],
  "45": ["onset"]
};
var $val = global[44];
var arr = [];
$.each($val, function(key, val) {
  var value = $('#' + val).val();
  arr.push(value);
});

var $combine = arr; //not sure how to combine all value like this (ok,good), or array(ok,good) acceptable also
console.log($combine);
var data = {
  action: 'check_first',
  //AjaxFrontNonce : ajax_csky.AjaxFrontNonce, not defiend
  combine: $combine
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">



回答2:


Try this:

var global = {
    "44":["onset","frequency"],
    "45":["onset"]
};

var $val = global[44];
var values = [];  

jQuery.each( $val, function( key ,value) {		
    values.push($('#'+value).val());			
});

var $combine = '(' + values.join(',') + ')';
console.log($combine);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">



回答3:


You can use $.map to go over all of the items and return the value for each element.
There is an example of both Array and String values, you can use whichever works better for you.

var global = {
    "44":["onset","frequency"],
    "45":["onset"]
};
var $val = global[44];

combinedAr = $.map($val, function(val) {
  return $('#'+val).val();
});
combinedStr = combinedAr.join(",");

var data= {
    action: 'check_first',
    AjaxFrontNonce : ajax_csky.AjaxFrontNonce,
    combine : combinedStr
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">


来源:https://stackoverflow.com/questions/38807704/trying-to-combine-all-value-from-jquery-each-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!