Using jQuery map() with multiple types of form ele

2019-09-07 22:38发布

问题:

I am building a multi-step contact form (each step is within an article tag), and I am using jQuery map() to store the labels and input values into an array, and then on the last part of the form, the information is displayed. The jQuery that stores the array is like so:

$("article:last").prev().find("a.next").on("click", function(){
    var arr = $('.form-item').map(function() {
        var lab = $('label', this).text();
        var val = $('input', this).val();
        return "<li>" + lab + " " + val + "</li>";
    }).get()

    $("article:last ul#results").append(arr.join(''))
});

This works great, but returns "undefined" for textareas and select menus, rightfully so. I need to adapt this code to work for select items and textareas. My HTML is very simple, like so:

<article>
<div class="form-item">
    <label>Address:</label>
    <input type="text" />
</div>

<div class="form-item">
    <label>Message:</label>
    <textarea rows="2" cols="20"></textarea>
</div>
</article>

Each article represents a new section of the form. So the question is, how to I adapt my jQuery to support other form elements? Would it be a good bet to do a conditional saying, "if .form-item's children contains a textarea, run this code....etc.

回答1:

You can use :eq() selector, eq(1) selects the second child of the div tags, an input or a textarea element.

var arr = $('.form-item').map(function() {
    var lab = $('label', this).text();
    var val = $(':eq(1)', this).val();
    return "<li>" + lab + " " + val + "</li>";
}).get()

http://jsfiddle.net/bFumx/



回答2:

You can write something like this:

​var arr = $('.form-item').map(function() {
    var val = $(this).find('input, textarea').val();
    return val;
}).get();​​​​​​​​​​​

Live example on JSFiddle