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

1

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of .attr("value") you could alternatively call .val() which is more handy (to me), but it is just my personal taste.
1

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

2 Comments

this would get select the element with id #form_2 which doesn't exist.
I mentioned renaming the forms in my post
0

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.com/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>

Comments

0

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()">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.