问题
Trying to do something if the input value contains a certain word but this doesn't work:
var formMain = $('#MainForm :input[name="Search"]');
if ((formMain).value.indexOf('word') >= 0) {
alert('HAS THIS WORD IN IT!');
Example Form:
<form onsubmit="return OnSubmitSearchForm(event, this);" action="/searchresults.asp" id="MainForm" name="MainForm" method="post" class="search_results_section">
<input type="hidden" value="word" name="Search">
<input type="hidden" value="" name="Cat">
</form>
回答1:
Your title mentions val()
but you're not actually using it. formMain
is a jquery object and has no value
, you should use val()
.
var formMain = $('#MainForm :input[name="Search"]');
if (formMain.val().indexOf('word') >= 0) {
alert('HAS THIS WORD IN IT!');
}
Also note that formMain
is a misleading variable name as it is not the main form but rather a jquery object which contains the search input.
回答2:
$(function(){
var formMain = $('#MainForm input[name="Search"]').val();
if (formMain.indexOf('word') >= 0) {
alert('HAS THIS WORD IN IT!');
}
});
回答3:
possibly you are doing mistake with selector and should use .val with selector only .... here is something for you check this http://jsfiddle.net/sahil20grover1988/V2dsn/3/
来源:https://stackoverflow.com/questions/7615719/jquery-val-indexof-not-working