最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get a specific form elements using jQuery - Stack Overflow

programmeradmin0浏览0评论

I have a multiple forms in a page and i would like to get the elements of a specific form. For example:

<form class="form" id="1">
  <input type="text" name="message" value="message">
  <button type="submit" value="submit">Submit</button> 
</form>
<form class="form" id="2">
  <input type="text" name="message" value="message">
  <button type="submit" value="submit">Submit</button> 
</form>

How to get the value of message of form id=2...... Thanks in advance

I have a multiple forms in a page and i would like to get the elements of a specific form. For example:

<form class="form" id="1">
  <input type="text" name="message" value="message">
  <button type="submit" value="submit">Submit</button> 
</form>
<form class="form" id="2">
  <input type="text" name="message" value="message">
  <button type="submit" value="submit">Submit</button> 
</form>

How to get the value of message of form id=2...... Thanks in advance

Share Improve this question asked Dec 1, 2015 at 19:39 SheharoseSheharose 2953 silver badges16 bronze badges 1
  • 5 Possible duplicate of jquery- how to select child elements under id – abc123 Commented Dec 1, 2015 at 19:42
Add a ment  | 

4 Answers 4

Reset to default 6

Just use attribute selectors

 $('form[id=2]') // get the form with id = 2
.find('input[name=message]') // locate the input element with attribute name = message
.attr("value"); //  get the attribute = value

You really shouldn't use raw numbers for ids, let's rename those to form_1 and form_2, then your jquery selector would be:

$("#form_2 [name='message']").val();

Simply query the input from the id of the form you'd like

console.log($('#2 input').val());

//more specific
console.log($('#2 input[name="message"]').val());
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form" id="1">
  <input type="text" name="message" value="message">
  <button type="submit" value="submit">Submit</button> 
</form>
<form class="form" id="2">
  <input type="text" name="message" value="message">
  <button type="submit" value="submit">Submit</button> 
</form>

You can use jQuery, or you can use basic JavaScript to return the message value. With basic JS, you would have to give your form a name, but then could return the message value.

Code:

function getValue() {
    var message = document.forms["form_name"]["message"].value;
}

You would then have to return the function when the form is submitted

<form class="form" name="form_name" onsubmit="return getValue()">
发布评论

评论列表(0)

  1. 暂无评论