开发者

How do i get the string after an element with jquery?

开发者 https://www.devze.com 2023-04-07 04:32 出处:网络
I have several forms on my page.Each form is named according to the ID in the database. <form id=\"spam-X\" method=\"post\">

I have several forms on my page. Each form is named according to the ID in the database.

<form id="spam-X" method="post">

So on my page, if there are 3 comments, there are 3 forms.

<form id="spam-1" method="post">...</form>  <form id="spam-2" method="post">...</form>   <form id="spam-3" method="post">...</form>

Now I want to run a set of functions for based on 开发者_如何学编程what form is submitted. So I have my submit function in jquery...

$("form#[id^='spam']").submit(function() {  

Now the problem is, I want to get the contents within this specific form that was clicked, so I'm assuming I will need the trailing ID (spam-1, spam-2, spam-3).... How do I get that value?


You don't need to refer to the form by it's specific ID, because the function you bind to the submit handler will be called with 'this' being the DOM element of the form. You can get the text content of the form using the text() function:

$("form#[id^='spam']").submit(function() {
     // 'this' is the dom element that is being submitted
     var text = $(this).text();
});


Just use:

$("form#[id^='spam']").submit(function() {  
   var formThatWasSubmitted = this;
}

The to get the value of a particular input in that form:

var email = this.email.value;


Try using $(this).attr('id') inside the submit handler.


You can use the $(this) inside the function to get access to the form that was activated by the click.

Then using something like $(this).find("SELECTOR").val() to narrow down to the field that you need the information from. Where you'd need to substitute SELECTOR with the name or class selector for your field inside that form.

0

精彩评论

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