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

javascript - JQuery - Click Submit Button Get Form Value - Stack Overflow

programmeradmin3浏览0评论

I have the following function and all i am trying to do is get the value out of the form field.

$( ".searchbutton" ).click(function() {
    var tc = $(this).closest("form input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

The alert keeps telling me "Undefined". I have treid closest, parent, parents, find, etc. I don't know what im doing wrong. Im clicking the submit button and all i want in return is the value in the search box. Please help.

html

<form action="/index.php" method="get" class="qsearch" >
<input type="text" id="fsearch" name="searchbox" >
<input class="searchbutton" type="submit" value="Submit">
</form>

I have the following function and all i am trying to do is get the value out of the form field.

$( ".searchbutton" ).click(function() {
    var tc = $(this).closest("form input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

The alert keeps telling me "Undefined". I have treid closest, parent, parents, find, etc. I don't know what im doing wrong. Im clicking the submit button and all i want in return is the value in the search box. Please help.

html

<form action="/index.php" method="get" class="qsearch" >
<input type="text" id="fsearch" name="searchbox" >
<input class="searchbutton" type="submit" value="Submit">
</form>
Share Improve this question edited Dec 30, 2014 at 11:46 user982853 asked Dec 30, 2014 at 11:41 user982853user982853 2,48815 gold badges59 silver badges85 bronze badges 3
  • var tc = $('#fsearch').val(); since you already have id, why plicate? – sinisake Commented Dec 30, 2014 at 11:49
  • 1 Not sure if there is an id why are you not using $('#fsearch').val();? – Pratip Ghosh Commented Dec 30, 2014 at 11:49
  • @PratipGhosh, lol, at the same time (almost). :) – sinisake Commented Dec 30, 2014 at 11:50
Add a ment  | 

3 Answers 3

Reset to default 8

Try this:

$( ".searchbutton" ).click(function() {
    var tc = $(this).closest("form").find("input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

Update Yep, it work with your HTML - see here http://jsfiddle/qa6z3n1b/

As alternative - you must use

$( ".searchbutton" ).click(function() {
    var tc = $(this).siblings("input[name='searchbox']").val();
    alert(tc);      
    return false;
}); 

in your case. http://jsfiddle/qa6z3n1b/1/

Try easiest way:

<script>
$( ".searchbutton" ).click(function() {
var tc = $('#fsearch').val();
alert(tc);      
return false;
}); 
</script>

How about just using $('input[name="searchbox"]') selector:

$( ".searchbutton" ).click(function() {
    var tc = $('input[name="searchbox"]').val();
    alert(tc);      
    return false;
}); 
发布评论

评论列表(0)

  1. 暂无评论