Jquery & Javascript Code snippet might be helpful for you

by in Jquery Javascript


Jquery & Javascript Code snippet might be helpful for you.

1. Onclick event

Method 1:

<button type=”button” onclick=”clickTest()”>Click</button>

function clickTest() {
// code …
}

 

Method 2:

$(‘.btn-delete’).on(‘click’, function () {
// code …
});

=> should work fine, no problem. But if the onclick button is in the result of another function, the following Ajax example:

 

$.ajax({
url : ‘…’,
type : ‘post’,
dataType : ‘text’,
data : {id: id},
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”token”]’).attr(‘content’)
},
success: function (result) {
// console.log(“result: “, JSON.parse(result));
var html = ”; var iteration = 0;
if (result) {
var result = JSON.parse(result);
result.forEach (function (item, index) {
if (item[‘id’] && item[‘name’]) {
iteration = index + 1;

html += ‘<tr><td class=”text-center”>’ + iteration + ‘</td>’;
html += ‘<td class=”text-left”>’ + item[‘name’] + ‘</td>’;
var btnDelete = ‘<td class=”text-center”><button class=”btn btn-danger btn-s btn-delete” data-title=”Delete” data-toggle=”modal” data-target=”#delete”‘;
btnDelete += ‘data-id=”‘ + item[‘id’] + ‘”‘;
btnDelete += ‘><span class=”glyphicon glyphicon-trash”></span></button></td>’;

html += btnEdit;
html += btnDelete;

html += ‘</tr>’;
}
});
}
html = (html) ? html : ‘<tr><td colspan=”6″>Data not found.</td></tr>’;
}
});

 

In this case, when you catch the on click on btn-delete button, you cannot use the above method, replace it with the following code:

$(document).on(‘click’,’.btn-delete’,function() {
$(‘#delete .id’).val($(this).data(‘id’));
});

 

2. jQuery closest() Method

<div class=”col-md-12″>
<div class=”col-md-6″>
<div class=”col-md-6″>
<div class=”col-md-6″>
<span>Heading</span>
<button type=”button” class=”btnColor”>Button</button>
</div>
</div>
</div>
</div>

 

<style>
.col-md-6{border: 1px solid green; padding: 5px};
</style>
<script>
$(document).ready(function(){
$(“.btnColor”).closest(“div”).css({“color”: “red”, “border”: “1px solid red”, “padding”: “5px” });
});
</script>

 

js-closet-method-result-example

Result

 

3. Callback function jquery ajax:

$(‘.btn_check’).on(‘click’, function () {
var url = ‘…’;
var datas = {‘…’: ‘…’, ‘…’: ‘…’};

saveDataByAjax(url, datas, loadData);
});

// Callback function
function loadData(result){
console.log(result) // then execute this line
}

function saveDataByAjax(url, datas, callback) {
$.ajax({
url : url,
type : ‘post’,
dataType : ‘text’,
data : datas,
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”token”]’).attr(‘content’)
},
success : function(result) {
// console.log(“result”, JSON.parse(result));
callback(result);
},
error : function(error) {
console.log(“error: “, error);
}
});
}

Tags: , , , , , , ,