How to pass a variable selector to jquery .attr() - javascript

This is the scenario. In a jQuery DataTable I have some value and an edit button to modify 2 of them; clicking on it, a modal popup is opened and offer a form to insert the new value for notes and status:
...
"columnDefs": [
{
"targets": [ 0 ],
"visible": false
//"searchable": false
}],
"columns": [
{ "data": "id" },
{ "data": "date" },
{ "data": "type" },
{ "data": "name" },
{ "data": "user_name" },
{ "data": "status" },
{ "data": "closing_date" },
{ "data": "info" },
{ "data": "note" },
{ "data": null,
"render": function ( data, type, full, meta ) {
return "<button type='button' class='btn btn-info btn-md' id=\'" + full.id + "\' data-toggle='modal' data-id=\'" + full.id + "\' data-target='#myModal'> Edit </button>";
}
...
Immediately below, I have the ajax function to send the inserted value to a Spring controller:
//This function is used to send the form data to Spring controller; cause we use a modal, with code that must be put in the file with html table head,
//we must replace the use of view made by jsp using an ajax function
$('#myModal').on('click', '.btn.btn-success', function(event) {
var form = $('#updateeventsform'); //recover the form inside modal by using id
var formdata = form.serializeObject(); //use the serializeObject function to prepare data for Json format
formdata.idevent = $(this).attr('data-id'); //add the event id to form data, after setting it with the IDnumber variabile
console.log(formdata, this);
event.preventDefault();
//here starts the code to sending data to Spring controller
$.ajax({
url: "../updateevents.json",
type: "post",
data: formdata,
success : function() {
console.log("Invio riuscito.");
DTevents.ajax.reload( null, false ); //we reload the table, showing immediately the data updated.
}
});
});
This code give me an undefined value on formdata.idevent; and it's right, because the $(this) value refers to the current element (in my case, the submit button).
As you can see, the id for the button is a numeric value, setted with the full.id field.
So, I've got a try: put a numeric value as selector for attr() function. I changed:
formdata.idevent = $(this).attr('data-id');
in
formdata.idevent = $('#5').attr('data-id');
and this works.
So, the question is: is there a way to use a variable value as selector for the .attr() function? If no, what should I use to pass the correct value to the controller?
Edit for comment answer.
Already used $(this).data('id'); does not works. I got undefined values for idevent.
<button type='button' class='btn btn-info btn-md' **id=\'" + full.id +**
here you can note the numeric id of button element.
The intent is: this table represent events. When the 2 fields modified, notes and status, must be send to the controller, i Must send also the events id to it and i want perform this with the use of .attr() function.
Now, this function must be used on a selector; i may want use the button id as selector but I have different button with different id. So, if i click the 4th button, the id is 4 and I may have:
formdata.idevent = $['#4'].attr('data-id');
if I click the 5th button the code must be:
formdata.idevent = $['#5'].attr('data-id');
if I click the 6th button:
formdata.idevent = $['#6'].attr('data-id');
and so on. So, I have a variable selector to use; I don't know how to perform this.

I would try to add an hidden input to the modal...
<input type="hidden" id="idevent" name="idevent">
And on a "Edit" button click, carry its id to the modal form:
$(".btn.btn-info").on("click",function(){
var idevent = $(this).data("id"); // Or $(this).attr("id")
// Delay for the modal openning animation...
setTimout(function(idevent){
$('#myModal form #idevent').val(idevent);
},800);
});
Then, the info would already be in the form when user submits it.;)

Related

how to Disable / Enable button in datatable

I want to check the Article's Status, if true the Edit button will be disabled else the user can click and switch to the Edit page. How to use it?
return ' Edit ';
}}
],
order: [1, 'asc']
});
The column render function you are using:
render: function (data) { ... }
is capable of accessing all the data in the current row. Its full signature is:
render: function ( data, type, row, meta ) { ... }
So, you can use the row parameter to access other columns in that row, such as row.status:
{
data: 'id',
className: "center",
title: 'Actions',
render: function (data, type, row, meta) {
if (row.status === true) {
return ' Edit ';
} else {
return '<a href="Student/EditArticle/' + data + '" class="btn btn-success mr-1" disabled> Edit </a>';
}
}
}
You can see further details and examples here.
It is worth looking at why the type parameter is provided and how it is used. It basically helps you to provide multiple versions of a value - one value for the table display (the HTML link); a different value for sorting; another value for filtering, and so on.
So, for example, for your clickable link, you may prefer the sort and filter values to be simply the data value (without any of the extraneous HTML).
But this is completely optional - you don't have to use it. See orthogonal data for more info.
Update:
I forgot that a hyperlink cannot be disabled in the same way as a button (so you cannot use "disabled"). Instead, you can look at these approaches, or do what TimRoberts suggested in your question's comments. Having said that, the render function with the row parameter should be what you need.
else {
return 'Edit'; // or, alternatively: return ''
}

Kendo Combo Box Scroll: automatically call function

I am new to Kendo and creating a project using it. I have encountered a very unique kind of problem. I am using select options in kendoCombox. What I am doing is that I am just updating the select box value on click of the edit button. The value is updated successfully but when I scroll, it automatically calls the function where I get all values. Here is my code:
I am updating the value using this:
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
<select class="span12" onchange="rackChange()" id="rackModelName" name="rackModelName"
tabindex="6">
</select>
The below function automatically calls on scroll change:
function getRackFun(libraryDeviceId,dataCenterId,type){
console.log("calling");
if(libraryDeviceId && dataCenterId){
$.ajax({
type : "GET",
dataType : "json",
url : "${getRacksByLocationId}&libraryDeviceId=" + libraryDeviceId+"&dataCenterId=" +dataCenterId,
success : function(result) {
if(result.length>0){
var jsonObject = jQuery.parseJSON(JSON.stringify(result));
$("#rackModelName").data("kendoComboBox").setDataSource(jsonObject);
}else{
if(type!="edit"){
$("#rackModelName").data("kendoComboBox").value("");
$("#rackModelName").val("");
$("#rackModelName").data("kendoComboBox").setDataSource([]);
$("#rackStartUnit").empty();
$("#rackStartUnit").append($('<option>',{
value : '',
text : '<liferay-ui:message key="inventory.please_select"></liferay-ui:message>'
}));
$("#rackEndUnit").val('');
}
}
}
});
}else{
$("#rackModelName").data("kendoComboBox").value("");
}
}
change the way you initialize the combobox to
$("#rackModelName").kendoComboBox({
...
change: rackChange, //your change function name
...
});
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
remove the on change from the html element
To know more about events trigger check this https://demos.telerik.com/kendo-ui/combobox/events

How to change the value in the input field while we click on dynamically created edit icons?

Here in the code there is ajax which assigning the values to the fields but there is the edit icon which is created dynamically it means that how many address you added in the database then number of times edit icon will be created. My need is that when I click on first button then it will alert its id value and when I clicked on the other one then it will alert its id value
Following is my code I tried:-
var full_url = document.URL; // Get current url
var url_array = full_url.split('=') // Split the string into an array with / as separator
var UserId = url_array[url_array.length-1]; // Get the last part of the array (-1)
$.ajax({
url:"url,
type: "GET",
dataType: 'json',
async: false,
data:{"UserId":UserId},
success: function(response){
if (response.response.total_record[0].status === "active") {
$('#email').html(response.response.total_record[0].email);
$('#name').html(response.response.total_record[0].first_name+" "+response.response.total_record[0].last_name);
$('#first').val(response.response.total_record[0].first_name);
$('#last').val(response.response.total_record[0].last_name);
$('#phone').val(response.response.total_record[0].phone_number);
$('#alternative').val(response.response.total_record[0].alternative_number);
$('#id').val(response.response.total_record[0]._id);
$('#status').val(response.response.total_record[0].status)
if (response.response.total_record[0].status === "active") {
$('#activate').hide();
}
if (response.response.total_record[0].status === "deactivate") { $('#activate').show();
$("#deactivate").hide();
}
$.each(response.response.total_record[0].address,function(i,item){
console.log(response.response.total_record[0].address[i])
$('#edit_id').val(response.response.total_record[0].address[i]._id)
$('.cards').append('<div class="location-list"><header class="header_title"><div class="location_heading"><h3>Location:</h3></div><div class="edit_icon"><a class="editByAnchor" id='+response.response.total_record[0].address[i]._id+' href="#" data-toggle="modal" data-target="#edit_address"><i class="fa fa-edit"></i></a></div></header><div id="dAddress" class="location-detial"><p><span id='+response.response.total_record[0].address[i]._id+'>'+response.response.total_record[0].address[i].address+'</span></p></div></div>');
});
}
}
});
Html
<input type="hidden" id = "edit_id" value= "">
Jquery for finding the clicked
$('.editByAnchor').change(function() {
alert("You just clicked checkbox with the name " + this.id)
});
Produces the output
<a class="editByAnchor" id="1" href="#" data-toggle="modal" data-target="#edit_address"><i class="fa fa-edit"></i></a>
/*more like this but id will be change base on the dynamically fields*/
The above output anchor tag having id attribute it will assigned dynamically as you see my code so how will I get the id attribute of each icon by clicking them.
For dynamically created element use on(). Also you have to use click event instead of change:
$('.editByAnchor').on('click', function() {
alert("You just clicked checkbox with the name " + this.id)
});
By taking the reference of this link I post a answer for this everything is alright I have to change my code by following
$(".editByAnchor").click(function(){
var id = this.id;
alert(id)
});

How to render HTML with jQuery from an AJAX call

I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html

Not able to set form attribute value after post it

I've the form and it looks like :
<form method="POST" action="create.php" data-id="0" class="postForm">
<input type="hidden" id="#formId" value="1">
<textarea class="formBodyText"></textarea>
<button type="submit">Post</button>
</form>
The ajax call for this form is as :
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
$.post("create.php",{'formId':$("#formId").val(),'formBodyText':$(this).find('.formBodyText').val()},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
$(this).attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
the problem is with $(this).attr("data-id",data); , it's not setting the new value for the form.
what wrong with this code??
Try,
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
var cache = $(this); // get the form object here and use that inside of $.post
$.post("create.php",
{'formId':$("#formId").val(),
'formBodyText':$(this).find('.formBodyText').val()
},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
cache.attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
this inside the ajax handler does not refer to the submitted form, you can use a closure variable like $form as shown below to fix this.
$(document).on("submit", ".postFrom", function (event) {
event.preventDefault();
var $form = $(this);
$.post("create.php", {
'formId': $("#formId").val(),
'formBodyText': $(this).find('.formBodyText').val()
}, function (data) {
console.log("Return : " + data); //working fine , I mean getting expected result
$form.attr("data-id", data); // want to set the return data as form data-id attribute value
});
});
jQuery.ajax()
The this reference within all callbacks is the object in the context
option passed to $.ajax in the settings; if context is not specified,
this is a reference to the Ajax settings themselves.

Categories

Resources