Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery How to get string from the search box

I am studying jquery searching box.

I am getting trouble with getting string var from html.

in my html file.

i have..

<header>
  <div id="searchBox">
    <form name="searchForm">
      <div>
        <i class="icon-search icon-large icon-height"></i>
        <input name="searchfield" type="search" size="20" maxlength="30">
      </div>
    </form>
  </div>
</header>

and

in my jquery file i have

$(".icon-search").click(function() {
  var searchstring  = $(this).text('#searchfield');// $('#searchfield');
  searchstring.focus();
  //$('#searchBox').html($('input:searchfield').val());
  alert("searchfield.  " + searchstring +  " hahah");
});

when I clicked to searching some strings.

It shows that Object object instead of some strings.

I am not really sure how to convert object to strings.

Does anybody know how to convert it ?

like image 675
Dc Redwing Avatar asked Dec 26 '22 20:12

Dc Redwing


1 Answers

This line of code means nothing:

var searchstring  = $(this).text('#searchfield');// $('#searchfield');

It should indeed be:

var searchstring = $('#searchfield');

Then you'll be able to do:

searchstring.focus();

And retreive the text with .val():

alert("searchfield.  " + searchstring.val() +  " hahah");

.text() gets or sets the text content of a HTML element. It gets a value if it is being invoked without any parameters, and it sets a value if a value is passed to it. So $(this).text('#searchfield') would set the inner text of $(this) (your .icon-search) to the string "#searchfield".

Now, a form element doesn't have an inner text, it has a value, hence .val(), which otherwise works the same way as .text()

alert(myTextbox.val()); // get value
myTextbox.val('test');  // set value

Edit:

Also, $('#searchfield') looks for an element of the ID "searchfield". You should either add id="searchfield" to your textfield, or update your script to

var searchstring = $('input[name=searchfield]');
like image 92
David Hedlund Avatar answered Dec 29 '22 10:12

David Hedlund