June 11, 2013

use jQuery/jQuerymobile .text to set content of multiple id's

Chris’s Question:

I have a page with multiple page(s- data-roles), and want to set the content on div’s, or other elements. Basically this works… like this:

<a href="..something" id="content-something"></a>
<div id="content-sometext"></div>

and setting it with that:

$('#content-something').text('Something in there');
$('#content-sometext').text('Sometext in there');

The problem occurs when I try to set the content over multiple instances of the id’s, and only the first id is being set – whether in the same page- data role or not:

<a href="..something" id="content-something"></a> ---> Something in there
<div id="content-sometext"></div> ---> Sometext in there
Some more html...
<a href="..something" id="content-something"></a> ---> empty!
<div id="content-sometext"></div> ---> empty!

As far as I understood the jQuery/mobile documentation, multiple instances should be able to be set with .text().

What am I doing wrong?
Thanks a lot for your help in advance 🙂

That is an expected behavior as IDs are suppose to be unique. Use class name to replace text of multiple elements.

<a href="..something" class="content-something"></a>
<div class="content-sometext"></div>
Some more html...
<a href="..something" class="content-something"></a>]
<div class="content-sometext"></div>
March 7, 2013

I need to pullback data from a jquery ajax post and break the array out to seperate outputs

Question by Ezos

I need to get the array and instead of just pushing the data into an html div – get back the php variable.

My $.ajax post —-

  <script type="text/javascript">
    $(function() {

        $("#login").click(function() {
            var theName = $.trim($("#username").val());

            if(theName.length > 0)
            {
                $.ajax({
                  type: "POST",
                  url: "callajaxdemo.php",
                  data: ({name: theName}),
                  cache: false,
                  dataType: "text",
                  success: onSuccess
                });
            }
        });

        $("#resultLog").ajaxError(function(event, request, settings, exception) {
          $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
        });

        function onSuccess(data)
        {
            $("#resultLog").html("Result: " + data);
            //$.mobile.changePage('stats.html', { transition: 'slideup'}, true, true);
        }

    });
</script>'

My PHP file is —–

<?php
 $username = $_POST['username']; 
 $password = $_POST['password'];

$host = 'https://api.qpme.com/api/accounts/me';

$process = curl_init($host);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($process);

$content = json_decode($return);

/*
echo "<pre>";
print_r($content);
echo "</pre>";
*/

print $content->email . "<br>";
print "<h3>" . "Welcome" . ' ' . $content->firstName . ' ' . $content->lastName . '!' . "<h3>";

?>'

The goal would be to get back the array and then post certain parts of it to different jquery mobile pages.

Answer by Starx

You can send JSON data back to AJAX request.

Change your arrays to JSON like this:

echo json_encode($yourData);

To read this, you have to setup your script to accept JSON data

        $.ajax({
          type: "POST",
          url: "callajaxdemo.php",
          data: ({name: theName}),
          cache: false,
          dataType: "json", // <--- Here
          success: onSuccess
        });

Then you can access the properties as JavaScript Object.

    function onSuccess(data)
    {
        // access using data.item1
        //           or data.item2 how you prepare your array
    }
May 14, 2012

how to design grouped input text fields in one rounded corner box in jQuery Mobile

Question by EMMNS

can anyone tell me how can I put multiple text input fields in one grouped rounded corner box?

also with text place holder.

please see the attached image

input rounded corner box

I was trying from my side the code bellow:

<div data-role="content" data-inset="true" data-theme="b">
    <div data-role="fieldcontain">
    <form id="frmLogin" action="#" method="POST" data-transition="slide">
      <fieldset data-role="controlgroup" class="ui-corner-all ui-controlgroup ui-controlgroup-vertical">

        <div class="ui-field-contain">
          <label id="txtLoginName" for="loginName"></label>
          <input type="text" name="loginName" id="loginName" value=""  class="required"/>
        </div>
        <div class="ui-field-contain">
          <label id="txtLoginPassword" for="loginPassword"></label>
          <input type="password" name="password" id="loginPassword" value="" class="required"/>
        </div>

        <div class="ui-grid-a">
          <div class="ui-block-a">
            &nbsp;
          </div>
          <div class="ui-block-b">
            <a id="btnLoginSubmit" href="#" data-role="button" data-transition="slide" data-inline="true"></a>
          </div>
        </div>

      </fieldset>
    </form>
    </div>
  </div>

thanks in advance

Answer by Starx

I dont have your CSS to work with. So, here is a simple alternative.

CSS:

div {
    border: 2px #ddd solid;
    border-radius: 20px;
    width: 300px;
    padding: 20px;
}
div input {
    border: none;
    width: 260px;
    padding: 20px;
}
div input:not(:last-child) {
    border-bottom: 1px #ddd solid;
}

HTML:

<div>
    <input type="text"  value="email"/>
    <input type="password" value="password" />
</div>

Demo

April 15, 2012

is it possible to capture scrollstart on an element other than $(document) in Jquery/Javascript?

Question by frequent

I’m trying to use the Overthrow Plugin, which is a polyfill for overflow:auto on mobile devices. Sample here.

My question:
How can I detect scrollstart/scrollstop on a div.element that is scrollable? Is this possible at all, or do the scroll/scrollstart/scrollstop events only work on $(document)?

Specifically, if I have two panels on my page, which both are scrollable, is there any way to make this work:

 $(document).on('scrollstart','div:jqmData(panel="main"), div:jqmData(panel="menu")'), function() {
    console.log("scroll detected");
    });

Thanks for some inputs!

EDIT:
My HTML looks like this:

<html class="ui-popover-mode">
// OR depending on screen size
<html class="ui-splitview-mode">
   // panel 1
   <div data-panel="main" class="ui-panel">
       <div data-role="page" class="ui-page" id="mainOne">
           <div data-role="content" class="ui-content"></div>
       </div>
       <div data-role="page" class="ui-page" id="mainTwo">
           <div data-role="content" class="ui-content"></div>
       </div>
   </div>
   // panel 2
   <div data-panel="menu" class="ui-panel">
       <div data-role="page" class="ui-page" id="menuOne">
           <div data-role="content" class="ui-content"></div>
       </div>
       <div data-role="page" class="ui-page" id="menuTwo">
           <div data-role="content" class="ui-content"></div>
       </div>
   </div>
   // panel 3
   <div data-panel="pop" class="ui-panel">
       <div data-role="page" class="ui-page" id="popOne">
           <div data-role="content" class="ui-content"></div>
       </div>
       <div data-role="page" class="ui-page" id="popTwo">
           <div data-role="content" class="ui-content"></div>
       </div>
   </div>
</html>

Screen Mode is set depending on screen size. In every panel there can be multiple pages, which each have a content section, which is scrollable using overthrow.

I want to bind to scrollstart in main and menu content section in splitview-mode AND main content sections in popover-mode.

Originally my selector tried to capture this and only attach to the relevant content elements:

$(document).on('scrollstart','.ui-splitview-mode div:jqmData(panel="main") .ui-content,  .ui-splitview-mode div:jqmData(panel="menu") .ui-content, .ui-popover-mode div:jqmData(panel="main") .ui-content, ', function() {
        // do sth
    });

Agreed this is complex and did not work. But it attached events only to the necessary elements. Now I’m doing like this:

$('.ui-content').on('scrollstart', function() {
        // check here if .ui-content is on the correct panel
    });

So I now have a lot of unnecessary bindings and only check if the binding is correct after the event is detected vs. the other way I would only attach the event to the required elements.

That’s what I was wondering.

Answer by Starx

You can directly select the element and attach the scroll event. Simple example

$("#selector").on('scrollstart', function() {
    //...do stuff
});
April 3, 2012

how to apply this to all of my pages in jquerymobile

Question by Wondering Coder

Im using jquerymobile together with codeigniter framework and I’m having a problem

I have this script below and I want it to be trigger in all of my pages.

<script type="text/javascript">
        var i = 0;
    $(function() {
        $("#h1").hide();
        $("#h2").hide();
        $("#h3").hide();
        <? if ($account_type != 'prepaid' && $account_type != 'PREPAID') : ?>
            $("#h4").hide();
        <? endif ?>
        head();
        setInterval('head()',2000);
    });

        function head()
        {
            i++;
            if (i==1) h1();
            if (i==2) h2();
            <? if ($account_type == 'prepaid' || $account_type == 'PREPAID') : ?>
                if (i==3){ h3(); i=0; }
            <? else : ?>
                if (i==3) h3();
                if (i==4){ h4(); i=0; }
            <? endif ?>
        }

        function h1()
        {
            <? if ($account_type == 'prepaid' || $account_type == 'PREPAID') : ?>
                $("#h3").hide();
            <? else : ?>
                $("#h4").hide();
            <? endif ?>
            $("#h1").fadeIn().delay(1000);
            //h2();
        }

        function h2()
        {
            $("#h1").hide();
            $("#h2").fadeIn().delay(1000);
        }

        function h3()
        {
            $("#h2").hide();
            $("#h3").fadeIn().delay(1000);
        }

        function h4()
        {
            $("#h3").hide();
            $("#h4").fadeIn().delay(1000);
        }

    </script>

tried replacing the $(function() { to $(document).bind(‘pageinit’, function () { but still doesn’t work. The function only fires in my index.php not in the other pages. Please help.

Answer by regeint

Try this one.
Prepare an index file with following scripts

<script type="text/javascript">
var i = 0;
$(function() {
    start();        
});

function start(){

    $("#h1").hide();
    $("#h2").hide();
    $("#h3").hide();
    <? if ($account_type != 'prepaid' && $account_type != 'PREPAID') : ?>
        $("#h4").hide();
    <? endif ?>
    head();
    setInterval('head()',2000);
}

    function head()
    {
        i++;
        if (i==1) h1();
        if (i==2) h2();
        <? if ($account_type == 'prepaid' || $account_type == 'PREPAID') : ?>
            if (i==3){ h3(); i=0; }
        <? else : ?>
            if (i==3) h3();
            if (i==4){ h4(); i=0; }
        <? endif ?>
    }

    function h1()
    {
        <? if ($account_type == 'prepaid' || $account_type == 'PREPAID') : ?>
            $("#h3").hide();
        <? else : ?>
            $("#h4").hide();
        <? endif ?>
        $("#h1").fadeIn().delay(1000);
        //h2();
    }

    function h2()
    {
        $("#h1").hide();
        $("#h2").fadeIn().delay(1000);
    }

    function h3()
    {
        $("#h2").hide();
        $("#h3").fadeIn().delay(1000);
    }

    function h4()
    {
        $("#h3").hide();
        $("#h4").fadeIn().delay(1000);
    }

</script>

now, call this function when you initpage like the following

$('#my_page').live('pageinit',function(event){
start();

});

Answer by Starx

If you want to fire in other pages too. Include the script in all pages. Using

<script src="common.js"></script>
March 23, 2012

window.open() does nothing in jquery mobile?

Question by PathOfNeo

i can’t use target=_blank because my actions are build dynamically, example: when user clicks on the link, i catch it with .click(function(event), than ajax api is called and then in the callback i have the url where to go.

Now the problem:

window.location = mylink; // WORKS – OK!
window.open(mylink); // DOES NOT WORK – NOT OK!

why?

I need to open a new window because mylink is a link to a pdf file, and when using window.location the pdf file is correctly viewed, but,..without any back navigation controls of the browser. It’s a mobile webapp, and i use jquery mobile.

Too bad on the internet many others have the pdf viewer problem but no one has solved it, so i figured out to open a new window and pass the pdf link there. This way my parent window would stay untouched. Otherwise, you have to kill the current session and open safari again..

Answer by Starx

If you want to open a dialog/popup in jQuery Mobile you have to use an attribute data-rel="dialog" and the href attribute must point to a URL you want to load

<a href="yourpage.html" data-role="button" data-rel="dialog">Open dialog</a>
March 22, 2012

navigating between page divs with select and jquery mobile

Question by krapdagn

Trying to use this dropdown select to change to a different anchor on the page. It’s working except that when you select SF, it goes to the SF page and the selector button is set to SF. But if you then select NY, it goes back to #page1 but the default button stays as SF, unless the page is reloaded.

<select name="select1" id="select1" data-mini="true" data-native-menu="false" ONCHANGE="location = this.options[this.selectedIndex].value;">
<option value="#page1">New York, NY</option>
<option value="#SF">San Francisco, CA</option>
<option value="#LV">Las Vegas, NV</option>
<option value="#DAL">Dallas, TX</option>
</select>

What am I missing?

Thanks!

EDIT:

I think there is incomplete information here. On the #SF anchor text, for example, it’s an entirely new page with its own copy of the <select> in the header of that page. So what is happening is that when you select the second one to go back to the first, it doesn’t reset the first one.

Here is what the second select looks like:

<select name="select2" id="select2" data-mini="true" data-native-menu="false" ONCHANGE="window.location = this.options[this.selectedIndex].value;">
<option value="#SF">San Francisco, CA</option>
<option value="#page1">New York, NY</option>
<option value="#LV">Las Vegas, NV</option>
<option value="#DAL">Dallas, TX</option>

Here’s what happens

1 – Load #page1, NYC is preselected.
2 – Select SF, loads #SF, SF is selected because it is default in the second select
3 – Select NYC, it DOES load the NYC/#page1 page, but the select dropdown is still stuck on #SF because that was what it was last left at before the location changed.

Hopefully this more fully explains my problem. I’ve tried something like this (http://jsfiddle.net/QEUwg/132/) but it isn’t working, maybe because the two selects are in separate divs?

OK This works:

//refresh value         
$('select').selectmenu('refresh');

//refresh and force rebuild
$('select').selectmenu('refresh', true);

It only took about 20 hours of beating my head against the wall.

Answer by Starx

Use window.location instead of location

Update:

I will give you a better way since you are already using jQuery.

$("#select-choice-1").change(function() {
    $($(this).val())[0].scrollIntoView(true); 
})

Demo

Update 2

The problem is that you are using multiple select box and not updating all of them, when you are changing the page

$(".navigateToPage").on('change', function() {
    $(".navigateToPage").val($(this).val()); //set value for all the select boxes
    $(".navigateToPage").parent().find(".ui-btn-text").html($(this).find("option:selected").html()); 
    //^ Also find the text and update them

});

Working Solution

September 26, 2011

Why isn't my button click event being triggered?

Question by Sheehan Alam

I have the following js file:

var IOMaximizeButton = {
 setup: function () {
    $(this).click(function(){
        console.log("maximize button was clicked!");
    });
  }
};

$(document).ready(function() {
  IOMaximizeButton.setup();
});

Here is the body of my HTML:

 <body>
    <a href="#" data-role="button" data-icon="delete">Maximize</a>
    <iframe id='iframe-primary' name='iframe-primary' src='foo.html' />
    <iframe id='iframe-secondary' name='iframe-secondary' src='bar.html' />
    </body>

I want that javascript to execute when my button is clicked. But it doesn’t seem to be triggering. Why?

I have imported my JS file at the bottom of the HTML page btw.

Answer by James Allardice

In your object, this refers to the instance of the object itself, so you’re trying to bind a click event to the JavaScript object, rather than a DOM element. I’m guessing you actually want something like this:

var IOMaximizeButton = {
 setup: function () {
    $("#yourButton").click(function(){
        console.log("maximize button was clicked!");
    });
  }
};

Here’s a working example.

Answer by Starx

Your function is not attached to any selector, so I cannot catch any events. $(this) is a blank object.

Try changing $(this) to some specific selectors.

November 29, 2010

What sort of page weight / size should I be aiming for when optimising for mobile?

Question by Simon Scarfe

I’m looking to optimise the mobile browser experience in a small webapp, using the awesome jQuery mobile to do so.

It goes without saying that a user doesn’t want to DL 200k of data, I’m just trying to draw the line between using external and internal URLs. Is there any existing guideline of what sort of page sizes / loading times I should be shooting for? I’d prefer to stick to internal URLs (keep the mobile interface effectively in one place from a maintenance point of view), but am weary of bogging the user down with lots of information that they have no intention of viewing.

Answer by galambalazs

One thing to note is that e.g. iPhone won’t cache components bigger than 25K.

Also consider minifing and gzipping your code. And @jfar got one thing right. HTTP requests can be a huge performance hit, so you may also want to reduce them as much as possible.

Answer by Starx

I would say try to lower your page as much to 100kb, because if u manage to do so loading different pages as per user request might be negligible.

However, loading the big pile of content at a time and using simple javascript show and hide, to display the content in almost realtime manner might impress the viewer too.

...

Please fill the form - I will response as fast as I can!