开发者

JQuery map() form inputs

I'm mapping out the name attributes of :input using the example below. I had to put a conditional stat开发者_开发百科ement in map() to find out if checkbox is checked and return true or false. but now I'm not getting the select option name attr. I feel like it's taking more code writing then it should. What is an efficient way to get all the name attributes and watch for checked in checkboxes. Check the example at http://jsfiddle.net/gVHaQ/3/

<form>
    <input type="text" name="name" value="John"/>
    <input type="text" name="password" value="password"/>
    <input type="text" name="url" value="http://domain.org/"/>
    <select>
        <option name="one">1</option>
        <option name="two">2</option>
        <option name="three">3</option>
    </select>
    <input type="checkbox"/>            
</form>
<p></p>

$("p").append($(":input").map(function() {
    if ($(this).attr('type') == 'checkbox') {
        return $(this).attr('checked');
    }
    else {
        return $(this).attr('name');
    }
}).get().join(", "));

This is what is being returned

name, password, url, , true


Perhaps this is what you want?

$("p").append($(":input").map(function() {
    if($(this).is('select')) {
        return $(this).children('option').map(function() {
          return $(this).attr('name');
        }).get().join(", ");
    } else if($(this).attr('type')=='checkbox') {
        return $(this).attr('checked');
    } else {
        return $(this).attr('name');
    }
}).get().join(", "));

http://jsfiddle.net/gVHaQ/4/

If not, you should probably provide what the expected output is

EDIT: Accepted Version

$("p").append($(":input").map(function() {
    if($(this).is('select')) {
        return $(this).val();
    } else if($(this).attr('type')=='checkbox') {
        return $(this).attr('checked');
    } else {
        return $(this).attr('name');
    }
}).get().join(", "));


You can avoid using map twice if you still want to use map(): http://jsfiddle.net/PmDr9/.

But if you want to skip map(), I guess one way you can probably try is $('form').serialize(). And after you get the serialized string, you can use regex expression to replace the unwanted data. Note though, you will need to provide a name to and . Here's an example: http://jsfiddle.net/JKuZE/1/. (Note: my regex is not that great, so maybe you can play with it and get the result you want).

I don't know if the second implementation is what you are looking for, but it's a suggestion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜