jQuery val() indexOf not working

18,992

Solution 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.

Solution 2

$(function(){
  var formMain =  $('#MainForm input[name="Search"]').val();
  if (formMain.indexOf('word') >= 0) {
    alert('HAS THIS WORD IN IT!');
  }
});
Share:
18,992
ToddN
Author by

ToddN

Updated on June 04, 2022

Comments

  • ToddN
    ToddN almost 2 years

    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>
    
  • ToddN
    ToddN over 12 years
    I have successfully tested this. Thank you for clarification also!