开发者

jQuery serialize function with multple forms

开发者 https://www.devze.com 2022-12-10 20:33 出处:网络
I\'m using the jQuery .serialize function and can\'t get it to serialize the proper form on submit. my js code:

I'm using the jQuery .serialize function and can't get it to serialize the proper form on submit.

my js code:

    function getquerystring(form) {
    return $("form").serialize();
}

my forms:

<div class="leave_message_box">
    <form name="leave_message_form">
        <input type="text" name="clock_code" placeholder="Clock Code" />
    <input type="text" name="message" placeholder="Message (Blank for none)"/>
    <input type="hidden" name="type" value="leave_message" />
        <input value="Leave Message" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "leave_message_form")'></p>
    </form>
</div>
<div class="outside_job_box">
    <form name="outside_job_form">
        <input type="text" name="clock_code" placeholder="Clock Code" />
    <input type="text" name="message" placeholder="Message (Blank for none)"/>
    <input type="hidden" name="type" value="ouside_job" />
        <input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
    </form>
</div>

I must be doing something wrong in passing the variable. the full code @ p开发者_开发技巧astie. The function I have does work, however, its always the last form that gets submitted.


Using this code:

$("form")

will find all the <form> elements in your document.

Given that form is a string containing the name of the form, what you want instead is this:

$("form[name='" + form + "']")

Looking at your supplied code, I have this suggestion. Instead of passing the form name to your function, why not just pass the form itself?

<button onclick="xmlhttpPost('blah', this.form)">

You also don't need to put javascript: in the onclick, onfocus, onwhatever properties.


I would suggest putting an ID attribute on the form and then using that ID as an explicit selector for jQuery:

<div class="outside_job_box">
  <form id="outside_job_form" name="outside_job_form">
      <input type="text" name="clock_code" placeholder="Clock Code" />
      <input type="text" name="message" placeholder="Message (Blank for none)"/>
      <input type="hidden" name="type" value="ouside_job" />
      <input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
  </form>
</div>

Then you would select and serialize it like this;

var f = $("#outside_job_form").serialize();

Not only making your code more effecient but more readable, in my opinion.


If the sole purpose is to encode simple text into URL format then use encodeURIComponent().

0

精彩评论

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