dimanche 28 juin 2015

Changing an appended clone object in a loop - Javascript

I have a working JavaScript gist that create randomly three squares on the screen. The problem is now it's creating via the toAppend and clone() (see Initial Code at the bottom) 3 times the very same html block.

It generates currently:

<div class="info-square"><span class="square" data-target="#myInfoModal" data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal" data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal" data-toggle="modal" ></span></div>

I would like to have TO generate for each a different data-target for each div, like that:

<div class="info-square"><span class="square" data-target="#myInfoModal1"  data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal2"  data-toggle="modal" ></span></div>
<div class="info-square"><span class="square" data-target="#myInfoModal3"  data-toggle="modal" ></span></div>

The number 3 would come from the "var numInfoSquares"

INITIAL CODE

$(document).on('ready page:load', function () { 

    // Use jquery to display X squares according 
    var numInfoSquares = 3;
    var $zone = $("#zone");
    var $toAppend = $('<div class="info-square"><span class="square" data-toggle="modal" data-target="#myInfoModal"></span></div>');
    for (var c = 0; c < numInfoSquares; c++)
      $zone.append($toAppend.clone());
    // place squares randomly on the page
    function getRandomInt(min, max) {
      return Math.random() * (max - min + 1) + min;
    }
    $(".info-square").each(function () {
      var topPosition = getRandomInt(8, 70);  
      var leftPosition = getRandomInt(8, 92); 
      $(this).css({
        "top": topPosition+"%",
        "left": leftPosition+"%",
      });
    });   
  });  

Jquery for duplicate tabs

I am trying to create tabs in jquery and have been successful. However, there is one issue I am unable to solve and that is duplicate tabs.

With a single tab, jquery works fine but when I copy and paste that tab it does not work properly. I did add some extra code to find the tab in which the use is currently in by using the closest function but still no result.

Have a look at the code.

//HTML

<div class="tabsContainer">
    <ul class="tabs-nav">
        <li>
            <a href="#tab1" class="active">Tab One</a>
        </li>

        <li>
            <a href="#tab2">Tab Two</a>
        </li>

        <li>
            <a href="#tab3">Tab Three</a>
        </li>
    </ul>
    <section class="tabs-content">
       <div class="tabs active" id="tab1">
            This is tab 1<br />
            This is tab 1<br />
            This is tab 1<br />
        </div>

        <div class="tabs" id="tab2">
            This is tab 2<br />
            This is tab 2<br />
            This is tab 2<br />
        </div>

        <div class="tabs" id="tab3">
            This is tab 3<br />
            This is tab 3<br />
            This is tab 3<br />
        </div>
    </section>
</div>


//2nd tab
<div class="tabsContainer">
    <ul class="tabs-nav">
        <li>
            <a href="#tab1" class="active">Tab One</a>
        </li>

        <li>
            <a href="#tab2">Tab Two</a>
        </li>

        <li>
            <a href="#tab3">Tab Three</a>
        </li>
    </ul>
    <section class="tabs-content">
        <div class="tabs active" id="tab1">
            This is tab 1<br />
            This is tab 1<br />
            This is tab 1<br />
        </div>

        <div class="tabs" id="tab2">
            This is tab 2<br />
            This is tab 2<br />
            This is tab 2<br />
        </div>

        <div class="tabs" id="tab3">
            This is tab 3<br />
            This is tab 3<br />
            This is tab 3<br />
        </div>

    </section>
</div>

CSS Code

.tabsContainer{
    overflow:hidden;
}
.tabs-nav{
    overflow:hidden;
    margin:0;
    padding:0;
    list-style:none;
}
.tabs-nav li {
    display: inline-block;
    background: #34495E;
    border-width: 1px 1px 0 1px;
    border-style: solid;
    border-color: #34495E;
    margin-right: 5px;
}
.tabs-nav li a {
    display: block;
    padding: 10px 15px;
    font-weight: bold;
    color: #fff;
}
.tabs-nav li a.active {
    background: #FFF;
}

.tabs-nav li a.active {
    color: inherit;
}
.tabs-content {
    border: 1px solid #34495E;
    padding: 10px;
    background: #FFF;
    margin-top: -1px;
    overflow:hidden;
}
.tabs-content .tabs{
    overflow:hidden;
    display:none;
    margin:0 0 30px;
}
.tabs-content .tabs.active{
    display:block;
}

JAVAScript

$(function() {

    //listeing for click events
    $('.tabsContainer .tabs-nav li a').on('click', function(){

        //if more than 1 tab find out which tab you are currently in using the closest function
        //by clicking on the a tag it will find which container it is a part of.
        var $tab = $(this).closest('.tabsContainer'); 

        $tab.find('.tabs-nav li a.active').removeClass('active');
        $(this).addClass('active');
        //grabbing the tab which is clicked using the attribute "href"
        var currentClick = $(this).attr('href');

        //hiding the current panel
        //using a call back function. What this does is wait for the slideup to finish and then it will excute the call back function
        $tab.find('.tabs-content .tabs.active').slideUp(300, nextTab);

        //the call back function to show the new tab
        function nextTab(){
            $(this).removeClass('active');
            $(currentClick).slideDown(300, function(){
                $(this).addClass('active');
            });
        }
    });
});

check a checkbox and save it with the selected name using jquery

I'd like to assign a different homeworks to three different students , so once i choose the student from the drop down list and check with the checkbox the wanted homework for that student i like it to be his own homework "after a confirming message " so once again i choose another student and the homework that i already assign it to the previous student would be disable or hidden so it would be only assigning the non taken homeworks so in the end under each student will be the assigned homeworks using jquery.

i hope you would help me ... thank you

here is my code HTML

    <html>
    <div id="containerlog">
    <form>
    <label for="name">Student Name:</label>
    <select>
       <option value="Jhon">Jhon</option>
       <option value="Jessi">Jessi</option>
       <option value="Baker">Baker</option>
    </select>
    <div>
    <input type="checkbox"><label class="check" for="checkbox">HW-1</label>
    </div>
    <div>
    <input type="checkbox"><label class="check" for="checkbox">HW-2</label>
    </div>
    <div>
    <input type="checkbox"><label class="check" for="checkbox">HW-3</label>
    <br>
    </div>
    <div>
    <input type="checkbox"><label class="check" for="checkbox">HW-4</label>
    </div>
    <div>
    <input type="checkbox"><label class="check" for="checkbox">HW-5</label>
    </div>
    <div>
    <button type="button" onclick="alert('Are you sure!')">Submit</button>
    </div>
    <div id="checker"></div>
    </div>
    </form>

    *JQUERY*

    $(document).ready(function(){
    $( "input" ).on( "click", function() {
    $( "#checker" ).html( $( "input:checked" ).hide());
    });
    });

Wordpress: Need help to customize .js code to call out specific dynamic class within Visual Composer

Im a novice programmer / designer trying to have fun with some js libraries. With my basic knowledge of code I was able to get 80% there, but Im afraid Im missing the last piece of the puzzle. The site in question is www.topcatsmusic.com

At the bottom ive coded a player which utilizes js. Beneath the player Ive included a dynamic slider to display .jpg files or album covers. As it is now, Ive been using a simple href tag to send to external soundcloud source.

However, the plugin allows you to make API calls to en-queue the song within the player instead of sending to new window, outside source.

Sample API usage:

ToneDen.player.getInstanceByDom("#player").getTrack("http://ift.tt/1NpyKBY");

Custom JS file in use "Clickfunction.js"

  $('.ult-item-wrap a').click(function(e) {
    var sound = $(this).attr('href');
    ToneDen.player.getInstanceByDom("#player").addTracks(sound);
    ToneDen.player.getInstanceByDom("#player").removeTracks(0, 1);
    ToneDen.player.getInstanceByDom("#player").addTracks(sound);
    alert(ToneDen.player.getInstanceByDom("#player").getAllTracks());
    return false;
  });

So, if I load the JS file using the

<script> </script>

within my header - what do I need to do to customize this code so I can identify which song to load based on the custom class assigned to each image?

jquery function executing multiple time for bootstrap modal

$(document).on('click', '.event_class', function() {

    $('#originalImageShow').modal('show');

    $('#originalImageShow').on('shown.bs.modal',  function() {
        alert('Modal Open');
    });
    $('#originalImageShow').on('hidden.bs.modal', function() {
        alert('Modal Close');
        $('#originalImageShow').off();
        $(this).removeData('bs.modal');
    });

});

Hi, Each time I click the event_class It shows "Modal Open" alert twice. Even sometimes it shows multiple times. And also when I close the Bootstrap Modal sometimes it shows "Modal Close" alert multiple times. Basically number of alert number is changing randomly. Please help.

Why does this Javascript populate forms okay in Chrome and Firefox, but not Internet Explorer? [on hold]

Local Storage is used with Key 'Preferences' and content in JSON name: value: pairs.

Below is code my to populate a fieldset from that localstorage:

var fData = JSON.parse(localStorage.getItem('Preferences'));
if (fData) {
  for (var pair in fData) {      
        $('[name=' + fData[pair].name + ']').val(fData[pair].value);                            
  }
}

It works fine in Chrome and Firefox but not IE - any reason why not? How do I fix?

fade text from a word | javascript

i am trying to work on this javascript, where when the page loads, i need the text "Hello World" to zoom on page load, and it should pause for 3 seconds, and then when it zooms out, it should retain only "H" from hello and "W" from world. So when it zooms out, only H and W will go back to a position.

  window.onload = function() {

         // 3. Page load completes - the text "hello",
// has come to center with zoom 800%
$("#hello").animate({
  zoom: "350%",
  left: window.innerWidth / 2
}, 3000, function() {
  // 4. Pause for 3 seconds
  $(this).delay(3000)
  // 6. zooms out to 200% heading towards left top corner,
  // (logo position) 
  // 7. Fades out when reaching the logo 8. Logo appears
  .animate({
    zoom: "100%",
    left:0
  }, 3000, function() {
    $(this).fadeOut()
  })
})
         };


<div id="hello">
  <h1 style="zoom: 200%; transition: zoom 1s ease-in-out;">Hello World</h1>
</div>

Drag and Drop between 2 listboxs & Database Update

I want to implement a facility for a web app users for drag an item from a listbox and drop it to the other listbox. After every Drag & Drop needs to update a sql table. I googled about D&D and find some solutions, but I do not know which one is the best? and also I do not know the right way. Which on I have to use? jquery, Ajax, or some other plugins? I'd appreciate If someone give me a pathway to accomplish this task.

Drag, drop, sortable system using jQuery

This is quite a complicated question so I am not looking for "full examples", but instead ideas of implementing a solution to my problem.

I am creating a drag-and-drop page where users can drag and drop tools into their workspace. This is currently working fine through the implementation of draggable() (jQuery UI).

However, the system is getting complicated with new features I am implementing:

  • When dragged onto the workspace, the user can freely move the items around their page. However I would like the user to be able to drag items on top of other divs- and this dropped item should "morph" into this div (hopefully by using append()). This specific div that the element is dropped onto implements sortable(), so where ever the dropped element is placed should be its specific position on this sortable list.

    • EXAMPLE: If the div contains a number of dropped elements; lets say 5 items, if another item is dropped in between the 2nd and 3rd items, it should be appended to this div in that position.
  • Secondly, any element that is appended to a sortable div should then have the ability of being dragged out of this sortable div (un-appended) and back onto the main area of the workspace (I have no clue of how to do this!) BUT it should still holds its ability of being sorted (list should still be sortable).

I am using jQuery + jQuery UI to complete this project and may use other javascript-based extensions if they can complete my desired outcome easily.

Type of implementation I have at the moment

This implementation is very unfinished.

    $("div.layout.lo-content > div.content").droppable(
    {
        drop: function(e, ui)
        {
            $(ui.draggable).appendTo($(this));
            if($(this).hasClass("ui-sortable"))
            {
                $("div.content").sortable('refresh');
            }
        }
    });

^^ when doing sortable('refresh') it breaks the system with error:

Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'refresh'

The sortable list which the item is dragged onto:

$("div.layout.lo-content > div.content").sortable(
{
    opacity:0.7,
    axis:'y',
    start: function(e, ui)
    {
        $(this).children("div.ui-sortable-placeholder").css("height",$(ui.helper).css("height"));
    }
});

Cannot Click button when table row with button is appended

http://ift.tt/1RIfuRa

$('#insertBtn').click( function(){
    $('#mytable > tbody:last-child').append('<tr><td>'+$('#fnameText').val()+'</td><td>'+$('#lnameText').val()+'</td><td>'+$('#pointText').val()+'</td><td><button type="button" class="deleteClass">Delete</button></td></tr>');
    $('#textTable input').val('')
});

$(".deleteClass").on("click",function() {
    alert('row deleted');
});

Try typing anything into the textboxes. Then click on the insert button. Then click on the delete button on the first column. Notice the alert didn't trigger even though the button has the intended class

What is wrong with my code?

Load ajax success data on new page

My ajax call hits the controller and fetches a complete JSP page on success. I was trying to load that data independently on a new page rather than within some element of the existing page. I tried loading it for an html tag but that didn't work either. I tried skipping the success function but it remained on the same page without success data. My ajax call is made on clicking a normal button in the form and the code looks like as shown below.

$.ajax({

    url : '/newpage',
    type : 'POST',
    data : requestString,
    dataType : "text",
    processData : false,
    contentType : false,
    success : function(completeHtmlPage) {
        alert("Success");
        $("#html").load(completeHtmlPage);
    },
    error : function() {
        alert("error in loading");
    }

});

Auto click a shortcode link in wordpress

 if ( !(is_user_logged_in()) ) {
                ?>
               <script>
                $(document).ready(function() { 
                    $('#show_login').trigger('click');
                });
            </script>
            <?php echo do_shortcode('[ciusan_login]'); 
              } 

 do_shortcode('[ciusan_login]')= login link where id = show_login

I am trying to click this link automatically if the user is not logged in.but its not clicking that link . can any body help me.this code is in wordpress.

I found that div scroll event can fired continuously in android,but render will lag until scroll end?

I found that div scroll event can fired continuously in some android device,but render will lag until scroll end?

I tested: Samsung Galaxy Nexus

var outerContent = document.getElementById('outer-content');
var demo = document.getElementById('demo');
var tempStr = '';
var index = 0;


for(var i = 0;i < 800;i++){
  tempStr +='<div class="s-item">\
        <div class="item-bg" style="width:100%;">'+(index++) + '</div>\
       </div>';
  }

outerContent.innerHtml = tempStr;


outerContent.onscroll = function(e){
  document.title = e.target.scrollTop; //this will update continously during scroll
  
  
  // element change its color only when scroll stop
  demo.style.background = 'yellow';
  
};
.outer-content{
  width:100%;
  height:500px;
  overflow:auto;
 }

.item-bg{
  height:38px;
  background:green;
 }

#demo{
  width:40px;
  height:40px;
  background:red;
  position:absolute;
  right:0;
  top:0;
  z-index:99;
}
<div id="demo"></div>
<div id="outer-content" class="outer-content"></div>

Is there some solution for such situation?

Uncaught TypeError: Cannot read property 'length' of undefined when trying to populate responsive datatable using php?

I am trying to fill responsive datatable with ajax request to a php script , the response is returned a JSON_encode format , i can see the response in xhr requests: ["abc","def","ght","jkl"]

Here is the code i am using

Name

                                    </tr>
                                </thead>
                             <tfoot>
        <tr>
            <th>Name</th>

        </tr>
    </tfoot>
    </table>




    $('#dataTables-example').DataTable({
            responsive: true,
               "ajax": "search_autocomplete.php",


    });

});

here is the php script-

   if ($result->num_rows >0) {
// output data of each row
while($row = $result->fetch_assoc()) {


    $list[] =$row['name'];

    }       
      echo json_encode( $list );            

}

show the li that has an anchor link which has a data attribute name "data-link" that match unto specified text

Base from my snippets below, firstly, If i clicked unto any branch from a dropdown that has a label of "select branch", then it will get the text from a clicked branch (anchor link e.g. Iligan) and then hide all the li's from the ul of a dropdown that has a label of "select user" and then show all li's that has a link with a data attribute named "data-link" and its content match on the text of the select branch dropdown currently clicked link but sadly not working, I can hide all li's but unable to show those li that has an anchor link with a data attribute named "data-link" which data-link content is matched to the text of the currently clicked link from the select branch dropdown. Any help, suggestions, clues, recommendations, ideas would be greatly appreciated. Thank you!

//user change pass on user management
    $(".uu .uu_dp a").click(function(e){
        $(this).parents(".uu").find(".unregistered_user").text("User: " + $(this).text());
        $(this).parents(".uu").find(".unregistered_user").attr("data-link", $(this).attr("data-link"));
        bbr = $(this).parents(".uc_header").next().find(".uu_cp_form fieldset");
        $(this).parents(".daselect").next().find("form").slideDown();
        e.preventDefault();
    });
    //u branch on user management
    $(".ub .ub_dp a").click(function(e){
        $(this).parents(".ub").find(".u_branch").text("Branch: " + $(this).text());
        $(this).parents(".ub").find(".u_branch").attr("data-link", $(this).attr("data-link"));
        $(this).parents(".daselect").find(".uu .uu_dp li").hide();
        (this).parents(".daselect").find('.uu .uu_dp li a[data-link="Iligan"]').show;
        e.preventDefault();
    });
<script src="http://ift.tt/1oMJErh"></script>
<script src="http://ift.tt/1InYcE4"></script>
<link href="http://ift.tt/1K1B2rp" rel="stylesheet"/>
<div class="extend clear daselect">
                <div class="btn-group ub align_left margin_right5px">
                    <button type="button" class="btn btn-default u_branch" data-toggle="dropdown">Select branch</button>
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                        <span class="caret"></span>
                        <span class="sr-only">Toggle Dropdown</span>
                    </button>

                    <ul class="ub_dp dropdown-menu" role="menu">
                            <li><a href="#" data-identity="cp">Iligan</a></li>
                      <li><a href="#" data-identity="cp">Corporate</a></li>
                      <li><a href="#" data-identity="cp">Initao</a></li>
                    </ul>
                </div>
                <div class="btn-group uu align_left">
                  <button type="button" class="btn btn-default unregistered_user" data-toggle="dropdown">Select User</button>
                  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">Toggle Dropdown</span>
                  </button>

                  <ul class="uu_dp dropdown-menu" role="menu" style="height: 300px;">
                        <li><a href="#" data-id="1" data-link="Iligan">User 1 of Iligan</a></li>
                    <li><a href="#" data-id="2" data-link="Iligan">User 2 of Iligan</a></li>
                    <li><a href="#" data-id="3" data-link="Iligan">User 3 of Iligan</a></li>
                    <li><a href="#" data-id="4" data-link="Corporate">User 1 of Corporate</a></li>
                    <li><a href="#" data-id="5" data-link="Corporate">User 2 of Corporate</a></li>
                    <li><a href="#" data-id="6" data-link="Initao">User 1 of Initao</a></li>
                  </ul>
                </div>
            </div>

jquery countdown changes when user change its system time

i'm using jquery countdown with php. i have given an end date which is going to the countdown. my problem is lets suppose 1 hour left is showing in countdown but when a user change its system time the countdown changes. like if a user back his time 1 hour then the counter will display the 2 hours left. is there any way to get the server time for more accurate time not the user system time. please help.

how can i get server time not user system time?

What Code To Add To TableSorter To Retrieve Data From A List Of Specific Columns?

I have a range of 34 districts and 34 postcodes in individually named columns in MySql and xml. A user inputs information and will select only 1 district and 1 postcode (also other information is input). This will leave 33 empty columns for postcodes and districts.

What code do I need to add to make TableSorter display (in child rows) only the single district and postcode that has been input and ignore the empty column (district & postcode) values?

I have TableSorter displaying most of my required data on the front end using the following code:

    <meta charset="utf-8">
    <!-- jQuery -->


<!-- Tablesorter: required -->
<link rel="stylesheet" href="../css/theme.blue.css">


<!-- Tablesorter: pager -->
<link rel="stylesheet" href="../css/jquery.tablesorter.pager.css">


    <script>
    $(function() {

    $(".tablesorter")
    .tablesorter({
    theme : 'blue',
    // this is the default setting
    cssChildRow: "tablesorter-childRow",

    // initialize zebra and filter widgets
    widgets: ["zebra", "filter", "pager"],

    widgetOptions: {
    // output default: '{page}/{totalPages}'
    // possible variables: {page}, {totalPages}, {filteredPages},                     {startRow}, {endRow}, {filteredRows} and {totalRows}
    pager_output: '{startRow} - {endRow} / {filteredRows} ({totalRows})', // '{page}/{totalPages}'
    pager_removeRows: false,
    // set number of rows to show; make sure to include this
    // value in the select options
    pager_size: 100,  
    // include child row content while filtering, if true
    filter_childRows  : true,
    // class name applied to filter row and each input
    filter_cssFilter  : 'tablesorter-filter',
    // search from beginning
    filter_startsWith : false,
    // Set this option to false to make the searches case sensitive
    filter_ignoreCase : true
  }

});
 // hide child rows
     $('.tablesorter-childRow td').hide();

  // Toggle child row content (td), not hiding the row since we are using rowspan
  // Using delegate because the pager plugin rebuilds the table after each page change
  // "delegate" works in jQuery 1.4.2+; use "live" back to v1.3; for older jQuery - SOL
  $('.tablesorter').delegate('.toggle', 'click' ,function(){

// use "nextUntil" to toggle multiple child rows
// toggle table cells instead of the row
$(this).closest('tr').nextUntil('tr.tablesorter-hasChildRow').find('td').toggle();

  return false;
  });

  // Toggle widgetFilterChildRows option
  $('button.toggle-option').click(function(){
var c = $('.tablesorter')[0].config.widgetOptions,
o = !c.filter_childRows;
c.filter_childRows = o;
$('.state').html(o.toString());
// update filter; include false parameter to force a new search
$('table').trigger('search', false);
return false;
  });
});
</script>


<div id="demo">

<div class="pager">
    <img src="../assets/images/first.png" class="first" alt="First" />
    <img src="../assets/images/previous.png" class="prev" alt="Prev" />
    <span class="pagedisplay"></span> <!-- this can be any element, including an input -->
    <img src="../assets/images/next.png" class="next" alt="Next" />
    <img src="../assets/images/last.png" class="last" alt="Last" />
    <select class="pagesize" title="Select page size">
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
        <option value="40">40</option>
        <option value="50">50</option>
        <option value="100">100</option>
    </select>
    <select class="gotoPage" title="Select page number"></select>
</div>

<table class="tablesorter">
<colgroup>
    <col width="85" />
    <col width="110" />
    <col width="110" />
    <col width="100" />
    <col width="100" />
</colgroup>
<thead>
    <tr>
        <th>Id No #</th>
        <th>Province</th>
        <th>Date</th>
        <th>Country</th>
        <th>Package Type</th>
    </tr>
</thead>
<tbody>
    <!-- First row expanded to reveal the layout -->
[[+innerrows.row]]
    </tbody>
</table>

   </div>

I want to add code to the following so to include as child rows the only selected district and postcode:

        <tr>
<td rowspan="4"> <!-- rowspan="4" makes the table look nicer -->
    <a href="#" class="toggle">[[+id]] - More info</a> <!-- link to toggle view of the child row -->
</td>
<td>[[+province]]</td>
<td>[[+date132]]</td>
<td>[[+country]]</td>
<td>[[+packagetype]]</td>
</tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Customer Name</div><div>[[+yourname]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Phone Number</div><div>[[+phonenumber]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Email Address</div><div>[[+email128]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Company Name</div><div>[[+companyname]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Package Weight</div><div>[[+weight]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Package Width</div><div>[[+width]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">package Height</div><div>[[+height]]<br></div></td></tr>
<tr class="tablesorter-childRow"><td colspan="5"><div class="bold">Details</div><div>[[+details]]<br></div></td></tr>

Here is the xml including the 34 districts and postcodes:

    <model package="shipsaveeng" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
<object class="ShipSave" table="shipsaveeng" extends="xPDOSimpleObject">
<field key="id" dbtype="int" precision="11" phptype="integer" null="false" default=""/>
<field key="province" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district1" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district2" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district3" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district4" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district5" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district6" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district7" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district8" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district9" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district10" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district11" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district12" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district13" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district14" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district15" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district16" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district17" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district18" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district19" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district20" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district21" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district22" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district23" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district24" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district25" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district26" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district27" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district28" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district29" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district30" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district31" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district32" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district33" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="district34" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="postcode1" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode2" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode3" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode4" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode5" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode6" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode7" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode8" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode9" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode10" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode11" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode12" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode13" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode14" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode15" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode16" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode17" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode18" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode19" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode20" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode21" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode22" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode23" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode24" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode25" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode26" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode27" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode28" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode29" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode30" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode31" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode32" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode33" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="postcode34" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="date132" dbtype="date" phptype="date" null="true" default="0000-00-00"/>
<field key="country" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="phonenumber" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="email128" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="companyname" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="packagetype" dbtype="varchar" precision="255" phptype="string" null="false" default=""/>
<field key="weightkgs" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="width" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="length" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="height" dbtype="decimal" precision="11.0" phptype="string" null="false" default=""/>
<field key="details" dbtype="text" phptype="string" null="false" default=""/>
<index alias="PRIMARY" name="PRIMARY" primary="true" unique="true">
    <column key="id" collation="A" null="false" />
</index>
    <aggregate alias="Resource" class="modResource" local="resource_id" foreign="id" cardinality="one" owner="foreign" />
    <aggregate alias="Creator" class="modUser" local="createdby" foreign="id" cardinality="one" owner="foreign" />
</object>
</model>

what is wrong in this code for validation of controls?

I use jquery for validation of controls .my codes like this:

function RegisterClient() {
    var bookname = true; var edition = true; var author = true; var price = true; var imgType = true; var imgSize = true;

    if (j('#txt_book_name').val() === null) {   //1
        j('#alertBookName').removeClass('hidden');
        bookname = false;
    }
    if (j('#txt_edition').val() === null) {     //2
        j('#alertEditionbook').removeClass('hidden'); edition = false;
    }
    if (j('#txt_author').val() === null) {       //3
        j('#alertAuthor').removeClass('hidden'); author = false;
    }
    if (j('#txt_price').val() === null) {        //4
        j('#alertPrice').removeClass('hidden'); price = false;
    }
    var fileType = j("#ContentPlaceHolder1_FileUpload1").val().split('.').pop().toLowerCase();
    if (j('#ContentPlaceHolder1_FileUpload1').val() != "" && j.inArray(fileType, ['gif', 'png', 'jpg']) == -1)
    { j('#alertImgType').removeClass('hidden'); imgType = false; }
    if (j('#ContentPlaceHolder1_FileUpload1').val() != null) {
        var sizeImg = j("#ContentPlaceHolder1_FileUpload1")[0].files[0].size/1024;
        if (sizeImg > 25) { j('#alertImgSize').removeClass('hidden'); imgSize = false; }
    }
    if (bookname && edition && author && price && imgType && imgSize) __doPostBack('ctl00$ContentPlaceHolder1$Button1', '');

}

1.In sections 1 ,2,3,4 (j('#txt_...').val() === null) statment is not work curectly

2.(var sizeImg = j("#ContentPlaceHolder1_FileUpload1")[0].files[0].size/1024;)

statment have an error when use firbug .I can show value of j("#ContentPlaceHolder1_FileUpload1")[0].files[0].size with Alert() but here have an error.

Please help.

Dynamic loading on modules from modules in requirejs

I'm using requirejs and have an app.js that pulls in framework.js and initializes it and passes in settings and modules with their own settings. Problem is $('[data-navigation]').navigation(); is triggering before the navigation module, which is a jQuery plugin, is ready. If I add around a 500ms delay it works.

require(['jquery-private', 'framework', 'navigation'],
function($, framework, navigation) {

    //==========
    // Initialize the framework core.
    //==========
    var core = framework.init({
        // Core settings.
        namespace: '',

        // Initialize modules.
        modules: {
            navigation: {
                openClass: 'open',
            },
        },
    });

    //==========
    // App logic.
    //==========
    $('[data-navigation]').navigation();
});

Here is how the modules are initialized. I think the problem is happning with this require([moduleName], function(module) {} running while the script continues on.

define(['jquery', 'matchmedia'], function($) {

    //==========
    // Core initialization object.
    //==========
    var init = function(customOptions) {


        //==========
        // Logic
        //==========


        //==========
        // Load a module with it's custom options.
        //==========
        function initModule(module, customOptions, coreObject) {
            // Get the previously defined module or the path to load it.
            var moduleName = (require.defined(module)) ? module : config.modulesDir + '/' + module;

            // Initialize the module.
            require([moduleName], function(module) {
                var returnObject = module.init(customOptions, coreObject);

                // Add to the loaded modules if not already present.
                if (settings.modules.indexOf(moduleName) < 0) {
                    settings.modules.push(moduleName);
                    settings.m[moduleName] = returnObject;
                }
            });

            return settings.m[moduleName];
        }


        //==========
        // Logic
        //==========


        //==========
        // Build the core object.
        //==========
        var core = {
            // Properties.
            // Methods.
        }


        //==========
        // Load the defined modules.
        //==========
        $.each(config.modules, function(index, value) {
            initModule(index, value, core);
        });


        //==========
        // Return the core object.
        //==========
        return core;
    }


    //==========
    // Return the initialization object.
    //==========
    return {
        init: init
    }
});

I've been at this for a while now. I'm pretty sure there is a solution, but I can't seem to wrap my head around it. Any guidance is appreciated.

Here is a good chunk of the navigation module code if it helps.

define(['jquery'], function($) {

    //==========
    // Module initialization object.
    //==========
    var init = function(customOptions, core) {
        // Ensure customOptions is an object.
        var customOptions = typeof customOptions !== 'undefined' ? customOptions : {};
        // Get the custom selector or the modules default.
        var selector = typeof customOptions.selector !== 'undefined' ? customOptions.selector : '[' + core.space('data-navigation') + ']';


        //==========
        // Build the jQuery plugin.
        //==========
        $.fn.navigation = function(options) {

            //==========
            // Plugin code.
            //==========

        }


        //==========
        // Initialize the plugin.
        //
        // RUNNING THE PLUGIN FROM HERE DOES WORK, BUT I NEED IT TO WORK FROM THE APP.JS TOO!
        //
        //==========
        $(function() {
            if ($(selector).length > 0) {
                $(selector).navigation(customOptions);
            }
        });


        //==========
        // Return object for core.m.[module]
        //==========
        return {};
    }


    //==========
    // Return the module initialization object.
    //==========
    return {
        init: init
    }
});

Datatables draw() without ajax call

I'm trying to resize server-side Datatables to fit the screen size. When the window size is changed I make recalculation of new datatables height and then call draw(false) to redraw the layout of datatable.

Unfortunately, the draw() method makes an ajax call and this makes the solution unusable, because it shows "processing" and takes time to get the data on every small window change.

How to redraw datatables layout without calling AJAX? I don't need to refresh data, I just want to redraw the table.

java ajax autocomplete not working

Ajax auto complete is not working. I debug the code and found that in my controller where I wrote the json line the debugger failed to debug there. I am new too this, plz help me out.

Controller

    response.setContentType("application/json");
        try {
                String term = request.getParameter("term");
                System.out.println("Data from ajax call " + term);

                AutoData a = new AutoData();
                a.setName(term);

                DataDao d = new DataDao();
                List<AutoData> data = d.getData();


                String searchList = new Gson().toJson(data);
                response.getWriter().write(searchList);
        } catch (Exception e) {
                System.err.println(e.getMessage());
        }
}

DataDAO

public class DataDao {
        private String sql;
        private ResultSet rs;


        public List<AutoData> getData(){
            List<AutoData> aData = new ArrayList<AutoData>();
            try{
            sql = "select * from userdetails";
            rs = DBConnection.executeQuery(sql);
            while(rs.next()){

                AutoData a = new AutoData();
                a.setName(rs.getString("userid"));
                aData.add(a);
            }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
            }
            return aData;





}
}

AJAX CODE

$(document).ready(function() {
        $(function() {
                $("#search").autocomplete({     
                source : function(request, response) {
                $.ajax({
                        url : "AutoController",
                        type : "GET",
                        data : {
                                term : request.term
                        },
                        dataType : "json",
                        success : function(data) {
                                response(data);
                        }
                });
        }
});
});
});

samedi 27 juin 2015

change css attributes after slider class changed

i am using codetabs.js for my project and now i hava a problem with that i hava an tab box with 4 tabs and wanna To organize those in side by side layout , i mean content of next tab shows at side of active tab . i used this jquery code :

<script>
jQuery(document).ready(function($) {
    $(".ct-ready.ct-cur").next().css({"visibility": "visible", "margin-left": "45%"});
 }); 
</script>

and it worked but just for firs tab and when active tab changed attributes those i added doesn't remove and next tab (number 3 tab) hasn't any attributes .

how i can solve this problem to Dynamically change of attributes after class change ? or how to use another way to side by side tabs ?

thanks for your answers.

I should also mention that the call back event of tab change is :

code.ev.on('selectID', function() {

and id used it too , this one problem is just the attributes doesn't remove after class change i think solve this on is easier

Load HTML/PHP into div, iframe alternative

I have an html/php page which I want to place into a div, but i'd prefer not to use an iframe. The page relies on a get request to work. Is there any purpose built framework/solution for this type of problem.

change an objects color after scrolling

hey I what a make a object which can change color after scrolling (down) 100px and change back to default after srolling back (up). Im using this code but not working

JQuary:

$(window).scroll(function() {

//After scrolling 100px from the top...
if ( $(window).scrollTop() >= 100 ) {
$('#menu').css('background', '#fff');

//Otherwise remove inline styles and thereby revert to original stying
} else {
$('#menu').removeAttr('style');

}
});​

and my html:

<header>
<table>
<tr>
<td  id="menu" class="title">
TITLE
</td>
<td style="width:40px;">
<div class=" ico">    
<img src="search.svg" alt="search" style="width: 25px;" />
</div>
</td>
<td style="width: 40px;">
<div class=" ico">
<img src="menu.svg" alt="search" style="width: 25px;"/>
</div>
</td>
</tr>
</table>
</header>

Function from external js link not working Properly On Mean.js

Can anyone help me with this problem?

OKay im using Mean.js(Im a newb) and on my home controller im trying to call my Jquery dependencies witch came with the tamplate i bought. This is the code im using.

'use strict';angular.module('core').controller('HomeController', ['$scope', '$http', '$location', 'Authentication',
function($scope, $http, $location, Authentication) {
    // This provides Authentication context.
    $scope.authentication = Authentication;
    if (!$scope.authentication.user) $location.path('/signin');
        $scope.inicio = function(){ 
            jQuery(document).ready(function() {  

            App.setPage("index");
            App.init(); 
            });
        };  
}]);

And calling my JS from config/env/all.js and here is it
'public/lib/angular/angular.js',
            'public/lib/angular-resource/angular-resource.js', 
            'public/lib/angular-cookies/angular-cookies.js', 
            'public/lib/angular-animate/angular-animate.js', 
            'public/lib/angular-touch/angular-touch.js', 
            'public/lib/angular-sanitize/angular-sanitize.js', 
            'public/lib/angular-ui-router/release/angular-ui-router.js',
            'public/lib/angular-ui-utils/ui-utils.js',
            'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
            'public/tema/js/jquery/jquery-2.0.3.min.js',
            'public/tema/js/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js',
            'public/tema/bootstrap-dist/js/bootstrap.min.js',
            'public/tema/js/uniform/jquery.uniform.min.js',
            'public/tema/js/backstretch/jquery.backstretch.min.js',
            'public/tema/js/bootstrap-daterangepicker/moment.min.js',
            'public/tema/js/bootstrap-daterangepicker/daterangepicker.min.js',
            'public/tema/js/jQuery-slimScroll-1.3.0/jquery.slimscroll.min.js',
            'public/tema/js/jQuery-slimScroll-1.3.0/slimScrollHorizontal.min.js',
            'public/tema/js/jQuery-BlockUI/jquery.blockUI.min.js',
            'public/tema/js/sparklines/jquery.sparkline.min.js',
            'public/tema/js/jquery-easing/jquery.easing.min.js',
            'public/tema/js/easypiechart/jquery.easypiechart.min.js',
            'public/tema/js/flot/jquery.flot.min.js',
            'public/tema/js/flot/jquery.flot.time.min.js',
            'public/tema/js/flot/jquery.flot.selection.min.js',
            'public/tema/js/flot/jquery.flot.resize.min.js',
            'public/tema/js/flot/jquery.flot.pie.min.js',
            'public/tema/js/flot/jquery.flot.stack.min.js',
            'public/tema/js/flot/jquery.flot.crosshair.min.js',
            'public/tema/js/jquery-todo/js/paddystodolist.js',
            'public/tema/js/timeago/jquery.timeago.min.js',
            'public/tema/js/fullcalendar/fullcalendar.min.js',
            'public/tema/js/jQuery-Cookie/jquery.cookie.min.js',
            'public/tema/js/gritter/js/jquery.gritter.min.js',
            'public/tema/js/script.js',

Some dependencies do work but some dont its very wierd, and if i call it from console(Google chrome) everything works fine but cant make it work from the controller. Im sorry my english is bad.. And thanks for the help

HTML5 Local storage - Save last audio position.

I'm new to jQuery and HTML5. I'm messing around with local storage. Pretty cool. I'm trying to figure out with this audio player to have local storage load the last mp3 file the user clicked with HTML5 local storage.

The player will auto play and loop the same track over and over.

I'm also trying to have once the user click the stop button (pause) the audio player will stay on that as well for when the user goes back to the page with HTML5 local storage!

Thank you for any help! I'm still learning!

<div id="wrapper">
    <br>
    <a href="#" class="pause" data-src="music/1.mp3">Stop Music</a>
    <br><br>


    <audio preload></audio>
    <ol>

        <li><a href="#" class="track" data-src="music/1.mp3">Music 1</a>
        </li>
        <li><a href="#" class="track" data-src="music/1.mp3">Music 2</a>
        <li><a href="#" class="track" data-src="music/1.mp3">Music 3</a>
        </li>
    </ol>
</div>

<script src="jquery-1.11.3.min.js"></script>
<script src="audio.min.js"></script>
<script>


    document.querySelector('.track').onclick = function() {
        localStorage.setItem("name", $('ol a').attr('data-src'));
        localStorage.getItem('name');
    };


    $(function () {
        // Setup the player to autoplay the next track
        var a = audiojs.createAll({
            trackEnded: function () {
                var next = $('ol li.playing').next();
                if (!next.length) next = $('ol li').first();
                // next.addClass('playing').siblings().removeClass('playing');
                // audio.load($('a', next).attr('data-src'));
                // audio.play();
                audio.play();
            }
        });

        // Load in the first track
        var audio = a[0];
        first = $('ol a').attr('data-src');
        $('ol li').first().addClass('playing');
        audio.load(first);
        audio.play();

        // Load in a track on click
        $('ol li').click(function (e) {
            e.preventDefault();
            $(this).addClass('playing').siblings().removeClass('playing');
            audio.load($('a', this).attr('data-src'));
            audio.play();
        });


        // Pause audio 
        $('.pause').click(function (e) {
            audio.pause();
        });



    });


</script>

Rails render partial with progress bar

I'm running Rails 4 and am trying to use a bootstrap form wizard. The thing about the form wizard is that not all of its tabs should be displayed at all times.

The form wizard is in a partial that I render via $("#tab3").html("<%= j(render partial: 'wizard' ) %>"); in update_forms.js.erb (called via an ajax call).

Everything works well in this except the progress bar doesn't display (it is 0) unless I refresh the page. Any thoughts on how I can set the progress bar when rendering the partial?

Countdown timer with socket.io not working with setInterval function

As the title says, iam building a countdown timer in nodejs with socket.io. But the socket.io function inside the setinterval function is not working.

Heres code:

var app = require('express')();
var http = require('http').Server(app);;
var io = require('socket.io')(http);
io.on('connection',function(socket){
  console.log("a user connected");
  var min = 3;
  var sec = 00;
  var time = new Object;
  function timer()
  {
   
    if(sec == 00)
    {
      min = min-1;
      sec = 60;
    }
    if(min == 0)
      {return;}
    sec = sec-1;
    time = {'min':min,'sec':sec};
    console.log("timer working"); //this is working without any problem
    socket.emit('time',"time");
    console.log("after socket working"); // this also works
  }
var starttime = setInterval(timer,1000);
if(min == 0)
{
  clearInterval(starttime);
}

Javascript show select box based on output

I want to have a select box that shows the available hours on the day based on the date selected. I've made the code that does that but it shows both select boxes when someone changes the date. Need to set it up so it doesn't shows only the select box for the date. http://ift.tt/1HnN39V here's the code.

    <script type="text/javascript">
        $('#date').change(function(){
            var test = $("#date").val();
            if (test) {
                $('#time').each(function(){
                $(this).addClass('hidden');
                });
                test = '.'+test.replace('/','_');
                test = test.replace('/','_');
                $(test).removeClass('hidden');
            };
        });



        // When the document is ready
                var availableDates = ["9-6-2015","14-6-2015","15-6-2015"];

    function available(date) {
      dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
      if ($.inArray(dmy, availableDates) != -1) {
        return [true, "","Available"];
      } else {
        return [false,"","unAvailable"];
      }
    }

    $('#date').datepicker({ beforeShowDay: available });


    </script>

angular - using element replace with in directive not removing previous element on update

In my directive i am using custom template. for that reason and my style purpose i am using element.replaceWith() - it works.

But when i update the collection the old elements and the data still exist. In case if i remove the element.replaceWidth() method it all works fine.

How can i use element.replaceWith() in the directive as well update the new collection?

code snippet:

  element.html(getTemplate(scope.value, scope.index));
  $compile(element.contents())(scope);
  element.replaceWith(element.contents()); //using this old elements exist.

In my demo, please click on next button to load new collection.

Demo

php Random variable countdown limited in time

I am writing a randomized countdown that show number of products left in promotion alongside a timer. Number of products left is stored in the database, so all users see the same number. I am using simple php/ajax/javascript solution. My problem is with distributing the random sales so all fit within limited timer and are nicely distributed.

Here is code I have so far:

function start() {
    $date= new DateTime();
    $prod_left = getval("SELECT * FROM counter LIMIT 1");
    if ( $prod_left == 20 ) {
        $fp = fopen("../index.html", "r+");
        while($buf = fgets($fp)){
            if(preg_match("/<!--(.|\s)*?-->/", $buf)){
                fputs($fp, '<script type="text/javascript">$(document).ready(function() {$(".countdown").circularCountdown({startDate:"' . $date->format('Y/m/d H:i:s') . '",endDate:"' . $date->modify("+5minutes")->format('Y/m/d H:i:s') . '",timeZone:+2});});</script></body></html>');
            }
        }
        fclose($fp);
        sleep(30);
        while ($prod_left > 0) {
            if (rand(0,4) > 2) {
                $prod_left--;
                sleep(rand(1,13));
                updateval($prod_left);
            }
        }

    } else {
        echo 'Promocja w trakcie lub zakończona, zresetuj zegar, jeżeli chcesz rozpocząć ponownie';
    }
    exit;
}

My assumption here is: 50% of time decrease timer and wait on average 6.5 seconds, which should on average give me 260 seconds for full sale. Unfortunately its very unevenly distributed. My goal is to have the $prod_value down to 0 not later than 270seconds after loop start, with quite evenly distributed value decreases (can accelerate towards ending) Will you be able to help?

Implementation doesnt need to be in any particular programing language, im just looking for a clue/concept I can follow to achieve this.

What is the strangest, the $prod_left value not always goes to 0, on sime iterations it just sits at 3 or 5.

Please help!

Changing width of autocomplete field and dropdown make them go in two different directions

I'm using Google's auto complete API. I'm also using a JQuery which animates the autocomplete field making it wider. However, the dropdown is not being positioned correctly when i have float right on the autocomplete field.

To test this type a letter then move the focus away from the field, then focus on the field again, you will see that the field and the dropdown get wider, but in 2 different directions.

(Note: it works with float:left, but I want to use float right for this)

<!DOCTYPE html>

<html>

  <head>

    <title>Place Autocomplete Form</title>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">

    <meta charset="utf-8">

    <link type="text/css" rel="stylesheet" href="http://ift.tt/1fgkMjW">

    <script src="http://ift.tt/1LzLlDy"></script>

    <script src="http://ift.tt/eSWUvL" type="text/javascript"></script>

    <script>

        function initialize() {

          autocomplete = new google.maps.places.Autocomplete(
          /** @type {HTMLInputElement} */(document.getElementById('autocomplete')));

          $('#autocomplete').focus(function() {

            $(this).attr('data-default', $(this).width());
            $(this).animate({ width: 315 }, 'slow');
            $('.pac-container').animate({ width: 315 }, 'slow');

        }).blur(function() {

            var w = 150;
            $(this).animate({ width: w }, 'slow');
            $('.pac-container').animate({ width: w }, 'slow');

        });

        }

    </script>

    <style>

      #autocomplete {
        position: absolute;
        top: 0px;
        margin-right:300px;
        right: 0px;
        width: 150px;
        float:right;
      }

    </style>

  </head>

  <body onload="initialize()">

    <div id="locationField">

      <input id="autocomplete" placeholder="Enter your address" 
      onFocus="geolocate()" type="text"></input>

    </div>

  </body>

</html>

Upload events to javascript datepicker from mySQLi table

I am trying to upload events from a mySQLi database to a jQuery datepicker. For example, if my team had a game on June 28, I want the user to be able to click on the datepicker and to have a popup show up saying who the team is playing on that date.

Here is my javascript for the datepicker:

<link href="CSS/jquery-ui.css" rel="stylesheet" />      
<script src="Scripts/jquery.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<!-- Javascript -->
<script>
    var events = new Array();
    <?php echo "events = ".$js_array. ";\n";?>

        /*var events = [ 
              { Title: "Five K for charity", Date: new Date("06/30/2015") }, 
              { Title: "Dinner", Date: new Date("07/01/2015") }, 
              { Title: "Meeting with manager", Date: new Date("07/02/2015") }
         ];*/
         $(function() {
             $( "#datepicker" ).datepicker({
                 beforeShowDay: function(date) {
                     var result = [true, '', null];
                     var matching = $.grep(events, function(event) {
                         return event.Date.valueOf() === date.valueOf();
                     });

                     if (matching.length) {
                         result = [true, 'highlight', null];
                     }
                     return result;
                 },
                 onSelect: function(dateText) {
                     var date,
                     selectedDate = new Date(dateText),
                     i = 0,
                     event = null;

                     while (i < events.length && !event) {
                         date = events[i].Date;

                         if (selectedDate.valueOf() === date.valueOf()) {
                             event = events[i];
                         }
                         i++;
                     }
                     if (event) {
                         alert(event.Title);
                     }
                 }
            });

And the accompanying php:

<?php 
    session_start();
    if(isset($_SESSION["userid"])) {    
        mysqli_select_db($con, "fundraising") or die("could not find db");
        $queryGame = "SELECT Date, Event FROM schedule_test WHERE EventID 
        BETWEEN 1 AND 20" or die("the query don’t work!");
        $gamer=$con->query($queryGame);

        if(!$gamer){
            $count=0;
        } else {
            $count = mysqli_num_rows($gamer);
            echo $count;
        }
        if ($count==0){
            echo("something went wrong");
        } else {
            $gamesArr = array();
            $i=0;
            while($row = mysqli_fetch_array($gamer)) {
                $arr[$i]['Title'] = $row['Date'];
                $arr[$i]['Date'] = $row['Event'];

                ++$i;       
            }
            $js_array = json_encode($gamesArr); 
        }
    } else {
        header('Location: indexv2.php');    
    }
?>

As you can see, there is an events array in the javascript that is commented out. When events are directly placed in the code, it works just fine and the alert comes up, but I want an administrator to be able to upload a schedule to the database and then have the calendar automatically load with that schedule.

I tried the json_encode() to convert the php array to javascript, but either it is not functioning or there is a bad race condition occuring such that the events array is undefined when the script runs.

Does anyone have a good solution to this? Or a better way to do it? Really appreciate your help.

how to alert multiple input file values in javascript

i have a file input field . In that user can choose multiple files for uploading. For that purpose i want to alert and check values which is retrieving correctly .

And i using Form-data to get values . is it possible to alert Form-data values

Thanks in advance

Raphaeljs image change color

I'm using Raphael.js to manipulate svg...

I have a folder with many svgs, and when the user choose one svg, the element paper.image of the raphaeljs load this svg on the "div svg selected"... Ok, this works fine, but the second step is the user change the color of this svg... Maybe the second steps doesn't worked for me because the image tag doesn't accepts fill or stroke (correct?). I've looked on the documentation a way to place on a sgv tag or object but not worked... Someone can help me? I need to change the color of a SVG generated with Adobe illustrator. If somebody knows other library or how can I change the color on pure javascript... Any help will be very appreciated!

var corEscolhida ='';
var group =drawing.set();
var text = null, imagemBadge=null;

$(document).ready(function() {
    try{
       var drawing = Raphael( "drawing");
       text = drawing.text(280, 140, "Hello Word")
            .attr({
                'fill': "#040404",
                'font-size':'50px',
                'font-family':   FontLike();
             });
        group.push(text );
        imagemBadge=drawing.image(getBadger(), 100, 100, 100, 100);
        group.push(imagemBadge );
     }catch(err){
         console.log(err);
     }
 });
 $("[name='cores']").click(function () {
    corEscolhida = $(this).css('background-color');
    text.attr("fill", corEscolhida);//it's work

    imagemBadge.attr('stroke', corEscolhida);
    imagemBadge.attr('fill', corEscolhida);
 ![enter image description here][1]});

Auto Refresh a div using jQuery

I need to auto refresh a specific div, i tried the following code but it make a lot of requests to the server instead of one every 5 seconds.

<script type="text/javascript">
        $(document).ready(function() {
            refresh();
        });

        function refresh() {
            $.get('site', function(result) {
                $('#div').html(result);
            });
            setTimeout('refresh()', 5000);
        }

    </script>

Why isn't my js script loading in WordPress

I am trying to add a bootstrap js script to my WordPress theme the "right" way but i'm not seeing a link to the js file in the head section of the webpage when it loads. Iv'e tried adding it to the header of the WordPress theme the "right" way but no luck. Not i'm trying in the functions.php file and still no luck. Please help!

function buns_bootstrap_run(){


        wp_register_script('bootstrap-js', get_stylesheet_directory() . '/js/bootstrap.min.js', array('jquery'),'3.2.0', false);

        wp_enqueue_script('bootstrap-js');

        }

    add_action('wp_enqueue_script', 'buns_bootstrap_run');

angularjs hogging my CPU [on hold]

I have a web app using angularjs (I am new to it) and jquery, when I click button the first time, it runs fine (browser doesn't appear to be very slow), when I click it the second time, the google chrome browser seems to be very busy. The strange thing is profiling doesn't show any user function. Here is the snapshot:

enter image description here

Not sure what could be the cause. Any ideas? Thanks.

JQuery not working in seperate .js file

I'm having an issue with my JQuery code.

When I add this code in script tags on my HTML file, it will work, however when I place it in a separate js file, it will not work. I know it's not an issue with referencing the correct file name and location.

Here is my code:

//Populate date select options
var num = [i];
var by = '<option value="2009">2009</option>'
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var lst = "";
var lst1 = "";
var lst2 = "";
var i;
for (i = 1; i <= 12; i++) {
    lst = lst + '<option value="' + i + '">' + months[i-1] + '</option>';
} 
for (i = 1; i <= 31; i++) {
    num.push(i);
    lst1 = lst1 + '<option value="' + i + '">' + num[i] + '</option>';
}
for (i = 10; i <= 30; i++) {
    num.push(i);
    lst2 = lst2 + '<option value="20' + i + '">20' + num[i] + '</option>';
}
$(document).ready(function(){
    $("#month").html(lst);
});
$(document).ready(function(){
    $("#day").html(lst1);
});
$(document).ready(function(){
    $("#year").html(by + lst2);
});

Thanks for reading!

How Get an array by JSon and how i can set this return value to a modal form?

My Ajax code is

$("a#edit").click(function(){
      var id = $(this).closest('tr').attr('id');
        //alert(id);
$.ajax({
        url: 'getdata.php',
        type: "POST",
        dataType:'JSON',
        data: {
            id: id,
        },
        success:function(result){
            alert(result);
        }
      });
    });

My php code is here...

if ($_REQUEST['id'] != "") 
{
     $id=$_REQUEST['id'];
   $sql = "select * from visit_reports WHERE visit_planner_id='$id'";

        $query = sqlsrv_query( $link, $sql);
        while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
            {
              print_r($data);
      }  
  }

In firebug the array i get ..

Array
(
[id] => 1.0000
[visit_planner_id] => 230338
[bi_staff_present_name] => BI staff present name
[bi_staff_trial_function] => BI staff trial function
)

Now how i can use this array value into my specific input field of modal form ?

jQuery mobile pop up adding &ui-state=dialog at the end of url

I was using this sample code from jquery mobile demo page example.

<a href="#popupMenu" data-rel="popup" data-transition="slideup" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-icon-gear ui-btn-icon-left ui-btn-a">Actions...</a>
<div data-role="popup" id="popupMenu" data-theme="b">
        <ul data-role="listview" data-inset="true" style="min-width:210px;">
            <li data-role="list-divider">Choose an action</li>
            <li><a href="#">View details</a></li>
            <li><a href="#">Edit</a></li>
        </ul>
</div>

I i run this sample in jquery mobile site it works well but if i run it in my local system &ui-state=dialog is appended to the window url.

Asp.net MVC Loading Parent View from the actionlink of PartialView using Ajax not working

I have a situation where I need to call ParentView from its partial view. Like I have list of ToDos in Partial view where Ajax actionlink is used to edit the data in parent by passing its id. The same is working without using Ajax as it is manipulating url by putting querystring. But we would like to have internal call with Ajax which is not firing.

The code we are using is like that:

<li>@Ajax.ActionLink(@item.ToDoTitle, "Index", new { tdid = @item.ToDoId }, new AjaxOptions { UpdateTargetId = "saved", InsertionMode = InsertionMode.Replace, HttpMethod="POST" })</li>

and controller is like that:

public ActionResult Index(int tdid =0)
    {
        if (tdid !=0)
        {
            ToDo t = new ToDo();
            t.ToDoTitle = "Ramlal";
            t.ToDoDesc = "Shyamlal";
            t.ToDoId = tdid;
            return Json(t);
        }
        else
        {
            return View();
        }
    }

Passing File path to MVC controller from View with Ajax J query return null

I'm trying to upload a image using MVC 5 and Ajax Jquery (asynchronously) but value of image variable always return null,

i already checked some previous stack overflow posts regarding this issue but i could not find my mistake, can anyone help me,

please help,,

Model Class

 public class TravelCategoryCustom
        {
            public int categoryId { get; set; }
            public string categoryName { get; set; }
            public string categoryDescriprion { get; set; }
            public HttpPostedFileBase image { get; set; }
            public int TotalPlaces { get; set; }
        }

View

<form enctype="multipart/form-data">
                <div class="form-group">
                    <label>Category Name</label>
                    @Html.TextBoxFor(model => model.categoryName, new { @class = "form-control" })

                </div>
                <div class="form-group">
                    <label>Category Description</label>
                    @Html.TextAreaFor(model => model.categoryDescriprion, 5, 1, new { @class = "form-control " })
                </div>
                <div class="form-group">
                    <label>Category Image</label>
                     <input type="file" id="dialog" />
                </div>

                <input type="button" value="Create" id="submtt" class="btn btn-primary" onclick="favfunct()" />

            </form>   

Script

<script>
    function favfunct() {
    $.ajax({
  var formData = new FormData($('form')[0]);
        url: "/MVCTravelCategories/Create",
        dataType: "json",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ trvlcategory: { categoryId: '1', categoryName: 'testName', categoryDescriprion: 'TestDec', image: formData , TotalPlaces: '3' } }),
        async: true,
        processData: false,
        cache: false,
        success: function (data) {
            alert(data);
        },
        error: function (xhr) {
            alert('error');
        }
    });
    }
</script>

Action Result (image) http://ift.tt/1ebUc1m

jquery, click on class not working when page loads from .load [duplicate]

This question already has an answer here:

If I execute this from a single page (all the code on the same page) it works as expected... However, I want to have the "filter" code in a seperate file, so I can reuse it on other pages....

THIS WORKS (the code that errors is below)

<!DOCTYPE html><html lang="en" ><head></head><body>

<table class="table table-bordered table-condensed"  >
    <tr>
        <td><a class="alphaFilterLink" data="A" >A</a></td>
        <td><a class="alphaFilterLink" data="B" >B</a></td>
        <td><a class="alphaFilterLink" data="C" >C</a></td>
        <td><a class="alphaFilterLink" data="D" >D</a></td>
    </tr>
</table>

</body></html>

<!-- script references -->
<script src="resources/js/jquery.min.js" ></script>
<script src="resources/js/bootstrap.min.js" ></script>

<script>        
    // Filter By Letter
    $( '.alphaFilterLink' ).click( function() {
        var x = $( this ).attr( 'data' );
        alert( 'we are responding to the click of a alphaFilterLink ' + x );
    });
</script>

THIS DOES NOT WORK: (and nothing shows in console)

<!DOCTYPE html><html lang="en" ><head></head><body>

<div id="filter"></div>

</body></html>

<!-- script references -->
<script src="resources/js/jquery.min.js" ></script>
<script src="resources/js/bootstrap.min.js" ></script>

<script>
    $( '#filter' ).load( 'templates/filter.html', function( response, status, xhr ) {
        $( '#filter' ).slideDown( 3000 ).fadeIn( 1000 ); // slide it down
        if ( status == 'error' ) {
            var msg = 'Sorry but there was an error loading the filter page: ';
            $( '#filter' ).html( msg + xhr.status + ' ' + xhr.statusText );
        }
    });

    // Filter By Letter
    $( '.alphaFilterLink' ).click( function() {
        var x = $( this ).attr( 'data' );
        alert( 'we are responding to the click of a alphaFilterLink ' + x );
    });
</script>

templates/filter.html

<table class="table table-bordered table-condensed"  >
    <tr>
        <td><a class="alphaFilterLink" data="A" >A</a></td>
        <td><a class="alphaFilterLink" data="B" >B</a></td>
        <td><a class="alphaFilterLink" data="C" >C</a></td>
        <td><a class="alphaFilterLink" data="D" >D</a></td>
    </tr>
</table>

JQuery: RangeError maximum call stack exceeded

I have an on change event that fires when a select box is changed. The select box, however, is located inside a div that is replaced and thus the select box is regenerated. Since this error can result from an endless loop, I'm guessing my trigger event must also fire when the select box is created. I have tried many things with no success.

Does anyone know how I can prevent this event from triggering on creation and only when the portion is manually changed?

Login failed in my code after inserting proper login details (i.e username and password), code in php and jquery

I have following code (php and jquery) for Login for Student and Teacher (using same form for both access). In my system the admin can create Student and Teacher. Once created, the details are saved into database. The saved details is suppose to be use for login to their admin panel. But, the problem is , when Student or Teacher wants to login with the login details, provided by the admin (which has already been saved in database table), It display error message : Login Failed, Please check your username and password. (Same details, saved into database table is used for login process). This aching my head. If someone can tell me , if there is some error in my code, will be much appreciated.

login_form.php

<form id="login_form1" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Sign in</h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button data-placement="right" title="Click Here to Sign In" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-signin icon-large"></i> Sign in</button>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').tooltip('show');
$('#signin').tooltip('hide');
});
</script>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#login_form1").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true_teacher')
{
$.jGrowl("Loading File Please Wait......", { sticky: true });
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'dasboard_teacher.php'  }, delay);  
}else if (html == 'true'){
$.jGrowl("Welcome to Soch College's E- Learning Management System", { header: 'Access Granted' });
var delay = 1000;
setTimeout(function(){ window.location = 'student_notification.php'  }, delay); 
}else
{
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
});
</script>

login.php

<?php include('admin/dbcon.php');
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//for student login
$query_student = mysql_query("SELECT * FROM student WHERE username='$username' AND password='$password'");
$count_stu = mysql_num_rows($query_student);
$row_stu = mysql_fetch_array($query_student);
//for teacher login
$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
$count_tea = mysql_num_rows($query_teacher);
$row_tea = mysql_fetch_array($query_teacher);
if( $count_stu > 0 ) { 
$_SESSION['id']=$row_student['student_id'];
echo 'true';
}else if( $count_tea > 0 ) { 
$_SESSION['id']=$row_teacher['teacher_id'];
echo 'true_teacher';
}
else{ 
}?>

AngularJS RangeError: Maximum call stack size exceeded using directive with Jquery

By using this directive:

.directive("materialSelect", ["$compile", "$timeout", function ($compile, $timeout) {
        return {
            link: function (scope, element, attrs) {
                if (element.is("select")) {
                    $compile(element.contents())(scope);
                    $timeout(function () {
                        element.material_select();
                    });
                    if (attrs.ngModel) {
                        scope.$watch(attrs.ngModel, function() {
                            element.material_select();
                        });
                    }
                }
            }
        }
    }]);

This is my module :

'use strict';

angular.module('sputnikApp.view1', ['ngRoute','ui.materialize.material_select'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/view1', {
            templateUrl: 'view1/view1.html',
            controller: 'View1Ctrl'
        });
    }])

    .controller('View1Ctrl', ['$scope', function ($scope) {
        $scope.priorityChoices = [
            {value: 1, name: "Very high"},
            {value: 2, name: "High"},
            {value: 3, name: "Normal"},
            {value: 4, name: "Low"},
            {value: 5, name: "Very low"}
        ];

        $scope.myChoice = $scope.priorityChoices[2];

    }]);

This HTML in my view:

<select  id="priority" ng-model="myChoice" ng-options="p.value as p.name for p in priorityChoices track by p.value" material-select></select>

I'm getting this error:

RangeError: Maximum call stack size exceeded
    at HTMLOptionElement.n.event.dispatch (jquery.js:4403)
    at HTMLOptionElement.n.event.add.r.handle (jquery.js:4121)
    at Object.n.event.trigger (jquery.js:4350)
    at n.fn.extend.triggerHandler (jquery.js:4907)
    at Function.jQuery.cleanData (angular.js:1738)
    at n.fn.extend.remove (jquery.js:5258)
    at ngOptionsDirective.link.removeUnknownOption (angular.js:26105)
    at writeNgOptionsValue [as writeValue] (angular.js:26117)
    at selectDirective.link.ngModelCtrl.$render (angular.js:28054)
    at HTMLOptionElement.<anonymous> (angular.js:28173)

The directive comes from there.

This is the order in which my script are in index.html

<script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="bower_components/materialize/dist/js/materialize.js"></script>
<script type="text/javascript" src="bower_components/angular-materialize/src/angular-materialize.js"></script>

<script type="text/javascript" src="sputnikApp.js"></script>
<script type="text/javascript" src="view1/view1.js"></script>

JQuery Version is : 2.1.4 Angular Version is : 1.4.1

I have tried reordering the JavaScript, no putting the dependency in my module, coping the directive in my own code. I'm kinda new to this AngularJS business

JQuery Button Data Returning As Null?

I have a button and when I click it, I want the html object (aka button) to be passed as a parameter to another javascript function. I want the javascript function to print the data-hi from the element in the button.

HTML BUTTON

<button type = "button" onclick = "whoIsRdns(this)" class="dns-information btn btn-xs btn-info pull-right" data-toggle="modal" data-target = "#whois_rdns_modal" data-path="{{ path( '_who_is_rdns', { 'peer': peer.number, 'ip': peer.mac } ) }}" data-hi = "hi2">
<i class="icon-search"></i>
</button>

JS FUNCTION(W/ JQUERY)

    function whoIsRdns(thisButton){

    //Enable jQuery properties from the param of the HTML object
        var btn = $(thisButton);

        var test = btn.data('hi');
        console.log('Value is ' + test);

}

Why would test return as null?

Gravity Forms - Date Picker - Disallow End Date to be before Start Date

basically I have a large form created on my WordPress site using Gravity Forms. One section of my forms has a bunch of items listed with a 'Start Date' followed by an 'End Date' -- Example:

Item | Start Date | End Date

Item#1 | 05/01/2015 | 05/25/2015

What I am after is making it so I can disallow the 'End Date' from being before the selected 'Start Date'. It would be best if the user was unable to even select the date from the date picker drop down, but if it has to be an error that pops up on submission, that is fine to. I have been researching this for hours and I am just too noob to know exactly what to do. Thanks for any and all help!

jquery call javascript and change page issue

My html page have two div which data-role="page", one id is pageone to collect user information, one id is pageresult to display a calculation result of the user information. I use a button to call the javascript function to calculate the information and to show the pageresult,

<a data-role="button" href="#pageresult" id="btnTry">Try</a>

but when I click the button ,the javascript called well , I debug and confirm it .but the pageresult just show one second then the page change back to the pageone, and the url of the browser has been changed to : http://localhost:8080/my_project/JqueryPage/mypage.html#pageresult if I refresh the browser manually, the page will become the pageresult again. Here is the js function I call when click the button:

    $('#btnTry').click(function() {
        var var1 =  $("#selIsHasSpeed").val() ==""?"false":$("#selIsHasSpeed").val();
        var var2 =  $("#selIsWashSpeed").val() == ""?"false":$("#selIsWashSpeed").val();
        //some calculate process 
        var paragraphs = $('div#resultList p');
        paragraphs[0].innerHTML = Wdamage;
        paragraphs[1].innerHTML= Cdamage;
        showResultPage();
    catch(e){
        alert(e);}
    });
    });

the showResultPage() function :

    function showResultPage(xmlHttpRequest, status){
    setTimeout(function() {
        $.mobile.changePage("#pageresult", {
            'allowSamePageTransition' : true,
            'reloadPage' : true,
            'transition' : 'none'
        });
    }, 1);
    }

also I want change the result in the pageresult , when the pagerusult show a second first when I click the the result has been changed by the js . But when I manually refresh the page the result has not been changed it seems a old page!