jquery onchange function is not calling - javascript

i have the following piece of code:
function teamAuswaehlen() {
$.post("Auswahl_Abteilung?_=" + new Date().getTime(), function(data) {
eintraege = "<div class='col-md-12 col-xs-12'>" +
"<div class='form-group'>" +
"<select class='form-control' id='teams' title='Wählen Sie hier ihre Teamansicht'>"
if (data.length > 1) {
$("#kalenderAuswahl .modal-body").empty();
$.each(JSON.parse(data), function(key, value) {
eintraege += "<option id='" + value.Team_ID + "'>" + value.TE_Kurzbezeichnung + "| " + value.TE_Langbezeichnung + "</option>";
});
eintraege += "</select>" +
"</div>" +
"</div>";
}
if (data.length > 1) {
$("#kalenderAuswahl .modal-body").append(eintraege);
$("#kalenderAuswahl").modal("show");
}
}).done(function() {
$("#teams").change(function() {
getId(this);
});
});
}
The Modal is build dynamicly at the start of the programm.
So the onchange event i want to call if a user change the select box is store in the done block.
But if i trie the code, nothing happens so the onchange event is not fired.
So how can i handle that ?

Here is code snippet for your change event.
$('body').on('change', '#teams', function(e) {
e.preventDefault();
// do your stuff
});
You can write this change event code in below section
Before body tag end Or
You can write in $(document).ready(function() {})

you can remove done method and paste your code to body.
select event with body tag as like $('body').on('change', '#teams'
or
just use like this $('body').on('change', '#teams' in done method.

No need to place code in done().place the following code anywhere in tag
$(document).on('change','#teams',function() {
getId(this);
});

Related

How to append data for each div separately

Simple but I dont know how to do it. I am trying to append data for each div separately $. Each function is looping and assigning whole data to the same div.
These are my two div.
<div class="div1">
<div class="div2">
// whole javascript code is here
</div>
</div>
The whole code is something like this:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData += item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/> ";
});
$(".div2").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
return false;
});
});
Div1 contains outer CSS for that particular div2. I want to generate multiple div2 for each data returned from the server. I have tried using return false but still same result. Please tell me how to do it.
This may help you. I have change the code to make it simple.
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
//make parent div blank
$(".div1").html("");
$.each(data, function (i, item) {
//make html for div2
var html += "<div class='div2'>";
html += item.PostedByName;
html += "<img src='" + item.PostedByAvatar + "'height='100' width='100'/>"
html += "</div>";
//append all div2 to parent div1
$(".div1").append(html);
});
});
});
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData +="<div class='div2'> item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/></div> ";
});
$(".div1").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
//return false;
});
});

JQuery PHP & Contenteditible

I am having a problem updating a database field via jquery and php with contenteditible. The ajax.php file just takes my input from the form and updates the database when the user clicks away but for some reason I can never hit the $("td[contenteditable=true]").blur(function(). Is it because I am displaying the html from the js file? If so how can I get the .blur() to run this way?
Here is a snip of my php.
<div id="status"></div>
<div class="row">
<div id="html"></div>
</div>
My js file
$(function(){
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('ajax.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},3000);
}
});
});
//snip
});
function updateTable() {
//snip
$.post("controller.php", payload, displayTable);
}
function displayTable(data){
var obj_defect = $.parseJSON(data);
//snip
html += '<thead><tbody>';
for(i=0; i<obj.length; i++) {
html +='<tr>';
html +='<td width="10%">' + obj[i].row1 + '</td>';
html +='<td width="10%">' + obj[i].row2 + '</td>';
html +='<td width="10%">' + obj[i].row3 + '</td>';
html +='<td width="10%">' + obj[i].row4 + '</td>';
html +='<td id="row0:'+obj[i].id+'" contenteditable="true"> ' + obj[i].row5 + '</td>';
html +='</tr>';
}
html += '</tbody></table>';
} else {
html = '<h4>No results found</h4>';
}
}
$("#html").html(html);
}
Your listener must run AFTER the element exists. You currently create the contenteditble td row after you receive the data from your post, which means when you go to assign a listener at page load there is no object in existence yet.
Something like this should work:
$.post("controller.php", payload, displayTable).done(function() {
// now create listener on td[contenteditable=true]
});

function called on page load while it must be called on onclick only

Here I want to call updateRecord("+n+") function on click Update button
here res.data is the response from ajax. But when the page loads the updareRecord called itself. Following code is written in js file. and on click getting following error:
Uncaught SyntaxError: Unexpected identifier.
I request to mention exact point if you don't understand any point of question instead mark it negative.
$.map(res.data,function(n,i){
if (n['type'] == 1)
html += "<tr><td>"
+ n['locationName']
+ "</td><td>"
+ n['categoryName']
+ "</td><td>"
+ n['day']
+ "</td><td>"
+ n['status']
+ "</td><td><input type='button' onclick = '"+updateRecord(n)+ "' value='Update'/></td></tr>";
});
Because you are calling the function already when callback function is called.
This happens right here on this line:
+ "</td><td><input type='button' onclick = '"+updateRecord(n)+ "' value='Update'/></td></tr>";
You call first updateRecord(n) and then append the return value to the text.
I would avoid adding events to DOM directly, but rather use something like this:
var button = $('<input type="button" value="Update" />');
button.click(function(event) {
updateRecord(n);
}
The problem is, that you call the method:
html += "<input type='button' onclick = '"+updateRecord(n)+"' ...";
/* like this you execute the method directly,
like any other function call in javascript */
In case you'll write it like this:
html += "<input type='button' onclick = 'updateRecord("+n+")'...";
/* like this it is a string, and will be
interpreted by the javascript click eventhandler
after adding the html string to the DOM */
It could work as expected, but the problem is, that you'll want to set an array/ object as parameter, which will cause an javascript error. To avoid that you could also do something like this:
$.map(res.data,function(n,i){
if (n['type'] == 1) {
html += "<tr><td>" + n['locationName'] + "</td><td>" +
n['categoryName'] + "</td><td>" + n['day'] + "</td><td>" +
n['status'] + "</td><td>" +
"<input class='update-button' data-value='"+
/* since n is an associative array, will need
to stringify in a special way */
JSON.stringify(n).replace(/'/g, "\\'")
+"' type='button' value='Update'/></td></tr>";
}
});
/* bind an click event to all .update-button elements,
whenever these elements will be appended to the DOM */
$(document).on('click','.update-button',function() {
updateRecord($(this).data('value'));
});

can not get the changed attribute using jquery

I fetched the data from remote sever, and appended different rows to the table, now, I want to get all the checked box data and do further treatment, like when tick the box, then the data will be pushed to an array, and remove the element from that array when tick off the check box. so now, the question is, i can not select the checked box which the attribute was changed after appending work, the core code part is:
$row.find('input[ischecked="unchecked"]').on('click', function(){
$(this).attr('ischecked','checked'); // it works here
if($.inArray(this.value, tickedArray) === -1){
tickedArray.push(this.value);
}
console.log('checked');
});
// it can not get the ischecked="checked"
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
and the full code here:
$(function(){
var url = some url;
var tickedArray = [];
$.ajax({
url: url,
type:'GET',
xhrFields: {
withCredentials: true,
},
success:function(data){
$.each(data.stories, function(index, value){
var $row = $("<tr>" +
"<td><input type='checkbox' value="+ value.id +" ischecked='unchecked'></td>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"</tr>");
$row.find('input[ischecked="unchecked"]').on('click', function(){
$(this).attr('ischecked','checked');
if($.inArray(this.value, tickedArray) === -1){
tickedArray.push(this.value);
}
console.log('checked');
});
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
$('#stories_list_table > tbody:last').
append($row);
});
}
});
});
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
This selector won't find any checkbox because there aren't any at that moment. Instead of creating 2 click events you should only create 1 change event and check the ischecked attribute for it's value.
Also, why do you create your own ischecked attribute instead of using the standard checked property?
I think you can try using event delegation, like this :
$row.on('click', 'input[ischecked="checked"]', function(){
console.log('unchecked');
});

Call a javascript function inside a dynamic row Jquery

Good day guys. I am trying to implement onclick function in a dynamically created table in jQuery. But each time I click the button, I get this error
(Unexpected token ILLEGAL)
in my console.
But when I click on the error, there's no code on the line it's pointing to.
Here is the code :
$(document).ready(function(){
var tbl="";
$.getJSON('./libs/form.php',function(result){
console.log(result);
$.each(result,function(key,val) {
if($.isNumeric(key)){
var mail=val.Email;
tbl+="<tr class='odd gradeX'> ";
tbl+="<td>" + val.Name + "</td>";
tbl+="<td>"+ val.Email +"</td>";
tbl+="<td>"+ val.Gender +"</td>";
tbl+="<td>" + val.Qualification + "</td>";
tbl+="<td>" + val.Experience + "</td>";
tbl+="<td>" + val.Note + "</td>";
tbl+="<td><a onclick='javascript:call(" + mail +");' class='btn btn-success btn-small'><i class='icon-edit icon-white'></i>" + "EDIT" + "</a></td>"
tbl+="</tr>";
}
});
$("#applicantstbl").append(tbl);
$("#applicantstbl").dataTable({
"bJQueryUI":true,
"sPaginationType":"full_numbers"
});
});
});
Please I'd like to know what am I doing wrong, it displays the table perfectly. Just the onclick function.
Here is the function am trying to call :
<script>
function call(name)
{
alert("Called"+ name);
}
</script>
Try changing
".....onclick='javascript:call(" + mail +");'...."
to
".....onclick='javascript:call(\"" + mail +"\");'....."
Try it like,
$('#applicantstbl').on('click','.mail-link',function(e){
e.preventDefault();
call($(this).data('email'));
});
Add a class mail-link to your html link like,
tbl+="<td><a data-email='"+mail+"' class='mail-link btn btn-success btn-small'><i class='icon-edit icon-white'></i>" + "EDIT" + "</a></td>"
change name of function call to something else may callFun.
<a onclick='javascript:callFun(\"" + mail +"\");'>mail</a>
or alternate is
<a emailId='" + mail +"'>mail</a>
$('#applicantstbl').on('click','.btn-small',function(e){
e.preventDefault();
callFun($(this).attr('emailId'));
});

Categories

Resources