Replaced div is not working Jquery Mobile - jquery-mobile

Basically I replaced the div in the content as soon as I click "Delete" on the Setting menu above. Well it does changes from collapsible set into checkbox with footer below containing two buttons. The buttons are delete and cancel but I can't perform anything with those buttons. For example, If Cancel clicked it should pop the alert popup (For the sake of testing). Please help..
<div data-role="content">
Tambah Katagori
<div id="Outcome" data-role="collapsibleset" data-theme="a" data-content-theme="a" data-collapsed-icon="arrow-r" data-expanded-icon="arrow-d"></div>
</div>
$("#Delete").click(function(){
$("#Outcome").replaceWith('<form><fieldset data-role="controlgroup" id="OutcometoDelete">');
db.transaction (function (transaction)
{
var sql = "SELECT * FROM KatagoriPengeluaran";
transaction.executeSql (sql,[],
function (transaction, result)
{
if (result.rows.length)
{
for(var i = 0; i< result.rows.length; i++ ) {
All2 =result.rows.item(i);
element = $(' <input type="checkbox" name="'+All2.Katagori+'" id="'+All2.Katagori+'"><label for="'+All2.Katagori+'">'+All2.Katagori+'</label>').appendTo($('#OutcometoDelete'));
}
All2 =result.rows.item((result.rows.length-1));
$('#'+All2.Katagori).append('</form></fieldset>');
$("#OutcometoDelete").append('<div id="someFooter" data-role="footer" data-position="fixed"><div id ="navbarFooter" data-role="navbar"><ul><li><a data-role="button" href="#popUpDelete">Delete</a></li><li><a data-role="button" href="index.html#Pengeluaran" data-ajax="false" id="cancelDelete" >Cancel</a></li></ul></div></div>');
$("#OutcometoDelete").trigger('create');
$("#someFooter").trigger('pagecreate');
$('#navbarFooter').trigger('pagecreate');
}
else
{
alert ("Retrieval Error");
}
}, error);
});
});
$("#cancelDelete").click(function(){
alert("oi");
});

This is because your way of event binding will not work for future elements. You can't just bind click event and expect it will work in the future, event(s) must be bind to something inside the DOM.
So this code will not work:
$("#cancelDelete").click(function(){
alert("oi");
});
On the other hand this code will work:
$(document).on('click',"#cancelDelete",function(){
alert("oi");
});
Second code will work because event is bind to document and it will propagate as soon as needed element is part of the DOM and appropriate event is trigger on it. This is also called delegated event binding.

Related

DirtyForms does not work properly with $.blockUI

I'm using DirtyForms and $.blockUI plugin, the latter to change pages when clicking on links (in my app, some pages take a couple of seconds more to load and a visual feedback is fine).
When I change field content and then click any link, DirtyForms is triggered: but when I cancel the process to stay on the page, $.blockUI starts its game, resulting in a stuck page
$('form[method="post"]').dirtyForms();
$('a').on('click', function(){
$.blockUI();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
Please, any solution?
EDIT: I also tried with stay.dirtyforms and afterstay.dirtyforms events, but they have no effect. defer.dirtyforms seems to work but the event is triggered twice (I put a console.log() to check) and I am not sure this is the way to go...
I've edit my answer: I've added some line of code to disable first the onbeforeunload dialog alert, taken from here. And at the end a link to an answer with another idea you can try.
My idea: you have to prevent the default link action and use the $.blockUI Modal Dialogs methods to open a custom dialog, then catch the link attribute href from the link put it inside a variable and use the variable value for the #yes button of the dialog.
See if this solution can meet your needs
/* beforeunload bind and unbind taken from https://gist.github.com/woss/3c2296d9e67e9b91292d */
// call this to restore 'onbeforeunload'
var windowReloadBind = function(message) {
window.onbeforeunload = function(event) {
if (message.length === 0) {
message = '';
};
if (typeof event == 'undefined') {
event = window.event;
};
if (event) {
event.returnValue = message;
};
return message;
}
};
// call this to prevent 'onbeforeunload' dialog
var windowReloadUnBind = function() {
window.onbeforeunload = function() {
return null;
};
};
var linkToFollow; // href to follow
$('form[method="post"]').dirtyForms();
$('a').on('click', function(e){
e.preventDefault();
windowReloadUnBind(); // prevent dialog
$.blockUI({ message: $('#question'), css: { width: '275px' } });
linkToFollow = $(this).attr('href');
});
$('#no').click(function() {
$.unblockUI();
return false;
});
$('#yes').click(function() {
$(window.location).attr('href', linkToFollow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js"></script>
<p>Change the field content to activate DirtyForms, then click on the link.<br>
When the popup appears, click on "cancel" to stay on the page.<br>
Watch blockUI getting fired as the link is going to be followed</p>
<form action="#" method="post">
<input type="text" name="username" required>
<button type="submit">send</button>
</form>
click me after changing field content
<div id="question" style="display:none; cursor: default">
<h6>Would you like to contine?.</h6>
<input type="button" id="yes" value="Yes" />
<input type="button" id="no" value="No" />
</div>
Other idea taken from another answer: Other idea would be to make a simple jQuery.ajax({}) call before return value in beforeunload as seen in this answer

Content of <div> not updating

I've got a div element which I am using as a popup which does not update itself. I'll use the picture below to explain:
When I click on each row in the grid, the right hand side updates to show the details, part of which is a potentially lengthy Note field. The button View Note triggers a popup with the full text inside. Here, I have previously selected Donor 2000000, which displayed the correct note. However, when I select another Donor(2000002 as highlighted) the information in the popup retains the info for the first selected Donor. So, essentially it sets it once and then does not update.
The (partial) code for the main View is:
<div class="col-md-4 col-md-push-8">
<h4>
Donor Details
</h4>
<div id="donor-details">
<p class="muted">
Select donor to display detailed infomation
</p>
</div>
</div>
<div class="col-md-8 col-md-pull-4">
#Html.Action("DonorSummaryGrid") #* configure grid in a partial view *#
</div>
</div>
<script>
$(function () {
pageGrids.donorSummaryGrid.onRowSelect(function (e) {
$.post("/Donor/GetDonorDetails?donorId=" + e.row.DonorId, function (data) {
if (data.Status <= 0) {
alert(data.Message);
return;
}
$("#donor-details").html(data.Content);
});
});
});
</script>
The code for the partial view - which contains the details - is:
#if (!String.IsNullOrWhiteSpace(Model.CurrentNoteText)) {
<div id="note-dialog" title="Note for Donor #Model.DonorId">
<p>#Html.DisplayTextFor(model => model.CurrentNoteText)</p>
</div>
<br />
}
#Scripts.Render("~/Scripts/NoteDialogue.js")
When I debug, the value of Model.CurrentNoteText and #Model.DonorId do reflect the correct data.
NoteDialogue.js is:
$(function() {
$("#note-dialog").dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "blind",
duration: 200
}
});
$("#opener").click(function() {
$("#note-dialog").dialog("open");
});
});
I hope this is clear :)
Oh, there are no errors shown in the browser, and everthing functions as expected, except for updating the info in the popup.
I have tried
<script>
$("#note-dialog").html("#Model.CurrentNoteText");
</script>
with no success.
Got there in the end :)
Looking at the generated source, I noticed that the code for
<div id="note-dialog" title="Note for Donor #Model.DonorId">
<p>#Html.DisplayTextFor(model => model.CurrentNoteText)</p>
</div>
<br />
was being generated right at the bottom, outside all the other divs containing the grid and details. Looked something like this:
<div tabindex="-1" class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable" role="dialog" aria-describedby="note-dialog" aria-labelledby="ui-id-1"....>
As I clicked each row with a note in, an extra div was being generated, with the aria-labelledby attribute incrementing, e.g. "ui-id-2", "ui-id-3"...
The first generated div was being selected for the dialogue opening.
The solution was to remove the div on the row click event. Code now is:
$(function() {
pageGrids.donorSummaryGrid.onRowSelect(function (e) {
$("#note-dialog").remove();
$.post("/Donor/GetDonorDetails?donorId=" + e.row.DonorId, function(data) {
if (data.Status <= 0) {
alert(data.Message);
return;
}
$("#donor-details").html(data.Content);
});
});
});

jQueryMobile Change listview's item attributes dynamically

I want to change dynamically (click event) a data-theme of a list item in a jQueryMobile listview. Firebug shows me that the change is performed but the list is not refreshed. (If I add elements it works, but with attribute changes the list won't be refreshed.) For example I want to change the data-theme from c to f when the item is clicked.
I tried everything I read in this forum, from trigger('mouseout') over trigger('create') on parents to refreshing the whole page, but no effect at all, so I guess I am blind to see something obvious. Maybe somebody can give me a hint... :)
<script>
function fillList() {
var li = '<li data-theme="c">List item</li>';
$("#alist").empty().append(li).promise().done(function () {
$(this).off("click").on("click", ".info", function (e) {
e.stopImmediatePropagation();
e.preventDefault();
var theLiElem = $(this).closest('li');
theLiElem.attr('data-theme','f').trigger('mouseout');
theLiElem.trigger("create");
});
$(this).listview("refresh");
});
}
$(document).on("pageinit", "#info-page", function () {
fillList();
});
</script>
<div data-role="page" id="info-page">
<div data-role="content">
<ul data-role="listview" id="alist" data-inset="true">
</ul>
</div>
</div>
Kind regards,
Steve

Jquery-Mobile: How to add the data dynamically to the select menu based on the text box value

I am new to jquery mobile. In my UI, one text box and one select menu are there. Initially select menu is empty.If the textbox value is more than 1 then some data is added to the select menu otherwise select menu is empty. For this, i am calling the function at the onchange of select menu but it is not working. Please can anybody help me.
Edit:
Ex:
$('#Goal_Time').bind( "focus", function(event, ui)
{
if(Goal_WeightVar.val() > 0)
{
Goal_WtVar = Math.abs(weightVar.val() - Goal_WeightVar.val());
Min_DurationVar = Math.round(Goal_WtVar * 2.2);
for(var i=0;i<10;i++)
{
$('#Goal_Time').append('<option value=Min_DurationVar>Min_DurationVar</option>');
}
}
});
thanks
Well Kinda working example:
http://jsfiddle.net/v5DC3/5/
JS
$('#Goal_WeightVar').live('change', function() {
var weightVar = 0; // for testing only
var goalWeightVar = $('#Goal_WeightVar').val();
if(goalWeightVar > 0)
{
Goal_WtVar = Math.abs(weightVar - goalWeightVar);
Min_DurationVar = Math.round(Goal_WtVar * 2.2);
for(var i=0;i<10;i++)
{
$('#Goal_Time').append('<option value='+Min_DurationVar+'>'+Min_DurationVar+'</option>');
}
$('#Goal_Time').listview('refresh');
}
});
HTML
<div data-role="page" id="Goal_Time_Page">
<div data-role="content">
<label for="Goal_WeightVar">Goal Weight:</label>
<input type="text" name="Goal_WeightVar" id="Goal_WeightVar" value="" />
<label for="Goal_Time" class="select">Goal Time:</label>
<select name="Goal_Time" id="Goal_Time">
<!-- Add options here -->
</select>
</div>
</div>
You will need to tweak it
As it says in the docs of jQuery Mobile, you have to tell the select menu to update it's contents by calling $('select').selectmenu();
If it still doesn't work you'll have to post a little sample code so I can have a look at it.
Edit:
Actually, that's not even necessary. If you have an empty <select id="to-append"></select>, you can just add options via $('#to-append').append('<option value="a">A</option>')!
The onchange event of the select is probably not the right event to do this though. The select will not change as long as it's empty, thus your event will never get triggered. Try the blur event of the text box.
jQuery Mobile Docs - Select

jQuery add/remove css class on selected radio

I've read a few solutions on here, but my problem differs enough where those will not work. Basically if the radio button is checked, add a css class to the parent div. If the radio is not checked, remove the css class. Sounds simple?
I have more than one radio button group, so in other words, there will be multiple radio buttons selected at a time. Each radio button group also is on different parts of the page seperated by other html.
Here is what I came up with:
$(document).ready(function () {
$('input').click(function () {
if ($('input:not(:checked)')) {
$('div').removeClass('style1');
}
if ($('input').is(':checked')) {
$(this).parent().addClass('style1');
}
});
});
I think I'm on the right path with the input:not(:checked), but on the next line it removes style1 from all div elements instead of checking if other divs radio button child is checked.
I guess what I'm asking is how do I write a script that when a radio button is clicked, add a css class to the parent and then find all div tags on the page that have a child of input. If the divs child input is not checked, remove the css class. So if a div has a child input element and it is checked, don't remove the css class from the inputs div.
I hope that makes sense.
Why not using the following: http://jsfiddle.net/Q2bzT/
$(document).ready(function () {
$('input').click(function () {
$('input:not(:checked)').parent().removeClass("style1");
$('input:checked').parent().addClass("style1");
});
});​
Assuming your radio buttons utilize the name property to properly group them, when one changes, you can find the radios with the same name, and remove the class, then add the class to the one that was activated.
Try it out: http://jsfiddle.net/U2AAQ/
$(document).ready(function () {
$(':radio').change(function () {
$(':radio[name=' + this.name + ']').parent().removeClass('style1');
$(this).parent().addClass('style1');
});
});​
I had a similar issue but I needed to target the radio button's label instead of a parent div element. I also needed to make sure the other related label elements did not have the class.
Here's what I came up with based on #user113716's answer:
HTML
MVC code removed so there is only HTML in this example
<ol class="list-group">
<li class="list-group-item">
<div class="input-group">
<label for="choice_ChoiceId" class="form-control">ChoiceDescription</label>
<span class="input-group-addon">
<input type="radio" id="choice_ChoiceId" value="choiceValue" name="choiceName" required />
</span>
</div>
</li>
</ol>
jQuery
$(':radio').click(function () {
var _groupName = $(this).attr('name'),
_radioId = $(this).attr('id'),
_radioGroup = $(':radio[name="' + _groupName + '"]');
//remove class from all labels for this group of radio buttons
_radioGroup.each(function(){
$('label[for*="' + $(this).attr('id') + '"]').removeClass('style1');
});
//add the class to the selected radio button
$('label[for*="' + _radioId + '"]').addClass('style1');
});
JavaScript
'use strict';
var o = 'label.input-check, label.input-radio';
$(o).find('input').change(function () {
$(o).find('input').filter('input[name="' + (this).name + '"]').each(function () {
$(this).parent(o).toggleClass('checked', (this).checked);
});
}).trigger('change');
Demo: http://jsfiddle.net/3uwp9c2n/
Just optimize if you need.

Resources