sanders
sanders

Reputation: 10888

Rewriting javascript to jquery for multiple forms on a page

I have a question concerning multiple similair forms on one page. Lets say you have a page with two or more polls. The HTML forms in itselves are very similair. Previously the was a soltuion built with inline javascript. Which is of course not the nicest solution. The way it was built is that eacht poll form had its own js function. But this is not wat I want anymore.

How Can i rewrite the script so that it knows wich form was submitted.

Here is the current form:

 <div style="display:block;">
    <form name="pollvoteform3" method="post" xaction="">
        <input type="hidden" name="poll" value="3">
        <input type="hidden" name="cmd" value="">
        <div class="poll">
            <div class="pollOption">
                <div class="pollRadio"><input type="radio" name="poll_option3" value="1"></div>
                <div class="pollOptionText">Option 1</div>
            </div>
            <div class="pollOption">
                <div class="pollRadio"><input type="radio" name="poll_option3" value="2"></div>
                <div class="pollOptionText">Option 2</div>
            </div>
           <p> <input type="button" name="bt_submit" class="pollButtonNormal" onmouseover="this.className='pollButtonHigh';" onmouseout="this.className='pollButtonNormal';" value="Stem" onclick="javascript:vote3();">
            <input type="button" name="bt_submit" class="pollButtonNormal" onmouseover="this.className='pollButtonHigh';" onmouseout="this.className='pollButtonNormal';" value="Resultaten" onclick="javascript:viewResults3();"></p>
        </div>
    </form>
</div>
<div style="display:none;">
    <form><input type="button" name="bt_submit" class="pollButtonNormal" onmouseover="this.className='pollButtonHigh';" onmouseout="this.className='pollButtonNormal';" value="Resultaten" onclick="javascript:viewResults3();"></form>
</div>

edit:

how can i rewrite this:

function vote1() {
    r=document.forms.pollfvoteform3.poll_option3
    var voted=false;
    if (r.value!=null && r.checked)
    {
        voted=true;
    } else {
        for (i=0;i<r.length;i++){
            if (r[i].checked) {
                voted=true;
                break;
            }
        }
    }
    if (voted) {
        document.forms.pollvoteform3.submit();
    } else {
        alert("Youre wrong!.");
    }
}

to jquery.

Upvotes: 1

Views: 360

Answers (1)

kgiannakakis
kgiannakakis

Reputation: 104168

You need to give an id and a common class to your forms:

<form name="form1" class="myforms" id="form1">

Then you can assign event handlers for both forms in one go:

$(".myforms").submit(function() {
  formId = $(this)[0].id;
});

As you can see wrapping this into a jQuery wrapped set can easily give you the id of the specific form.

Upvotes: 1

Related Questions