How to fetch search data from databse in php - javascript

Here in my code I take a div TextBoxContainer. Now I want that when I click on DynamicTextBox in script inputbox, it displays search values, which are already in the database. I have tried already autocomplete for that but it doesn't work.
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$( "#DynamicTextBox" ).autocomplete({
source: 'search1.php'
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox").val(values);
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox1]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox1").val(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" style="width:280px;margin-left:10px;" id="DynamicTextBox" class="skills" type="text" value = "' + value + '" /> ' + '<input style="width:280px;" name = "DynamicTextBox1" type="text" value = "' + value + '" /> ' +
'<span type="button" class="remove glyphicon glyphicon-remove"></span>'
}
</script>
<html>
<div id="TextBoxContainer"></div>
</html>

Related

Why am I getting undefined on this variable assigned with jQuery .val()?

I'm making a basic shopping list app and have run into a wall. The program silently fails, and upon checking with breakpoints and such, I've discovered that on line 75, I'm getting newItem as undefined.
Everything else in the statement is being defined correctly. Any clue what I've done wrong?
Here's the index.js:
'use strict';
var state = {
items: []
};
var listItemTemplate = (
'<li>' +
'<span class="shopping-item js-shopping-item"></span>' +
'<div class="shopping-item-controls">' +
'<button class="js-shopping-item-toggle">' +
'<span class="button-label">check</span>' +
'</button>' +
'<button class="js-shopping-item-delete">' +
'<span class="button-label">delete</span>' +
'</button>' +
'</div>' +
'</li>'
);
// state modification functions
var stateHelper = {
addItem: function(state, item) {
state.items.push({
displayName: item,
checkedOff: false
});
},
getItem: function(state, itemIndex) {
return state.items[itemIndex];
},
deleteItem: function(state, item) {
state.items.splice(itemIndex, 1);
},
updateItem: function(state, item) {
state.items[itemIndex] = newItemState;
}
}
// render functions
var renderHelper = {
renderItem: function(item, itemId, itemTemplate, itemDataAttr) {
var element = $(itemTemplate);
element.find('.js-shopping-item').text(item.displayName);
console.log("item.displayName: " + item.displayName)
console.log("item: " + item)
if (item.checkedOff) {
element.find('.js-shopping-item').addClass('shopping-item__checked');
}
element.find('.js-shopping-item-toggle')
element.attr(itemDataAttr, itemId);
// try `element.find('.js-shopping-item-toggle').attr(itemDataAttr, itemId);` instead and see if it works
console.log("itemDataAttr: " + itemDataAttr)
return element;
},
renderList: function(state, listElement, itemDataAttr) {
var itemsHTML = state.items.map(
function(item, index) {
//what determines the index here?
console.log("index: " + index)
return renderItem(item, index, listItemTemplate, itemDataAttr);
});
listElement.html(itemsHTML);
}
}
// event listeners
var eventHelper = {
handleItemAdds: function(formElement, newItemIdentifier, itemDataAttr, listElement, state) {
formElement.submit(function(event) {
event.preventDefault();
var newItem = formElement.find(newItemIdentifier).val();
console.log(newItem)
stateHelper.addItem(state, newItem);
console.log(newItemIdentifier)
this.reset();
});
},
handleItemDeletes: function(formElement, removeIdentifier, itemDataAttr, listElement, state) {
listElement.on('click', removeIdentifier, function(event) {
var itemIndex = parseInt($(this).closest('li').attr(itemDataAttr));
console.log("this: " + this);
console.log("$(this).closest('li').attr(itemDataAttr " + $(this).closest('li').attr(itemDataAttr));
stateHelper.deleteItem(state, itemIndex);
renderList(state, listElement, itemDataAttr);
console.log("what is itemDataAttr? it is: " + itemDataAttr)
})
},
handleItemToggles: function(listElement, toggleIdentifier, itemDataAttr, state) {
listElement.on('click', toggleIdentifier, function(event) {
var itemId = $(event.currentTarget.closest('li')).attr(itemDataAttr);
var oldItem = stateHelper.getItem(state, itemId);
stateHelper.updateItem(state, itemId, {
displayName: oldItem.displayName,
checkedOff: !oldItem.checkedOff
});
renderHelper.renderList(state, listElement, itemDataAttr)
});
}
}
$(function() {
var formElement = $('#js-shopping-list-form');
var listElement = $('.js-shopping-list');
//id of input containing list items
var newItemIdentifier = "#js-new-item";
//in listItemTemplate above; the delete button has this class
var removeIdentifier = ".js-shopping-item-delete";
//stores id of list item
var itemDataAttr = "data-list-item-id";
var toggleIdentifier = ".js-shopping-list-toggle"
eventHelper.handleItemAdds(formElement, newItemIdentifier, itemDataAttr, listElement, state);
eventHelper.handleItemDeletes(formElement, removeIdentifier, itemDataAttr, listElement, state);
eventHelper.handleItemToggles(listElement, toggleIdentifier, itemDataAttr, state);
});
And here's the index.html for reference:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Shopping List</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<h1>Shopping List</h1>
<form id="js-shopping-list-form">
<label for="shopping-list-entry">Add an item</label>
<input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
<button type="submit">Add item</button>
</form>
<ul class="shopping-list">
</ul>
</div>
<script src="jquery-3.1.1.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
Alacritas,
I don't see anywhere in your view that you actually have an element with an id that matches that accessor (#js-new-item).
Your comment says it belongs to the input box, but the input box you have in your html does not have that id.
I think you would need to update the string "#js-new-item" to be "#shopping-list-entry".

generate JSON data based on input fields

I would like to generate JSON data based on the following input fields:
name
uRL
where the JSON data output would look something like this:
{
"items": [
{
"url": "content/San-Francisco/berkeleyCampanile.jpg",
"name": "Image 1 name"
},
{
"url": "content/San-Francisco/castro.jpg",
"name": "Image 2 name"
},
{
"url": "content/San-Francisco/Tenderloin.jpg",
"name": "Image 3 name"
}
]
}
How it works right now is that theres two input field, name and url, and users can add another set of name and url inputs by clicking on the add button as shown on the picture
What I want is that when the user hits on generate it output based on all of the input filled the json data as shown on the format above.
Below is the code:
<head>
<link href="css/style.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<fieldset id="buildyourform">
<legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
});
</script>
</body>
</html>
Any help will be greatly appreciated
Update:
<html>
<head>
<link href="css/style.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form id="myform">
<fieldset id="jsonBuilder">
<legend id="legendHead">Neighboorhood Creation</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="submit" value="generate" class="add">
</form>
<script>
function showValues() {
var frm = $('#myform');
var data = JSON.stringify(frm.serializeArray());
}
</script>
<script>
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \"id=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
var url = $("<input type=\"text\"id=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#jsonBuilder").append(fieldWrapper);
});
});
</script>
</body>
</html>
A suggestion:
same ids are getting repeated so i changed it to class.
All you need is this:
$('#preview').click(function(){
var o = {"items":[]}; // create an object with key items to hold array
$('.fieldwrapper').each(function(){ // loop in to the input's wrapper
var obj = {
url : $(this).find('.url').val(), // place the url in a new object
name : $(this).find('.name').val() // place the name in a new object
};
o.items.push(obj); // push in the "o" object created
});
$('#console').text(JSON.stringify(o)); // strigify to show
});
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \" placeholder=\"Name of Neighborhood\"class=\"name fieldname\" />");
var url = $("<input type=\"text\" placeholder=\"Paste here the URL of the Image\"class=\"url fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$('#preview').click(function(){
var o = {"items":[]}; // create an object with key items to hold array
$('.fieldwrapper').each(function(){ // loop in to the input's wrapper
var obj = {
url : $(this).find('.url').val(), // place the url in a new object
name : $(this).find('.name').val() // place the name in a new object
};
o.items.push(obj); // push in the "o" object created
});
$('#console').text(JSON.stringify(o)); // strigify to show
});
});
#console {
background: #c5c5c5;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="buildyourform">
<legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />
<div id='console'></div>
I have made a JSFiddle for your guidance. Please take a look.
JSFiddle
$( "form" ).submit(function( event ) {
var items = {};
items["items"] = $( this ).serializeArray();
console.log(JSON.stringify(items));
event.preventDefault();
});
<form>
<input type="text" name="url" />
<input type="text" name="image" />
<input type="text" name="url" />
<input type="text" name="image" />
<button class="generate" type="submit" id="generate">Generate</button>
</form>
You can use the JQuery .serializeArray() method, here's the documentation
Here's an example:
var json = $('#form').serializeArray();
If you don't want to add the form tag to your code, here's a script that creates the JSON from your current form, FIDDLE
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" placeholder=\"Name of Neighborhood\"class=\"fieldname\" name=\"name\" />");
var url = $("<input type=\"text\" placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" name=\"url\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$('#preview').click(function(){
var json = {};
json.items = [];
$('.fieldwrapper').each(function(e){
var obj = {};
obj.name = $(this).find('input[name=name]').val();
obj.url = $(this).find('input[name=url]').val();
json.items.push(obj);
});
console.log(json);
});
});
With Json Indentation
html
<fieldset id="buildyourform">
<legend>test</legend>
</fieldset>
<input type="button" value="Add a field" class="add" id="add" />
<input type="button" value="Generate" class="add" id="preview" />
<pre id="json"></pre>
Javascript
var items = {'items':[]}
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#buildyourform div").length + 1;
var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
var name = $("<input type=\"text\" \"class=\"name\"placeholder=\"Name of Neighborhood\"class=\"fieldname\" />");
var url = $("<input type=\"text\"class=\"url\"placeholder=\"Paste here the URL of the Image\"class=\"fieldname\" />");
var removeButton = $("<input type=\"button\"class=\"remove\" value=\"Remove\" />");
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(name);
fieldWrapper.append(url);
fieldWrapper.append(removeButton);
$("#buildyourform").append(fieldWrapper);
});
$('#preview').on('click',function(){
$('.fieldwrapper').each(function(){
items.items.push({'url':$(this).find('.url').val(),'name':$(this).find('.fieldname').val()});
});
document.getElementById("json").innerHTML = JSON.stringify(items, undefined, 2);
});
});
here is a Fiddle
Here is another one without the form demo#fiddle
$("#preview").click(function() {
var arr = {};
arr.items = [];
$(".fieldwrapper").each(function() {
var entry = {}
var neighborhood = $(this).find("input[name='neighborhood']").val();
var url = $(this).find("input[name='url']").val();
entry["url"] = url;
entry["name"] = neighborhood;
arr.items.push(entry);
});
alert (JSON.stringify(arr, null, 4));
});
P.S. I have added name attributes to your input elements.

Cannot select a button which appended dynamically in jQuery

I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.
here is my script:
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
})
this is what i use to select:
$(':button.diaries').click(function(){});
but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?
#Kelvin Aliyanto ....So the solution will be like this
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
});
$('div').on('click', '.diaries', function(event){
alert("Hi");
}) ;
});
</script>
<div id="diaryList"></div>
check your code is after document ready
$(document).ready(function(){ //your code here });
and use
$('button.diaries').on(click , function(){})
instead of .click

Getting 0x800a138f - JavaScript runtime error: Unable to get property 'client' of undefined or null reference

I'm making a chat application using SignalR API. I'm getting error as:
0x800a138f - JavaScript runtime error: Unable to get property 'client'
of undefined or null reference
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="/Css/ChatStyle.css" />
<link rel="stylesheet" href="/Css/JQueryUI/themes/base/jquery.ui.all.css">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/ui/jquery.ui.core.js"></script>
<script src="/Scripts/ui/jquery.ui.widget.js"></script>
<script src="/Scripts/ui/jquery.ui.mouse.js"></script>
<script src="/Scripts/ui/jquery.ui.draggable.js"></script>
<script src="/Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
$("#divLogin").show();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
</head>
<body>
<div id="header">
SignalR Chat Room
</div>
<br />
<br />
<br />
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
</body>
</html>
You are referring to the client object of an undefined object. So I have been searching inside your code for
.client
These were the results:
chatHub.client.onConnected
chatHub.client.onNewUserConnected
chatHub.client.onUserDisconnected
chatHub.client.messageReceived
chatHub.client.sendPrivateMessage
So, if you look at the results, it becomes obvious that chatHub is undefined somewhere. This is how you initialize it:
var chatHub = $.connection.chatHub;
I wonder what is inside $.connection. Are you missing a script from your html?
A couple of things...
You're using an old signalr version, have you tried upgrading to the latest?
Otherwise; I had a similar problem, I had to solve it by setting up the connection without the generated proxy (/signalr/hubs).
See this link http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client and instead of setting it as a "generated proxy", implement it without it. (Search for "Without the generated proxy")

Uncheck checkbox with close button

Please, advice.
I want to add tags inside the container marking checkboxes and remove tags by clicking on the "x" button of each tag.
Everything works fine except that when you click on the "x" button and tags are removed the state of the checkbox remains checked.
But I need that when you click on the button of each tag the state of the checkbox must be unchecked.
It might be easier to do with the value and the name of input, but I can't use them - only id.
$(document).ready(function() {
var $list = $("#itemList");
$(".chkbox").change(function() {
var a = $('label[for="' + this.id + '"]').text();
if (this.checked) {
$list.append('<li>'+a+'<button class="closebutton" value="'+a+'">X</button></li>');
}
else {
$("#itemList li:contains('"+a+"')").remove();
}
})
$(document).on('click','.closebutton',function(){
var b = this.value;
$("#itemList li:contains('"+b+"')").remove();
$('label[for="' + this.id + '"]').removeAttr('checked');
});
});
<div id="items">
<ul id="itemList">
</ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button"><label for="one"><input type="checkbox" id="one" class="chkbox"><span>First book</span></label> </div>
<div id="ck-button"><label for="two"><input type="checkbox" class="chkbox" id="two"><span> Second book</span></label> </div>
</div>
Try
$(document).ready(function () {
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $(this).next().text();
if (this.checked) {
$('<li>' + a + '<button class="closebutton" value="' + a + '">X</button></li>').appendTo($list).data('src', this);
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var $li = $(this).closest('li');
$($li.data('src')).prop('checked', false);
$li.remove();
});
});
Demo: Fiddle
Try this:
<div id="items">
<ul id="itemList">
</ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button1"><label for="one"><input type="checkbox" id="one" class="chkbox"><span>First book</span></label>
</div>
<div id="ck-button2">
<label for="two"><input type="checkbox" class="chkbox" id="two"><span> Second book</span></label></div>
</div>
</body>
<script>
$(document).ready(function()
{
var $list = $("#itemList");
$(".chkbox").change(function()
{
var a = $('label[for="'+this.id+'"]').text();
var t = this.id;
if(this.checked)
{
$list.append('<li>'+a+'<button class="closebutton" title="'+t+'" value="'+a+'">X</button></li>');
}
else
{
$("#itemList li:contains('"+a+"')").remove();
}
})
$(document).on('click', '.closebutton', function()
{
var b = this.value;
var q = this;
$("#itemList li:contains('"+b+"')").remove();
$('#'+this.title).removeAttr('checked');
});
});
</script>
Or See this demo: http://jsfiddle.net/knYvf/
API used:
find: http://api.jquery.com/find/
contains: http://api.jquery.com/contains-selector/
This line should do the trick:
$('label:contains("' + b + '")').find('.chkbox').prop('checked', false);
+1 to you for neat question as well!
Hope any will suffice the need :)
Code
$(document).ready(function () {
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $('label[for="' + this.id + '"]').text();
if (this.checked) {
$list.append('<li>' + a + '<button class="closebutton" value="' + a + '">X</button></li>');
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var b = this.value;
$("#itemList li:contains('" + b + "')").remove();
$('label:contains("' + b + '")').find('.chkbox').prop('checked', false);
});
});
<div id="items">
<ul id="itemList"></ul>
</div>
<div id="tab1" class="tab-pane">
<div id="ck-button">
<!--html code should be like this no need to add span-->
<input type="checkbox" id="one" class="chkbox"/>
<label for="one">First book</label>
</div>
<div id="ck-button">
<input type="checkbox" class="chkbox" id="two" />
<label for="two"> Second book</label>
</div>
var $list = $("#itemList");
$(".chkbox").change(function () {
var a = $('label[for="' + this.id + '"]').text();
var name=$(this).attr('id');
if (this.checked) {
//add name attribute in the button with the id of checkbox
$list.append('<li>' + a + '
<button class="closebutton" value="' + a + '" name="'+name+'">X</button></li>');
} else {
$("#itemList li:contains('" + a + "')").remove();
}
})
$(document).on('click', '.closebutton', function () {
var b = this.value;
$("#itemList li:contains('" + b + "')").remove();
//remove the checkbox whose id is same as the name attribute of button
$(':checkbox[id="' + this.name + '"]').removeAttr('checked');
});
DEMO

Categories

Resources