1

I need to output inputs and their values into a div. However, because I need to match the correct labels to the correct inputs, and some fields allow null values, I'm running into matching issues. Using the following code to pull each label/input into an array, and then output:

var inputArr = $('input, select').map(function(){
    return "<p>" + $(this).val() + "</p>";
}).get()

var labelArr = $('label').map(function(){
  return "<p>" + $(this).text() + "</p>";
}).get()

function setValuesForConfirm() {
//Clear Div Contents                
  $("#test-output-1, #test-output").html('');

  for (var i = 0; i < labelArr.length; i++) {
    $("#test-output-1").append(labelArr[i]);
  }

  for (var i = 0; i < inputArr.length; i++) {
    $("#test-output").append(inputArr[i]);
  }
}

So if any of the input's are blank, the fields do not match the labels.

My question is, can I name the array keys to the field name or ID in JS using the .map() function as I am currently?

JSFiddle Here

2 Answers 2

1

You could create an object using the inputs:

var formObj={};

$('input, select').each(function(){
    formObj[this.name]={val: this.value, labelText: $(this).prev('label').text()}; 

});

then when loop over object can throw together html

$.each(formObj, function(key, item){
    var labelHtml='<p>'+item.labelText+'</p>';
    var inputHtml='<p>Name: '+ key+', value: '+item.val+'</p>';
    /* do something with html*/
})
Sign up to request clarification or add additional context in comments.

3 Comments

This is exactly what I needed. Kudos
I assumed all labels are element previous to select or input. If not there are many ways to traverse
Right, based on your example I was able to pull the labels I needed. Thanks again!
0

While what you have seems to work okay to me, .map creates an array and you can only have numeric ordinal keys in arrays in JavaScript, so you would need an object.

var inputArr = {};
$('input, select').each(function(){
    inputArr[$(this).attr('name')] = "<p>" + $(this).val() + "</p>";
});

http://jsfiddle.net/Mz9Vy/1/

1 Comment

Thanks. While that makes sense, if you look at your JSFiddle, you can see that 2 is still outputting where 1 would if it had a value. Pardon my density, but how would I best output the array value only if if it's key matches that of the label key? My thought would be to use a list for each element name/id. Is there a more efficient way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.