jQuery val() indexOf not working

て烟熏妆下的殇ゞ 提交于 2019-12-23 02:48:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!