简体   繁体   中英

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

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?

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;

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();
});

尝试在submit处理程序中使用$(this).attr('id')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM