Search code examples
jqueryjquery-mobilejquery-mobile-listview

JQueryMobile getting value of input field in a listview for searching in database


I want to get the values of two listviews to use them as variables for a database-call.

Here is a sscce:

<!DOCTYPE html> 
 <html>
<head>
<title>Startseite</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" /> 
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script>
$( document ).on( "pageinit", "#startseite", function() {
/* retrieve text from clicked li */
$(document).on("click", "li", function () {
  var text = $(this).text();
  $(this).closest("ul").prev("form").find("input").val(text);
  $(this).closest("ul").children().addClass('ui-screen-hidden');
});

$(document).on("click", "#send", function() {

});
});
</script>
</head>

<body>
<div data-role="page" id="startseite">

  <div data-role="header" data-theme="a">
<h1>Head</h1>
  </div>

  <!--<div data-role="main" class="ui-content">!-->
  <div data-role="tabs" id="tabs" >
<div data-role="navbar" data-iconpos="left">
  <ul>
      <li><a href="#one" data-ajax="false" class="ui-btn-active" data-icon="search">Suche</a></li>
      <li><a href="#two" data-ajax="false" data-icon="location">Karte</a></li>
  </ul>
</div>
<div id="one" class="ui-body-d ui-content">
  <form>
    <label for="shop">Was suchen Sie?</label>
    <ul id="shop" data-role="listview" data-filter="true" data-filter-reveal="true" data-filter-placeholder="Restaurant, Bar, Kiosk" data-inset="true">
      <li><a href="#">Restaurant</a></li>
      <li><a href="#">Bar</a></li>
      <li><a href="#">Kiosk</a></li>
    </ul>
    <label for="city">Wo suchen Sie?</label>
    <ul id="city" data-role="listview" data-filter="true" data-filter-reveal="true" data-filter-placeholder="Alsdorf" data-inset="true">
      <li><a href="#">Aachen</a></li>
      <li><a href="#">Augsburg</a></li>
    </ul>
    <br>
    <input id="send" class="ui-btn ui-btn-b ui-corner-all" type="button" value="Absenden">
  </form>
</div>
<div id="two" class="ui-body-d ui-content">
        Page 2
</div>

My problem is that I couldnt find a way to get access to the values of the from JQueryMobile generated input fields.


Solution

  • Auto-complete form is always placed dynamically before the list-view. All you need is to give the list-view an ID and look for input inside the previous form.

    $("#send").on("click", function () {
      var value = $("#autocomplete").prev("form").find("input").val();
      alert(value);
    });
    

    Demo