简体   繁体   中英

How to get the Specific Form Field value using JQuery

I have a form

<form id="post_comment" action="cmt.php" method="post">
   <input type="hidden" name="type" value="sub" />
   <textarea id="body"></textarea>
</form>

I am accessing the form using this code

$("#post_comment").submit(function(event){

    var form = $(this);

});

How can I get the value of <input type="hidden" name="type" value="sub" /> from this form. I tried to get using form.input("type") but it is not working.

$("#post_comment").submit(function(event){
    var inputValue = $("input[name='type']",this).val(); 
});

Try using an id like this:

<form id="post_comment" action="cmt.php" method="post">
 <input type="hidden" id='hidden' name="type" value="sub" />
 <textarea id="body"></textarea>
</form>

and later:

$("#post_comment").submit(function(event){
 var hiddenValue = $("#hidden").val(); 
});
<form id="post_comment" action="" method="post">
 <input type="hidden" class="hidden" name="type" value="sub" />
 <textarea id="body"></textarea>
 <input type="submit" value="submit" class="submit"/>
</form>



 $(".submit").click(function(){
   var hiddenVal=jQuery("#post_comment .hidden").val();
   //alert(hiddenVal);
 });
var form = $(this);
var inputValue =  form.find('input[name="type"]').val();

or 

var form = $(this);
var inputValue =  form.find('input:hidden').val();

Another approach for this
Consider if you have multiple forms with multiple input fields having name attribute than this code will be helpful for you :

$("#formId input[name='valueOfNameAttribute']").val()
$("#formId textarea[name='message']").val()


Hope it'll help somebody.

 $("#post_comment").submit(function(event){

        var form = $("input[name='type']").val();

    })

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