ssdesign
ssdesign

Reputation: 2821

How to reorder form fields using jquery

I have a PHP page with a form like this:

<form class="form3">
<label class="form3"><input type="checkbox"> Item-1</label>
<label class="form3"><input type="checkbox"> Item-2</label>
<label class="form3"><input type="checkbox"> Item-3</label>
<label class="form3"><input type="checkbox"> Item-4</label>
<label class="form3"><input type="checkbox"> Item-5</label>
</form>

I have javascript variables set like this:

var checked = ["", "yes", "", "yes", ""];

Now when the page is loaded, I want to check if the the checked value is "yes" then I want to put those input items first in teh list and the remaining ones later, like this:

<form class="form3">
<label class="form3"><input type="checkbox" checked="checked"> Item-2</label>
<label class="form3"><input type="checkbox" checked="checked"> Item-4</label>
<label class="form3"><input type="checkbox"> Item-1</label>
<label class="form3"><input type="checkbox"> Item-3</label>
<label class="form3"><input type="checkbox"> Item-5</label>
</form>

I assume, jQuery would be the way to do it. which means, I will need to loop through the form fields (which I am not sure how) and inside the loop check if the corresponding variable is blank or 'yes', and if yes, print that form field. Then again go through the same loop and print all fields where corresponding variable is blank.

Hope the logic is correct.

I am able to loop through the form elements like this:

$.each($('.form3'),function(i,e){
    if(checked[i] == "")
        {
            e.appendTo($('.form3'));
        }
});

BUT obviously, the appendTo line gives me error:

Uncaught TypeError: Object #<HTMLLabelElement> has no method 'appendTo'

So, now I would need to know how to pick each one of the rows and reorder them while looping.

Thanks

Upvotes: 1

Views: 2146

Answers (2)

Kimtho6
Kimtho6

Reputation: 6184

Try this instead:

$('.form3').each(function(i,e) {

    if(checked[i] == "") {

        $(this).find('input[type=checkbox]').attr('checked', true);
        $(this).appendTo($('form'));

    }

});

Upvotes: 4

Sander
Sander

Reputation: 13431

you are thinking in the right direction here is how i would take care of this:

$('.form3').each(function(){
    var lbl = $(this);
    var chk = lbl.find('input[type=checkbox]');
    if(chk.attr('checked'))
    {
        lbl.prependTo($('#myForm'));
    }
});

you can find a working example here: http://jsfiddle.net/saelfaer/LbMQG/1/

Upvotes: 0

Related Questions