I am getting json response from my server.
I am getting detail of user like school(name,id),major subject(name,id),start ,end etc.
I want to show this is appropriate text fields inside a form where user can edit this and after editing user should submit it again to server.
I am embadding fetched json code with html code inside the jquery.
I am finding it very difficult to manage html inside jquery is there any better way to this with following code.
$(document).on('click', '.edit-edu', function(event) {
event.preventDefault();
var id = $(this).parents('.row').attr('id');
var id1 = id.split('-');
$.post("SingleEdu", {id: id1[1]}, function(data) {
console.log(data);
$.each(data.educationList, function(key, value) {
$('#' + id).replaceWith('<div id="addNewEdu" class="addorEdit">'
+ '<legend>Edit education details</legend>'
+ '<form action="UpdateEducation" id="UpdateEducation" cssClass="form-horizontal">'
+ '<div class="form-group">'
+ '<div class="col-md-2">'
+ '<label>School/College</label>'
+ '</div>'
+ '<div class="col-md-6">'
+ ' <textfield name="ed.pageBySchoolPid.name" value="' + value.pageBySchoolPid.name + '" id="school2" label="School/College" placeholder="College or School Name" cssClass="form-control">' + '</textfield>'
+ '<input type="hidden" name="ed.pageBySchoolPid.id" value="' + value.pageBySchoolPid.id + '" id="schoolId2" label="School/College" cssClass="form-control">'
+ '</hidden>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<div class="col-md-2">'
+ '<label>Major</label>'
+ '</div>'
+ '<div class="col-md-6">'
+ '<input type="text" name="ed.pageByMajorPid.name" value="' + value.pageByMajorPid.name + '" id="major1" label="Class" placeholder="Major Subject" cssClass="form-control">'
+ '<input type="hidden" name="ed.pageByMajorPid.id" value="' + value.pageByMajorPid.id + '" id="majorId1" label="Class" cssClass="form-control">'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<div class="col-md-2">'
+ '<label>Start</label>'
+ '</div>'
+ '<div class="col-md-6">'
+ '<input type="text" name="ed.start" value="' + value.start + '" id="sstart1" label="From" placeholder="eg. Start: July 2007" cssClass="form-control">'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<div class="col-md-2">'
+ '<label>End</label>'
+ '</div>'
+ '<div class="col-md-6">'
+ '<input type="text" name="ed.end" value="' + value.end + '" id="send1" label="To" placeholder="eg. End : May 2011 or Till" cssClass="form-control">'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<div class="col-md-2">'
+ '<label>Visibility</label>'
+ ' </div>'
+ '<div class="col-md-6">'
+ '<select label="Visibility" name="ed.visibility" value="' + value.visibility + '" id="svisibility1" value="public" cssClass="form-control">'
+ '<option>Public</option>'
+ '<option>Friends</option>'
+ '<option>Me</option>'
+ '</select>'
+ '</div>'
+ '</div>'
+ '<div class="form-group">'
+ '<div class="col-md-2">'
+ '<label class="sr-only">Submit</label>'
+ '</div>'
+ '<div class="col-md-6">'
+ '<input type="submit" value="add" id="submit_education" cssClass="btn btn-sm btn-success"/>'
+ '</div>'
+ '</div>'
+ '</form>')
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"></script>
<div class="row" id="edu-56">
<div>Specialization</div>
<div>School</div>
<div>start end</div>
<i class="fa fa-edit edit-edu">edit</i>
<i class="fa fa-times delete-edu"></i>
</div>
You could store your code inside another .html file and pull it in using another AJAX call:
var FormHTML = '';
$.get('form.html', function(data) {
FormHTML = data;
});
Then to get your values in you can set up your input HTML with something that can be easily replaced out. I've just wrapped the object name in between some #:
<input type="hidden" name="ed.pageByMajorPid.id" value="##pageByMajorPid.id##" id="majorId1" label="Class" cssClass="form-control">
Then to replace out these values with your actual values, just do a loop:
for (var name in value) {
if (typeof value[name] != 'object') { // If not an object, replace the value
formHTML = formHTML.replace('##' + name + '##', value[name])
} else { // Else if it is an object, loop through it
for (var name2 in value[name]) {
formHTML = formHTML.replace('##' + name + '.' + name2 + '##', value[name][name2])
}
}
}
$('#' + id).replaceWith(formHTML);
Hope that works for you, let me know :)
You can use template engine like Mustache https://mustache.github.io/
Related
I have a page in which I have to show list of data in UI through ajax & append the list data in html table save that list data into Local Storage with Jquery, My question is that I want to implement lazy load in UI such that user clicks a button (Click to view more list), and after clicking the button the ajax calls another list with limit & offset to show more list & append the new list below the existing list in UI and also save the data into local storage along with the existing data present.
My Ajax Call for List Data
var sendingData = {
limit: "50000",
offset: "0"
};
$.ajax({
type: 'POST',
url: "/Common/Item/getselleritems?SellerId=" + userid,
data: sendingData ,
crossDomain: true,
success: function (data)
{
localStorage.setItem("productCode", JSON.stringify(data));
},
error()
{
//Do something
}
});
``
My Html design Function
function showProducts()
{
var productsStorage = localStorage.getItem("productCode");
var products = JSON.parse(productsStorage);
var trHTML = '';
$("table tbody").html("");
$.each(products.Data, function (key, value)
{
trHTML += '<tr>'
+ '<td class="d-md-flex align-items-center">' + '<figure style="' + imgStyle + '"><a href="" title="Photo title" data-effect="mfp-zoom-in">' +
'<img src="' + imgSrc + '" alt="thumb" class="lazy"></a></figure>' +
'<div class="flex-md-column">' +
'<h4 class="package_name" id="itemdescription_' + value.Id + '" onclick = "packageDetails(\'' + value.Price + '\',\'' + value.Name + '\',\'' + value.Description
+ '\',\'' + itemTimeSlotType + '\',\'' + value.ServiceName + '\',\'' + value.PreparationTime + '\',\'' + value.Quantity + '\')" >' +
'<i class="icon_box-selected" style="' + style + '; margin-right:3px"></i>' +
value.Name + '</h4>' +
'<p>' + value.Description + '</p>' +
'<em>' + "Available In: " + itemTimeSlotType + '</em>' + '<br>' +
'<span class="stars_sellerItem" style="' + starStyle + '">' + value.FoodtestAvgRating + ' <i class="icon_star"> </i> ' +
'</span>' +
'</div>' +
'</td>' + '<td style="padding: 0.75rem 0 0.75rem 0;">' +
'<strong id="itemprice_' + value.Id + '">' +
'<i class="fa fa-inr" aria-hidden="true"></i>' + value.Price +
'</strong>' +
'</td>' +
'<td class="options">' +
'<div class="dropdown dropdown-options">' +
'<i class="icon_plus_alt2"></i>' +
'<div class="numbers-row number" id="item2_' + value.Id + '" data-id="' + value.Id + '">' +
'<input type="text" value="1" class="form-control" name="quantity" id="itemvalue_' + value.Id + '" onchange="getval(' + itemId + ');" readonly>' +
'<div class="inc button_inc plus">' + '+' + '</div><div class="dec button_inc minus">' + '-' + '</div>' + '</div>' +
'</td>' + '</tr>';
}
$("table tbody").append(trHTML);
}
I have a select list and I want to set the selected option based on the value from ajax call, but the select list is not appearing, but everything else will be rendered to the view. The problem is with my if-else statement. Is there a way I can set the selected option based on ajax value without if-else
here is my javascript function:
function FillUserTable() {
$.ajax({
url: "/Home/GetAllUsers",
type: 'GET',
dataType: "json",
traditional: true,
success: function (data) {
$("#EditUserDiv").css("display", "block");
$("#MainPage").css("display", "none");
$("#AllUsersTable2").dataTable().fnDestroy();
$('#AllUsersTable2').DataTable({
paging: true,
processing: true, // control the processing indicator.
retrieve: true,
LengthMenu: false,
responsive: true,
aaData: data,
columns: [
{ "data": "NationalID" ,"title": "هوية المستخدم" },
{ "data": "username", "title": "اسم المستخدم" },
{ "data": "FullName", "title": "الاسم" },
{ "data": "MobileNumber","title": "رقم الهاتف" },
{ "data": "Email","title": "البريد الالكتروني" },
{ "data": "RoleName", "title": "صلاحية المستخدم" },
{ "data": "IsActiveText", "title": "حالة المستخدم" },
{
data: null,
render: function (data, type, row) {
console.log(data.IsActive);
var htmlData= '<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#a'+data.NationalID+'">عرض</button>'+
'<div class="modal fade" id="a'+data.NationalID+'" tabindex = "-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">'+
'<div class="modal-dialog modal-lg" role="document">'+
'<div class="modal-content">'+
'<div class="modal-header">'+
'<h1 class="modal-title" id="test2" style="text-align: right;"> بيانات المستخدم</h1>'+
'<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'</div>' +
'<div class="modal-body">' +
'<form action="" method="post">'+
'<div class="row">' +
'<div class="col-md-6">' +
'<div class="form-group">' +
'<label for="Email" class="control-label">البريد الإلكتروني</label>' +
'<input type="text" id="Email' + data.NationalID + '" name="Email" value="' + data.Email + '" class="control-label"><br />' +
'<label id="lblError'+data.NationalID+'" style="color:red;margin-right: -250px"></label>' +
'</div >' +
'</div >'
if (data.IsActive == 1) {
htmlData = htmlData + '<div class="col-md-6">'
'<div class="form-group">' +
'<label for="IsActive" class="control-label">حالة المستخدم</label>' +
'<select name="IsActive" id="IsActive' + data.NationalID + '">' +
'<option value="2">...</option>' +
'<option selected value="1">نشط</option>' +
'<option value="0">غير نشط</option>' +
'</select>' +
'</div >' +
'</div >'
} else if (data.IsActive == 0) {
htmlData = htmlData + '<div class="col-md-6">'
'<div class="form-group">' +
'<label for="IsActive" class="control-label">حالة المستخدم</label>' +
'<select name="IsActive" id="IsActive' + data.NationalID + '">' +
'<option value="2">...</option>' +
'<option value="1">نشط</option>' +
'<option selected value="0">غير نشط</option>' +
'</select>' +
'</div >' +
'</div >'
}
else {
htmlData = htmlData + '<div class="col-md-6">'
'<div class="form-group">' +
'<label for="IsActive" class="control-label">حالة المستخدم</label>' +
'<select name="IsActive" id="IsActive' + data.NationalID + '">' +
'<option value="2">...</option>' +
'<option value="1">نشط</option>' +
'<option selected value="0">غير نشط</option>' +
'</select>' +
'</div >' +
'</div >'
}
htmlData = htmlData + ' </div > ' +
'<div class="row">' +
'<div class="col-md-6">' +
'<div class="form-group">' +
'<label for="RoleId" class="control-label">صلاحية المستخدم</label>' +
'<select name="RoleId" id="RoleId' + data.NationalID + '">' +
'<option value="0">...</option>' +
'<option value="1">رئيس جهة</option>' +
'<option value="2"> ممثل لجنة</option>' +
'<option value="3">رئيس أو موظف لجنة</option>' +
'<option value="4"> عضو لجنة</option>' +
'</select>' +
'</div >' +
'</div >' +
' </div > ' +
'</form >'+
'</div > ' +
'<div class="modal-footer">'+
'<button id="close' + data.NationalID + '" type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>'+
'<button type="button" onclick="UpdateUserBtn(' + data.NationalID + ')" class="btn btn-primary">تعديل المستخدم </button>'+
'</div>'+
'</div>'+
'</div>'+
'</div >'
return htmlData;
}
},
],
});
},
error: function (xhr, status, thrownError) {
e.preventDefault();
$.notify(
"حدث خطأ أثناء تحميل البيانات, الرجاء المحاولة مرة أخرى",
{
globalPosition: 'top center',
className: 'error'
}
);
}
});
}
when I use console.log(data.IsActive); the values will be correct it is 0 or 1
in your if, else if and else blocks for showing this select, each line like this:
htmlData = htmlData + '<div class="col-md-6">'
you miss a + operator at the end of it! so it's not adding the rest of your html code to the htmlData, just add these +s and it will work fine ...
However, I'd like to recommend you to re-restructure your code and have more small composed pieces instead of doing all of this in one place, also, when you create large strings on multiple lines, consider using (`) backticks instead of (' or ") quotations, it will enable you to get rid of all these +s
I would like to select the content of this element
<div class="entry-content">
comment.body +
</div>
I want to get that comment.body in the function I call below, more precisely in
var body = parent.find('entry-content');
How can I select the content of a certain div? I tried val() and contents() and none of them worked.
Any suggestion?
$("body").on("click", ".show-textarea", function(){
var answerid = $(this).data('answer');
var type = $(this).data('type');
var questionid = $(this).data('question');
var $commentForm = $(this).parent().find('.comment-form').first();
console.log(answerid);
$.getJSON("/controller/api/comments/comment.php", {
answerid : answerid,
questionid : questionid,
type : type
}, function (data) {
$commentForm.find('article').remove();
console.log("AID " + answerid);
console.log("Data" + data.length);
$.each(data, function(i, comment) {
console.log("Comment:" + comment);
$commentForm.append('<article class="tweet-data">' +
'<div class="comment-items">' +
'<div class="qa-c-list-item hentry comment" id="c3574">' +
'<div class="asker-avatar">' +
'<a>' +
'<img width="40" height="40" src="' +
comment.user_photo +
'"></a>' +
'</div>' +
'<div class="qa-c-wrap">' +
'<div class="post-button">' +
'<button name="" onclick="" class="btn icon-flag" title="Flag this comment as spam or inappropriate" type="submit">flag</button>' +
'<button name="" class="btn icon-answers" title="Reply to this comment" type="submit">reply</button>' +
'</div>' +
'<span class="qa-c-item-meta">' +
'commented' +
' 1 day' +
' ago' +
' by ' +
'<a style="display: inline" href="" class="qa-user-link url nickname">' +
comment.username +
'</a> ' +
'<span class="qa-c-item-who-points"> ' +
'<span class="qa-c-item-who-points-pad">(</span><span class="qa-c-item-who-points-data">140</span><span class="qa-c-item-who-points-pad"> points)</span> ' +
'</span> ' +
'</span> ' +
'</span> ' +
'<div class="qa-c-item-content" style="color: #2d2727; font-size: 13px"> ' +
'<a name="3574"></a>' +
'<div class="entry-content">' +
comment.body +
'</div> ' +
'</div> ' +
'<div class="comment-edit-form">' +
'<form method="post" action="/controller/actions/comments/edit_comment.php">' +
'<button class = "edit-comment btn {if !$isMine}hidden{/if}" type="button">Edit</button>' +
'</form>' +
'</div> ' +
'</div> <!-- END qa-c-item --> ' +
'</div>' +
'</div></article>');
});
});
$commentForm.show();
});
$("body").on("click", ".textarea-ok, .textarea-cancel", function(){
commentsFetched = false;
$('.comment-form').hide();
});
$("body").on("click", ".edit-comment", function(){
console.log("Hello");
var parent = $("body").find('article').last();
var body = parent.find('entry-content');
console.log(body);
var parent_parent = $("body").find('article').parent().last();
parent.remove();
console.log(parent);
var button = $(this),
commentField = $('<div class="comment-form">' +
'<form method="post" action="/controller/actions/comments/edit_comment.php">' +
'<textarea name="comment" rows="4" cols="40" class="qa-form-tall-text">' +
body +
'</textarea>' +
'<input type="hidden" name="answerid" value="" />' +
'<input type="hidden" name="questionid" value="" />' +
'<button type="submit" class="textarea-ok">Edit Comment</button>' +
'</form>' +
'</div>'); // create a textarea element
commentField
// set the textarea's value to be the saved content, or a default if there is no saved content
.val(button.data('textContent') || 'This is my comment field\'s text')
// set up a keypress handler on the textarea
.keypress(function(e) {
if (e.which === 13) { // if it's the enter button
e.preventDefault(); // ignore the line break
button.data('textContent', this.value); // save the content to the button
$(this).remove(); // remove the textarea
}
}).appendTo(parent_parent); // add the textarea to the document
});
Since the binding is on '.edit-comment' which is a child of the '.tweet-data' encapsulating each individual entry (from the looks of your logic) I would suggest doing
$(this).closest('.tweet-data').find('.entry-content').text();
Your current logic is going to the last article for the 'parent' element. So if you tried to click the edit comment option on a tweet data other than the last one, your logic will most likely not work. Doing the lookup contextually by which element was clicked will fix this potential issue.
I am creating a dynamic unordered custom List view. In each element, there is one button. I am creating the list elements in the following way:
for (i = 0; i < arrayID.length; i++) {
var listElement = '<li class="has-form">' +
'<div class="row collapse">' +
'<div class="small-1 columns" style="margin: 5px">' +
'<img src="image/twitter.png">' +
'</div>' +
'<div class="small-6 columns small-only-text-center">' +
'<p>' +
'<i>' + arrayText[i] + '</i>' +
'</p>' +
'</div>' +
'<div class="small-3 columns">' +
'<button type="button" class="large-10" onclick="' + onClickViewButton() + '">view</button>' +
'</div>' +
'<div class="small-1 columns">' +
'<input id="checkbox1" type="checkbox">' +
'</div>' +
'</div>' +
'</li>';
$("#myList").append(listElement);
}
The code for button click is:
function onClickViewButton() {
alert('hello');
}
But unfortunately the when the page is loading, the button click is fired and not working on actual button click.
Please help.
Where you have:
onclick="'+onClickViewButton()+'"
you need to have:
onclick="onClickViewButton()"
instead.
Your current code calls the onClickViewButton function in your declaration, when what you really want to do is to just use it as a function reference so it gets called later on onclick.
Try with this snippet:
If you concat function name with parenthesis then it will be treated as function execution hence function will get called.
for (i = 0; i < arrayID.length; i++) {
var listElement = '<li class="has-form">' +
'<div class="row collapse">' +
'<div class="small-1 columns" style="margin: 5px">' +
'<img src="image/twitter.png">' +
'</div>' +
'<div class="small-6 columns small-only-text-center">' +
'<p>' +
'<i>' + arrayText[i] + '</i>' +
'</p>' +
'</div>' +
'<div class="small-3 columns">' +
'<button type="button" class="large-10" onclick="onClickViewButton()">view</button>' +
'</div>' +
'<div class="small-1 columns">' +
'<input id="checkbox1" type="checkbox">' +
'</div>' +
'</div>' +
'</li>';
$("#myList").append(listElement);
}
Yes, that's a chrome's console error that pops up on a click of a button. I think that these errors occur on the basis of the markup but then that's awkward because markup errors should directly come up when the page is loaded but this error comes up on the click of a button.
Here's the important HTML for this question:
<div class="container-fluid">
<script>
var offers = <? php echo PostOffer::GetOffers($_GET["id"]); ?> ;
for (var i = 0; i < offers.length; i++) {
var date = offers[i].Date.split(" ");
document.write('<div class="row-fluid offer">' +
'<div class="span2">' +
'<img class="profile_picture" src="' + offers[i].Picture_Path + '" />' +
'</div>' +
'<div class="span10">' +
'<div class="row-fluid">' +
'<div class="username">' +
'<p style="font-weight: bold;">' + offers[i].Name + '</p>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="content">' +
'<p class="content">' + offers[i].Text + '</p>' +
'<textarea class="hide span12" id="edited_content">' + offers[i].Text + '</textarea>' +
'<button type="button" class="hide btn btn-primary btn-small" id="save_edits" onclick="editPostOffer("<?php echo $_GET["id"]; ?>", ' + offers[i].Offer_ID + ', "aaaaaaaaa")">Save Edits</button> ' +
'<button type="button" class="hide btn btn-primary btn-small cancel_edits">Cancel Edits</button>' +
'</div>' +
'</div>' +
'<div class="row-fluid">' +
'<div class="date">' +
'<p class="pull-right"><strong><span class="muted">Offered on: </span></strong>' + date[0] + '</p>' +
'</div>');
if (offers[i].Username == "<?php echo $_SESSION["
username "]; ?>") {
document.write('<div class="controls pull-right">' +
'Edit ' +
'Delete | ' +
'</div>');
}
document.write('</div>' +
'</div>' +
'</div>' +
'<hr />');
}
</script>
</div>
JS:
$.post("admin/post_offer/edit_post_offer.php", { id: offer_id, text: edited_content }, function (data) {
if (data.status == "success") {
console.log("A");
}
}, 'json');
Can you tell me why that's happening?