JQuery

Ok, so here is the idea:

I want to make a jQuery script to handle multiple forms. Each form has a button. When this button is clicked, the script should send the name and value of all input fields in $ _POST to the action action URL. But I can't get this to work.

It will not go through my .each on line 3 in my jQuery file.

JQuery:

$("input[type='button']").click(function(){
    var query = {};
    $(this).parent('form').children('input[type="text"]').each(function(){
        query[$(this).attr('name')] = $(this).val();
    });

    $.post($(this).parent('form').attr('action'), query, function(data) {
        $("#dialog").html(data);
        $("#ui-id-1").html('Activate account');
        $("#dialog").dialog("open");
    }, 'json');
});

HTML:

<form action="/action/activateacc.php">
<table>
    <tr>
        <td>E-mail:</td>
        <td><input type="text" id="mail" name="mail" /></td>
        <td><img class="tick" id="mailIMG" width="20px" /></td>
    </tr>
    <tr>
        <td>Activation code:</td>
        <td><input type="text" id="code" name="code" /></td>
        <td><img class="tick" id="codeIMG" width="20px" /></td>
    </tr>
    <tr>
        <td>Choose organization-name:</td>
        <td><input type="text" id="name" name="name" /></td>
        <td><img class="tick" id="nameIMG" width="20px" /></td>
    </tr>
    <tr>
        <td></td>
        <td style="text-align:center"><input type="button" style="cursor:pointer" value="Activate account" /></td>
    </tr>
 </table>
 </form>
+5
source share
6 answers

Just use it . serialize () with the form to get the name / values ​​of your inputs, you should also use the closest one since the parent only goes up one level

$("input[type='button']").click(function(){   
    var query = $(this).closest('form').serialize();
    $.post($(this).parent('form').attr('action'), query , function(data) {
        $("#dialog").html(data);
        $("#ui-id-1").html('Activate account');
        $("#dialog").dialog("open");
    }, 'json');
});
+2
source

.parent()only rises one level DOM - try using .closest()and find()- so

$(this).closets('form').find('input[type="text"]').each(function(){
0

.find, .parents,

$(this).parents('form').find('input[type="text"]').each(function(){
        query[$(this).attr('name')] = $(this).val();
    });
0

: .closest() ( , , ), find() ( jQuery):

$(this).closest('form').find('input[type="text"]').each(function(){ 
    query[$(this).attr('name')] = $(this).val();
});

jsFiddle Demo

0

parent() 1 DOM, children() 1 DOM.

, 100% , ( , ), closest(), DOM.

0

form , $.serialize.

The .serialize () method creates a text string in a standard encoded notation URL. It works with a jQuery object representing a set of form elements.

In your case:

var query = $(this).closest('form').serialize();
0
source