Click Event on button in list not working - jquery-ui

<ul id="mylist">
<li id="1">1<button id="Button3">Delete</button> </li>
<li id="2">2<button id="Button2">Delete</button></li>
<li id="3">3<button id="another_entry">Save</button></li>
</ul>
I have the code as follows:
<script type="text/javascript">
$(document).ready(function() {
$("#mylist :button").live('click', function() {
var text = $(this).text();
if (text == "Delete") {
$(this).parent().remove();
}
else {
$(this).text("Delete");
}
});
$("#mylist li:last-child button").live('click', function() {
$(this).parent().append('<li>' + '<input type = "textbox">' + '<input type = "button" value= "Save">' + '</li>');
});
});
</script>
On clicking the button on the last list, it doesn`t add the new list, nor is the text on the save button changed as delete

You have to append the newly created li to ul and not to the parent of button which is li.
Change you code to
$(this).closest("#mylist").append('<li><input type = "textbox" /><button>Save</button></li>');

Related

How to create listview with buttons inside clickable list items in Jquery Mobile

Is there any way to create a listview in Jquery Mobile that has clickable list items and each item has 3 buttons? I don't want to use split-button listview. I have tried to create this but button clicks are not working. Clicking on any of the button behaves like clicking on list item.
You can add e.stopImmediatePropagation(); (http://api.jquery.com/event.stopimmediatepropagation/) to the button clicks so they will not propagate to the parent listitem.
UPDATE:
OP mentioned in comments that listitems are generated dynamically. The original code still works because event delegation (https://learn.jquery.com/events/event-delegation/) was used for the buttons. Here is an updated example:
Empty UL in markup
<ul data-role="listview" id="thelist">
</ul>
On pagecreate, fill the listview and add the click handlers
$(document).on("pagecreate", "#page1", function(){
//make list dynamically
var allItems = '';
for (var i=0; i< 4; i++){
allItems += '<li data-rowid="' + i + '"><div data-role="controlgroup" data-type="horizontal"><input type="button" value="Hmm" /><input type="button" value="No" /><input type="button" value="Yes" /></div> Item ' + i + ' text or description</li>';
}
$("#thelist").empty().append(allItems).listview("refresh").enhanceWithin();
$("#thelist").on("click", "li input", function(e){
e.stopImmediatePropagation();
var rowid = $(this).parents("li").data("rowid");
var btnText = $(this).val();
alert("You clicked the button: " + btnText + " on row number: " + rowid);
});
$("#thelist").on("click", "li a", function(e){
alert("You clicked the listitem");
});
});
Updated DEMO
ORIGINAL:
DEMO
<ul data-role="listview" id="thelist">
<li data-rowid="1">
<a href="#">
<div data-role="controlgroup" data-type="horizontal">
<input type="button" value="Hmm" />
<input type="button" value="No" />
<input type="button" value="Yes" />
</div>
Item 1 text or description
</a>
</li>
</ul>
$(document).on("pagecreate", "#page1", function(){
$("#thelist li").on("click", "input", function(e){
e.stopImmediatePropagation();
var rowid = $(this).parents("li").data("rowid");
var btnText = $(this).val();
alert("You clicked the button: " + btnText + " on row number: " + rowid);
});
$("#thelist li").on("click", "a", function(e){
alert("You clicked the listitem");
});
});
You could also put the buttons outside of the listitem anchor tag and use CSS to position everything nicely...

Adding events to button doesn't work with backbone

I read over 20 different articles and forum topics about that, tried different solutions but I didn't cope with it.
The following code doesn't work. I need someone's help...
LoginView.js
var LoginView = Backbone.View.extend({
//el: $('#page-login'),
initialize: function() {
_.bindAll(this, 'gotoLogin', 'render');
//this.render();
},
events: {
'click #button-login': 'gotoLogin'
},
gotoLogin : function(e){
e.preventDefault();
$('#signup-or-login').hide();
$('#login').show();
return true;
}
});
login.html
<div data-role="page" id="page-login">
<!-- SignUp or Login section-->
<div id="signup-or-login" data-theme="a">
<a data-role="button" data-theme="b" id="button-signup"> Sign Up </a>
<a data-role="button" data-theme="x" id="button-login"> Login </a>
</div>
<!-- Login section-->
<div id="login" data-theme="a">
<button data-theme="b"> Login </button>
<button data-theme="x"> Cancel </button>
</div>
</div>
The page is created in method of Backbone.Router extended class.
loadPage('login.html', new LoginView());
From what I understand, $.mobile.loadPage() grabs the desired html and attaches it to the DOM.
Currently, you're trying to set el after the View has been instantiated.
However, notice that Backbone.View attaches el and $el when it's instantiated:
var View = Backbone.View = function(options) {
...
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
Also notice that View.setElement() sets $el by passing a selector or a jQuery objected to View.el:
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
}
Bottom line:
You need to set el (in your case with the provided jQuery object) while instantiating it:
// Where `view` is a reference to the constructor, not an instantiated object
var loadPage = function(url, view) {
$.mobile.loadPage(url, true).done(function (absUrul, options, page) {
var v,
pageId = page.attr('id');
v = new view({
el: page
});
...
}
}
You now call loadPage() like so:
loadPage('login.html', LoginView);
This gives Backbone.View the $el which to delegate your events.

Listview style issue when changing the page

I'm working on a single page application using jquery mobile along with knockout.js binding on MVC4 platform..
This is my button on the main div page:
<div data-role="page" id="pageMain">
<div data-role="content">
View Invoices
</div>
</div>
This is my target div page:
<div data-role="page" id="pageExisting">
<div data-role="header">
<h1>Existing Invoices's</h1>
<a data-rel="back" data-role="button">Back</a>
</div>
<div class="choice_list" data-role="content" data-bind="visible: Headers().length > 0">
<ul id="headersList" data-role="listview" data-bind="foreach: Headers" data-filter-placeholder="Search Invoice" data-filter-theme="a" data-inset="true"
data-filter="true" data-theme="b">
<li>
<a href="#" data-inline="true">
<h2>Invoice No.: <span data-bind="text: inv_no"></span></h2>
<p>Amount.: <span data-bind="text: inv_amt"></span></p>
</a>
</ul>
</div>
</div>
Here is the script section:
var HeaderViewModel = function () {
//Make the self as 'this' reference
var self = this;
self.Headers = ko.observableArray([]);
function GetHeaders() {
//Ajax Call Get All Employee Records
// self.GetHeaders = function () {
$.ajax({
type: "GET",
url: "/api/InvAPI",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.Headers(data);
},
complete: function () {
$.mobile.changePage("#pageExisting");
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
}
self.GetHeader = function () {
GetHeaders();
}
};
$(document).ready(function () {
ko.applyBindings(new HeaderViewModel());
}
When I hit the button "view Invoices" I get a typical Jquery mobile formated listview
but the problem is when I hit the back button and navigate again to the "PageExisiting" div Page I get the list data with no styling..
When viewing page source in both cases, I noticed that on second navigation;
Li tags have not attributes.
I have tried some solutions like: listview refresh, page destroy, page create prior to the line:
$.mobile.changePage("#pageExisting");
with no luck.
I'm stuck here guys and I will appreciate your proposed solutions
Thanks
Refresh list view before showing the page.
$('#pageID').on('pagebeforeshow', function() {
$('[data-role=listview]').listview('refresh');
});

mobile css for radio button not applying in knock template binding

I have tried to use knockoutjs template binding to bind fieldsets dynamically which contain group of radio buttons. Here my problem is mobile radio button css not applying for radio buttons. I have searched in stackoverflow I have found issue for button but i didn't find for radio buttons. So can you please find me the solution
<script type="text/x-jquery-tmpl" id="MobileQuestionTemplate">
<div data-role="fieldcontain">
<div class="divborder">
<label id="l2" for="select-choice-1" class="questiontext" data-bind="text: QuestionText"></label>
<br />
<fieldset data-role="controlgroup" data-mini="true" align="center" data- bind="attr: { visible: QuestionType==13,id:QuestionID+'_fld'},template: {name:'MobileOptionTemplate', foreach: OptionList}"></fieldset>
</div>
</div>
</script>
<script type="text/x-jquery-tmpl" id="MobileOptionTemplate">
<input type="radio" data-bind="attr: {id:QuestionID+'_'+OptionID+'_rbt',val:OptionID,name: QuestionID+'_selectedObjects'}"/>
<label data-bind="text: OptionText ,attr: { for: QuestionID+'_'+OptionID+'_rbt'}" />
</script>
<table id="tblMobileMgrQuestions" data-bind="template: {name:'MobileQuestionTemplate', foreach: MobileManagerviewmodel.ManagerQuestions}">
</table>
Can you please tell me where I need to change the code in js to apply css
$.ajax(
{
url: "/Render/LoadSurveyManagerQuestions?surveyGuid=" + surveyGuid + "&surveyItemGuid=" + rsg,
success: function (result)
{
ko.bindingHandlers['button'] =
{
init: function (element, valueAccessor)
{
debugger;
$(element).button(ko.utils.unwrapObservable(valueAccessor()));
}
}
debugger;
var SurveyManagerQuestion = function (managerQuestions)
{
var Self = this;
Self.ManagerQuestions = ko.observableArray(managerQuestions);
Self.AssignQuestionAnswer = function (option)
{
ko.utils.arrayFirst(Self.ManagerQuestions(), function (question)
{
if (question.QuestionID == option.QuestionID)
{
question.OptionId = option.OptionID;
question.OptionText = option.OptionText;
}
});
};
Self.Save = function ()
{
alert('hi');
};
};
debugger;
MobileManagerviewmodel = new SurveyManagerQuestion(result);
ko.applyBindings(MobileManagerviewmodel, document.getElementById("tblMobileMgrQuestions"));
}
});
Thanks for any help in advance.
To enhance the markup of radio buttons dynamically, use the below.
$('input[type=radio]').checkboxradio().trigger('create')

UI jQuery Tabs - Create More than One Link to Tabs within Tabs on Same Page

My code so far:
$(function(){
$( "#tabs" ).tabs().find( ".ui-tabs-nav" ).sortable({ axis: "x" });
$(document).ready(function() {
var $tabs = $("#tabs").tabs();
$('#tabs-1 a').click( function(){
$tabs.tabs('select', 4); });
});
<div id="tabs">
<ul>
<li>Home</li>
<li>Alarms</li>
<li>Access Control</li>
<li>Services</li>
<li>Contact Us</li>
</ul>
<div id="tabs-1">
<p><span class="bodytext">Check our services</span></p> //want to link to tab 4(services)
<p><span class="bodytext">
Contact usfor free 24hours a day...</span></p>
As you can see from the code when you click on "Contact us" text in tab 1 there is a link to tab 5.
What i want to do is to create a link from "Check our services" to tab 4.
In general to create over 10 links withing tabs linking other tabs
I think i know that i have to change $tabs.tabs('select', 4); to $tabs.tabs('select', id); but i dont know how to call the "id" in html when i want to create my link.
Any suggestions?
I think I would handle this differently using the href on the link itself, perhaps with a class to indicate that it is an intra-tab link, to determine which tab to load and setting up the handlers in the tabs create event.
$('#tabs').tabs({
create: function(event,ui) {
$('a.intra-tab',ui.panel).unbind('click').click( function() {
var id = Number( $(this).attr('href').replace(/#tabs-/,'') ) - 1;
$('#tabs').tabs('select',id);
return false;
});
}
});
<div id="tabs">
<ul>
<li>Home</li>
<li>Alarms</li>
<li>Access Control</li>
<li>Services</li>
<li>Contact Us</li>
</ul>
<div id="tabs-1">
<p><span class="bodytext">Check our services</span></p>
</div>
...
You could also do it using live handlers.
$('#tabs').tabs();
$('a.intra-tab').live( 'click', function() {
var id = Number( $(this).attr('href').replace(/#tabs-/,'') ) - 1;
$('#tabs').tabs('select',id);
return false;
});

Resources