jquery jqwidgets listbox disappearing when submit button clicked - javascript

I am trying to learn a little about jquery and working with some UI widgets (JQWidgets). I am trying to get call a php script and call back some data in json format. I know that the json format is correct because I can get a listbox to show and run correctly if I just run it straight through. I am trying to type a value into a textbox and when I click on a submit button it will return a list of data into the listbox. When I click the button, the outline of box shows then disappears. I am not sure what I am doing.
Javascript Code:
<script type="text/javascript">
$(document).ready(function() {
//create jqxButton widget
$("#btnSubmit").jqxButton({ width: '150'});
//create jqxListBox widget
$("#btnSubmit").bind('click', function() {
//Do som
var textValue = $("#txtSearch").val();
var url = "include/showsearch.php?show_name='" + textValue + "'"; //returns json data
var source =
{
datatype: "json",
datafields: [
{ name: 'name' },
{ name: 'id' }
],
url:url
};
var dataAdapter = new $.jqx.dataAdapter(source);
dataAdapter.dataBind();
//crate jqxList widget
$("#search_grid").jqxListBox({source: dataAdapter,selectedIndex: 0,theme:'classic',displayMember: "name", valueMember:"id",itemHeight:70,height:'75%',width:'100%'});
});
});
Partial HTML:
<div id="content1">
<form id="search">
<label for="search">Search For:</label>
<input type="text" id="txtSearch" name="q">
<input style='margin-top: 20px;' type="submit" value="Search" id="btnSubmit"/>
</form>
<div id="search_grid">
</div>
<div style="font-size: 13px; font-family: Verdana;" id="selectionlog">
</div>
</div>
<div id="content2">
<div id="dl_grid">
</div></div>
Thanks in advance.
EDIT: I also want to mention that I am using 000webhost and I turned off the tracking script they use.

The problem is most probably your ListBox's height setting. If you want to define height in percentages, your container element should be with "height" defined, too, because 75% of something which is with auto-height by default would be equal to 0. Take a look at: jQWidgets ListBox with Size in Percentages

Related

Targeting specific items in a #foreach loop with Javascript

I have developed a comments editing system in my blog application.
When a user clicks on the page of a select blog post, a #foreach loop iterates through that post's comments and displays each one in the view underneath the Post's main content.
It is also possible for a user to edit a comment's content. User's click an edit button on the comment and a JavaScript function renders its <textarea> editable as well as unhides a "save" button. Once edited and the user hits save, a second JavaScript function sends the updated content to a Controller method which updates the relevant comment on the database.
The code I've produced works fine when there is one comment under the blog post, however, when there are multiple comments on the page, the JavaScript is not able to distinguish which comment is referenced - for example, pressing the edit button on one comment makes the save button appear for all comments.
Is there a straightforward way I can encapsulate the JavaScript for each comment?
Or is the best approach to produce unique Ids for each Comment? If so, what would be the best approach?
My code for your reference is below, though please note I am still new to web scripting and any pointers are appreciated.
THE VIEW (RAZOR):
#model List<Assignment_3.Models.CommentSubmission
//Blog Post
//Comments
#foreach (var item in Model)
{
//Comment information
//The textarea
<textarea rows="10" readonly class="descriptionForm" id="DescriptionText">#item.Body</textarea>
//The Edit button
<div style="text-align:right">
<img class="edit_icon" src=#Url.Content("~/Images/edit.png") alt='edit' height=15 width=15 />
<br />
//The Save button once editing is complete
<button type="submit"class="btn1" style="visibility: hidden">
<p class="split-btn-name">Save</p>
<span class="separator"></span>
<p><span class="glyphicon glyphicon-ok"></span></p>
</button>
</div>
}
<script>
//Make textarea editable and unhide the edit save button
$(document).ready(function () {
$(".edit_icon ").click(function () {
$(".descriptionForm").removeAttr("readonly");
$(".btn").removeAttr("style");
});
});
//Send updated content to Controller and update database
$(".btn1").click(function () {
$(".btn1").hide();
$(".descriptionForm").setAttribute('readonly');
var text1 = document.getElementById('DescriptionText').value;
var url = "/Comments/EditComment?id=#item.Id&s="+ text1;
$.post(url, null, function (data) {
});
});
</script>
THE CONTROLLER:
public void EditComment(int id, string s)
{
var cS = _context.CommentSubmissions
.Where(c => c.Id == id).
FirstOrDefault();
//The Comment's text body
cS.Body = s;
_context.Entry(cS).State = EntityState.Modified;
_context.SaveChanges();
}
UPDATE
ANSWER (thanks to Greg):
FORM:
<div class="row" style="padding: 15px;">
<div data-rel="#item.Id">
<textarea rows="10" readonly class="textarea">#item.Body</textarea>
<div style="text-align:right">
<p>
Edit <img class="edit_icon" src=#Url.Content("~/Images/edit.png") alt='Edit' height=15 width=15 id="EditIcon" />
</p>
#*The Save button once editing is complete*#
<input type="button" data-input="edit" value="Save" style="visibility: hidden" id="saveButton">
</div>
</div>
</div>
JQUERY:
<script>
$(function () {
$(".edit_icon").click(function () {
var container = $(this).closest('.row');
var id = parent.find('div[data-rel]');
var content = container.find('.textarea');
var button = container.find('#saveButton');
button.removeAttr("style");
content.focus();
content.removeAttr('readonly');
});
$("#saveButton").click(function () {
var container = $(this).closest('.row');
var id = container.find('div[data-rel]');
var content = container.find('.textarea');
var button = container.find('#saveButton');
button.hide();
content.prop('readonly', true);
var text1 = descriptionForm.value;
var url = "/Comments/EditComment?id=" + id + "&s=" + text1;
$.post(url, null, function (data) {
});
});
});
</script>
As denoted in the comment, your JavaScript has nothing unique to anchor on. So it modifies all elements that meet your criteria, to resolve this you can achieve with a unique identifier or structuring your markup better.
In your case, you have a button with a type="submit" which will instantly cause a post back. Not sure if that is indeed your intent, but you could do:
#foreach(var content in Model)
{
<form name="content.Id" action="Blog/Save" method="post">
</form>
}
In this instance, the post back from your submit could directly hit the server. But, post backs aren't cool. To rectify via Ajax, you can do.
#foreach(var content in Model)
{
<div class="container">
<div data-rel="#content.Id">
<!-- Put form data, or whatever here. -->
<input type="button" data-input="edit">Edit</input>
</div>
</div>
}
Now you have a unique value, clean structure, and you can move throughout the hierarchy fairly easy. So, for JavaScript you could do:
function editBlog(element) {
var container = document.querySelector(element).closest('[data-rel]');
}
I believe that is the ideal approach for JavaScript, I'm a custom to jQuery or a framework like Vue. So double check the syntax. But in theory, the JavaScript will scale from the button event to the parent node, then retrieve the child id. Similar mapping or templates can occur, so you can post the data to your action.
Hopefully this helps.
Update: You may get some domain error, but I hope not. Anyways, this is a really simple example.
Container : Simple element to act as a wrapper.
Row : Allow you to create a row for element structure.
Column : Will space around, to fit within window.
The point, is the jQuery will recurse up from the button, to the column, to the row, to the section id, to the container. But, it won't affect any other element on the page. If the jQuery was changed, to not affect a specific element, for instance:
$('button').click(function (e) {
$(this).text('Edit'); // Only this element
$('button').text('Edit'); // All button elements
});
$(function () {
$('button').click(function () {
var container = $(this).parents('.container');
var id = parent.find('div[data-rel]');
var rows = parent.find('.row');
var columns = parent.find('.column');
alert('The section id: ' + id.val());
console.log(container.html());
console.log(id);
console.table(rows);
console.table(columns);
});
});
.container {
width: 100%;
padding: 1rem;
box-shadow: 2px -1px 1px -2px, -1px 2px 1px -2px;
}
.row {
display: flex;
flex-flow: row;
justify-content: space-around;
align-items: center;
}
.column {
width: 33.3%;
}
.column:last-of-type {
width: 10%;
}
.column span {
width: 100%;
padding: .2rem;
display: inline-block;
}
.column label {
width: 95%;
}
.column button {
width: 100px;
}
.column input, .column textarea {
width: 95%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div data-rel="1">
<div class="row">
<div class="column">
<span>
<label>Article Name:</label>
<input type="text" data-rel="txtArticleName" />
</span>
<span>
<label>Article Date:</label>
<input type="text" data-input="txtArticleDate" />
</span>
</div>
<div class="column">
<label>Article Summary:</label>
<textarea data-input="txtArticleSummary" rows="5"></textarea>
</div>
<div class="column">
<button name type="button" onclick="return false;">Save</button>
</div>
</div>
</div>
</div>
<div class="container">
<div data-rel="2">
<div class="row">
<div class="column">
<span>
<label>Article Name:</label>
<input type="text" data-rel="txtArticleName" />
</span>
<span>
<label>Article Date:</label>
<input type="text" data-input="txtArticleDate" />
</span>
</div>
<div class="column">
<label>Article Summary:</label>
<textarea data-input="txtArticleSummary" rows="5"></textarea>
</div>
<div class="column">
<button type="button" onclick="return false;">Save</button>
</div>
</div>
</div>
</div>
The code works, but you may have security enabled that may not allow it to work. But the example is the important part.

jQuery doesn't work in a dynamic content

I have a problem with my web application. I've created a tchat in Ajax and I want it to be loaded when I click on a button. It works, but the dynamic data loaded doesn't support jQuery.
When I click on the button, I dynamically change the content of a div, initially empty. But on this finder (which open) I have a link which should load smileys simply in changing the height of the div, which is initially at 0 px.
I've done tests, and when I click on the button, the height is good changed, but nothing appear on the screen.
Here is a screenshot of my chat:
When I click on the smiley, I should see that:
But nothing happened.
Here is the code that works fine because the height is changed (I've tested it) :
var elm = window.document.getElementById('myCGU_Appear-1');
if (elm.style.height == "0px") {
elm.style.height = "100px";
elm.style.overflow = "auto";
window.document.getElementById('appear_emoticon-1').src = "/assets/images/emoticons/my_small_emoticons_000.png";
} else {
elm.style.height = "0px";
window.document.getElementById('appear_emoticon-1').src = "/assets/images/emoticons/my_small_emoticons_01.png";
}
I think I've done a mistake somewhere because yesterday the code worked fine...
Here is the code that load the tchat :
$.ajax({
url:"/scripts/ajax/load_tchat.php",
type: "POST",
data: "method_call=open",
dataType: "json",
success: function(data){
console.log(data);
if(data.tchat_operation == 'open') {
// load datas
$("#frameChat").html(data.tchat_content);
// open the tchat
frameChat.classList.remove("Espace-Chat-Ferme");
frameChat.classList.add("Espace-Chat");
}
},
error: function(resultat, statut, erreur){
console.log(resultat);
console.log(erreur);
}
});
And here is the JSON code that is send to me and that I've on my div :
> this.tchat_content
< "
[...]
<div style=\"position: absolute; bottom: 5px; width:280px; class=\"myBackgroundGreyLight\">
<div class=\"section group\">
<div class=\"col span_1_of_1\"><div id=\"myCGU_Appear-1\" name=\"myCGU_Appear-1\" style=\"height:0px;margin-bottom:2%;-webkit-transition:all 0.2s ease-in;transition: 0.5s ease-in-out;overflow: hidden;display:block;\" class=\"myBackgroundGreyLight\">All emoticons</div>
<a href=\"#\" onclick=\"My_CGU_Appear2(-1,5000)\" class= \"button scrolly\" >
<img id=\"appear_emoticon-1\" src=\"/assets/images/emoticons/my_small_emoticons_01.png\" width=\"6%\">
</a><div class=\"fileUpload\">
<input type=\"file\" accept=\"image/x-png, image/gif, image/jpeg, image/jpg\" id=\"imgInp-1\" />
</div>
<div>
<a href=\"#ouvre_photo\" onclick=\"AddImageInInput2(this,-1);\">
<img id=\"blah-1\" src=\"\" alt=\"\" />
</a>
</div><div contentEditable=\"true\" class=\"contact_message\" id=\"txt_comments-1\" onkeyup=\"ia_content_analysis(-1, event,2);\" style=\"background-color:white;max-height:125px;overflow-y:auto;overflow-x:hidden;min-height: 50px;\"></div>
<div id=\"test-1\" style=\"float:right;\">
<h4> </h4>
</div>
<div id=\"callback_-1\" style=\"font-size:11px;margin-top:10px;\"></div>
<div style=\"clear:both; display:block; height:10px;\"></div>
<div style=\"display:inline-block;width:100%;\">
<a style=\"display:inline-block;background-color:#bf0e07;float:right;border-radius:4px;padding:5px;cursor:pointer;width:50px;text-align:center;font-size:12px;color:white;\" rel=\"-1\" class=\"publish_message\">Publier</a>
</div>
</div>
</div>
</div>
<script src=\"/assets/javascript/jquery.min.js\"></script>
<script src=\"/assets/javascript/My_JSFunctions.js\"></script>
<script src=\"/assets/javascript/ajax.js\"></script>"
Thanks if you can help me or show me the right way :)
You haven't set any event handler on your emoticon-button. After loading HTML data via ajax you have to reinitialize all your event handlers previously set on your elements if you had set them via ID. So instead of reinitializing all the time you could try:
$(document).on('click', '#yourButtonId', function() { /* my logic */ });
instead of assigning the event handler directly on the dynamic content. I hope I got you right. Else providing a JSFiddle would help.

How to show and close form on click of a div?

When a div is clicked I want to show a form, as done on this page. This is what I have tried (fiddle):
$(document).on("click","#tawkchat-minified-container",function() {
var htmldynamic = ' <form id="test" action="test.php">\
<div>\
Test: <input name="blah" value="test" type="text">\
</div>\
</form>'
$("#maximizeChat").html(htmldynamic);
});
I don't know if this is the right way to do it. Is there a better approach?
Adding large chunks of HTML as JavaScript variables is not good practice. It is easy to make errors in the HTML as you have to read it awkwardly embedded in the JS.
A better approach is to include the HTML code with the rest of your markup, but use CSS to hide it. Then you can just show it using JavaScript when it is pressed.
HTML:
<div id="my-form-container">
<div id="my-form-header">My form</div>
<form id="my-form" action="test.php">
<div>
Test: <input name="blah" value="test" type="text">
</div>
</form>
</div>
CSS:
#my-form {
display: none; /* This will hide the form. */
}
JavaScript:
//When the container is clicked...
$("#my-form-container").click(function() {
//...show the form.
$("#my-form").show();
});
Use this approach will definitely solve your problem
$(document).ready(function(){
$("#tawkchat-minified-agent-container").click(function()
var hlink = $("#test").val();
$("#test").click(function(){
$(".form").show()
});
});
});

PHP Ajax live search box

I am trying to make a PHP Ajax live search Box, so far is working good but it seems that I am facing two problems:
The first one is that when data is showing on the screen, I want it to disappear if I move the mouse outside the search box.
The second one is related to CSS, I want the position of data results to be just under my search box, now is floating right.
Here the code:
<div class="widget-container widget_search">
<span class="adds"></span>
<form action="" id="searchform" method="POST">
<p>
<input type="text" id="search" placeholder="Chercher" size="30" name="search">
<button type="submit" id="searchsubmit"></button>
</p>
</form><!--/ #searchform-->
<div id="livesearch" style=" width:auto; height:auto; margin:auto; position: absolute;"></div>
</div><!--/ .widget-container-->
JS:
$(document).ready(function(){
$("#search").keyup(function(){
var valor = $("#search").val();
$.ajax({
type: "POST",
url: "/auto/search/",
data: {word:valor},
success: function(res) {
$('#livesearch').html(res);
}
});
});
});
Let'suppose the data container has an id, like "myid". Then, you can hide it like this:
document.getElementById('myid').style.display = "none";
You can make it visible like this:
document.getElementById('myid').style.display = "block";
To make this general, you can do something like this:
function changeDisplay(element, display) {
element.style.display = display;
}
You can store the data container like this:
var dataContainer = document.getElementById("myid");
Now, you want to hide it when the mouse leaves. So, you need to set the onmouseout of your search box to a function like this:
function left() {
changeDisplay(dataContainer, "none");
}
But you probably want to make it reappear when you hover to the element. So you need to set the onmouseover event to a function like this:
function entered() {
changeDisplay(dataContainer, "block");
}
As about positioning the results, you might consider adding a <br> after the search tag and then position it to the left.
using jquery:
livesearch-id of div (search box)
one-id of div where search elements are being showed
$("#livesearch").mouseout(function(){$('#one').hide(); //hides the div
});
$("#livesearch").mouseover(function(){$('#one').show(); //shows the div when mouse is pointed again
});
CSS:
set style="margin-left:(number) px;"

jquery resizable not working after ajax update

I have a resizable div that has some text in it and a edit button.
On the edit button click it opens a layer with a textbox and save button so the user can edit the text.
Then the user clicks save, the layer is closed and the db updated with some ajax. The div on the parent page is also updated with some ajax.
The problem I have is that the div is no longer resizable.
I know the line of code that is doing this and why it is doing it but cant find any other solution to updating the original div without stripping out the resizable code as well.
On the 'save' button click on the layer this function is called
$(document).ready(function() {
$('.button').click(function() {
var edit_content = $('#myFrm').find('.nicEdit-main').html();
var box_id = $('#myFrm').find("#box_id").val();
var page_ref = $('#myFrm').find("#page_ref").val();
var template_ref = $('#myFrm').find("#template_ref").val();
$.post("update_textarea.php",
{
box_id:box_id, page_ref:page_ref, template_ref:template_ref, edit_content:edit_content
},
function(data,status){
UpdateElementOfParent(box_id, page_ref, template_ref)
edit_box('hide')
});
});
});
This updates the db and the function UpdateElementOfParent() is called on the parent page
function UpdateElementOfParent(box_id, page_ref, template_ref) {
var myBox = box_id;
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref })
.done(function(data) {
$('#'+myBox).html(data);
});
}
this updates the original div with the updated content from the db.
I know the $('#'+myBox).html(data); strips out the inner html of the div and replaces it with the text and so removes the jquery resizable text but I cant find another way to update the text.
I have tried
$('#'+myBox).value(data);
$('#'+myBox).text(data);
$('#'+myBox).innerHTML(data);
document.getElementById('myBox').val(data);
document.getElementById('myBox').value(data);
document.getElementById('myBox').text(data);
document.getElementById('myBox').val=data;
document.getElementById('myBox').value=data;
document.getElementById('myBox').text=data;
None of these work.
My javascript is not too strong(as you can probably tell).
Can anyone help with a solution?
any help greatly appreciated
QUICK UPDATE
I noticed that if I use firebug inspector the div before it has any text updates is like so
<div id="3" class="textarea1 ui-resizable ui-resizable-autohide" style="width:300px; height:300px;position:absolute; top:10px;left:0px;overflow-y: none;background-color:transparent;" name="textarea[3]">
newtextarea
<div class="ui-resizable-handle ui-resizable-e" style="z-index: 90; display: none;"></div>
<div class="ui-resizable-handle ui-resizable-s" style="z-index: 90; display: none;"></div>
<div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 90; display: none;"></div>
</div>
but once I update it (I use nicedit to format the text) the div now has a hidden ipnout within it called 'content[]'
<div id="3" class="textarea1 ui-resizable ui-resizable-autohide" style="width:300px; height:300px;position:absolute; top:10px;left:0px;overflow-y: none;background-color:transparent;" name="textarea[3]"></div>
<br></br>
<input type="hidden" value="
<div align="justify">
<font face="trebuchet ms" size="2"><strong>Lorem Ipsum</strong> es simplemente el texto de relleno de las imprentas y archivos de texto.</font>
</div>" name="contents[1]">
</input>
so it would seem that the structure of the div has change and the inner input would need updating. As the input does not have an id how can I update just using its name
MORE
ok I have edited the update function to this
function UpdateElementOfParent(box_id, page_ref, template_ref) {
var myBox = box_id;
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref })
.done(function(data) {
var updatedata=data+"<div class='ui-resizable-handle ui-resizable-e' style='z-index: 90; display: none;'></div><div class='ui-resizable-handle ui-resizable-s' style='z-index: 90; display: none;'></div><div class='ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se' style='z-index: 90; display: none;'></div></div>";
('#'+myBox).html(updatedata);
});
}
now when I check the original dv in firebug with the newly updated one the structure and contents are exactly the same.
I need to reinitialise the resizable. any clues?
Not really sure what you want really to do but.
var oldContent = $('#'+myBox).html();
$('#'+myBox).html(data+oldContent);
Will keep the old content and add the new one.
Or you can use .append() http://api.jquery.com/append/ depending on what you get back when updating the database
$('#'+myBox).append(data);
UPDATE:
From what I can see data retrieves a hidden input with the value of the new text. I suggest that you either change data to give back something else or add the input value to the div manually.
The input is also wrong. In the input The value="" should be value='' because you already have " inside of it. After that this function should place the value inside the right div.
function UpdateElementOfParent(box_id, page_ref, template_ref) {
var myBox = box_id;
$.get("get_content.php", { box_id: box_id, page_ref: page_ref, template_ref:template_ref })
.done(function(data) {
$('#'+myBox).html(data);
var inval = $("input[name='contents["+myBox+"]']").val();
$("#"+myBox).html(inval).resizable();
});
}
The basic problem you had at start was that you forgot to reinitialize .resizable() on the new div.
I used dt192's suggestion and added a span inside the div and updated the span and it works great

Categories