ajax - Why onclick doesn't work with checkboxes - javascript

I am currently creating tables and checkboxes using ajax communication.
After it was created, it was confirmed that the checkbox function was working normally,
Even if I include checked while creating it, the onclick function doesn't fire.
success:function(data){
for (var key in data) {
feature = data[key]
head = feature[0].split(" ")
tail = feature[1].split(" ")
type = feature[2]
name = feature[3]
$('#pharmacophore_table').append("<tr>" +
"<td>" + name + "</td>" +
"<td> <label><input type='checkbox' name='ligand_feature' onclick='show_ligand_feature(this, " + '"' + feature + '"' + ");' ></label>" +
"</tr>");
$("input[name='ligand_feature']").attr( "checked", true);
}
},
error:function(data){
alert(data.status)
}
How can I solve this?

I solved it.
Just add click event
complete: function(){
var chck = document.getElementsByName('ligand_feature')
for (var l=0; l<chck.length; l++){
chck[l].click();
}

Related

Add custom object as option inside dropdownlist

I'm having some kind of a bad time where i need to append some json objects as selectlistitems inside a dropdownlist that is different from where i display these json objects.
I managed to retrieve all data, but i dont know how to translate all the information from one kind of element to another. Currently i set up something like this:
All objects that come from my JsonResult method in controller comes like this:
Jsonresult
and the current format for my dropdownlist is as follows:
Dropdownlist selection from controller
For right now I have come to the current state:
i created an array that stores all my objects and convert them to tags, but as i went debugging my array looks like this:
Array from ajax as option tags
My Ajax Request is working as follows:
function GetContratosFiltro() {
$("#id_contrato_aplicativo").empty();
$("#ckSelecionarTdsContratosFiltro").removeAttr("disabled");
var array_sistema = $('#id_sistema').val();
var array_build = $('#id_build_verus').val();
$.ajax({
type: "POST",
url: '#Url.Action("GetContratosFiltros")',
dataType: "json",
//data: "{ 'id_sistema': '" + array_sistema + "'," + "'id_build_verus': '" + array_build + "'}",
data: JSON.stringify({ id_sistema: array_sistema || null, id_build_verus: array_build || null }),
contentType: "application/json; charset=utf-8",
success: function (contratos) {
console.log(JSON.stringify(contratos));
var formoption = [];
content = contratos;
$.each(contratos, function (index, element) {
console.log(element);
var xx = $('<div class="checkbox">' +
'<input value="' + element.id_contrato + '" type="checkbox" name="' + element.contrato + '" class="form-check-input" id="' + index + '" checked>' +
'<label class="form-check-label" for="' + index + '">' + element.contrato + '</label>' +
'</div >');
$('#id_contrato_aplicativo').append(xx);
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " < option value = '" + element.id_contrato + "' id='" + element.id_contrato + "' > " + element.contrato + "</option >";
}
});
array = formoption;
$("#ckSelecionarTdsContratosFiltro").prop('checked', true);
console.log('formoption: ' + formoption);
console.log('array: ' + array);
console.log(content);
},
error: function (ex) {
//alert('Failed to retrieve states.' + ex);
}
});
}
My output on the filter modal is, for example:
Modal filter
On this code: id_contrato_aplicativo is a div where i store all the results from jsonresult query and displays them as checkboxes divs with input and labels, by this bootstrap documentation Checkboxes. My HTML consists into a modal with the filter options with two fields that send information to controller and the main dropdown just gets all information from regular query in controller, but i'm using a custom class called select2 which create the layout for my application and generate the multiselect dropdownlist as a element with each new showing as a block inside dropdown selection, like the image below:
Dropdown result
This code is where i generate all tags for each item from ajax call and below is the function that i am testing right now.
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " < option value = '" + element.id_contrato + "' id='" + element.id_contrato + "' > " + element.contrato + "</option >";
}
$('#btnTransf').click(function () {
console.log('clicou no botão!')
for (var i = 0; i < array.length; i++) {
array[i].appendTo('#id_contrato select');
$('#id_contrato').select();
//appends to select if parent div has id dropdown
//return !$("#id_contrato_aplicativo :checked").remove().appendTo('#id_contrato');
}
//return !$("#id_contrato_aplicativo :checked").remove().appendTo('#id_contrato');
});
UPDATE:
i have managed to locate the correct element and turn out that i only need to pass all elements already formated array variable with all elements as tags inside id_contrato element.
Removed useless info
I've managed to get it to work by making an event bind on a button that gets each element of my array of already formatted objects and with its ids as values from tags.
Array Structure example ( from ajax call):
array = []; //external variable
//put this susccess inside your call from ajax, considering a JsonResult as your controller method
success: function (contratos) {
console.log(JSON.stringify(contratos));
var formoption = [];
content = contratos;
$.each(contratos, function (index, element) {
console.log(element);
var xx = $('<div class="checkbox">' +
'<input value="' + element.id_contrato + '" type="checkbox" name="' + element.contrato + '" class="form-check-input" id="' + index + '" checked>' +
'<label class="form-check-label" for="' + index + '">' + element.contrato + '</label>' +
'</div >');
$('#id_contrato_aplicativo').append(xx);
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " <option value='" + element.id_contrato + "'selected> " + element.contrato + "</option>";
}
});
array = formoption;
$("#ckSelecionarTdsContratosFiltro").prop('checked', true);
console.log('formoption: ' + formoption);
console.log('array: ' + array);
console.log(content);
}
Code:
$('#btnTransf').click(function () {
console.log('test to check if click successful!')
$.each(array, function (index, element) {
console.log(element);
$('#id_contrato').append(element);
$('#id_contrato').select();
});
});

Calling a function in dynamically created button javascript

I'm trying to create a button with a an onClick that calls a function with the signature deleteEntry(entry). However, I get an error saying that entry is undefined even though I am using it in the same function. I tried adding escape characters but it does not have any effect. Any ideas?
function addToTable(entry) {
var result = "<tr>"
result += "<td>" + entry.id + "</td>";
result += "<td>" + entry.title + "</td>";
result += "<td>" + entry.url + "</td>";
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry +
")\">Delete</button></td>";
result += "</tr>";
$("#table").append(result);
}
You can create the button as a jQuery object and use the on method to listen to the click event. Then when the event listener is attached append the button to the row like the other elements in the function.
Check the code snippet below to see it in action.
// Dummy entry.
var entry = {
id: 0,
title: 'test',
url: 'http://url.com'
}
// Your AJAX call.
function deleteEntry(entry) {
console.log(entry);
}
function addEntryToTable(entry) {
var $id = $('<td>' + entry.id + '</td>');
var $title = $('<td>' + entry.title + '</td>');
var $url = $('<td>' + entry.url + '</td>');
var $button = $('<button class="btn">Delete</button>');
var $buttonWrap = $('<td></td>');
var $row = $('<tr></tr>');
// Add 'click' event listener to the button.
$button.on('click', function(event) {
deleteEntry(entry);
});
$buttonWrap.append($button)
$row.append($id, $title, $url, $buttonWrap);
$('#table').append($row);
}
addEntryToTable(entry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table"></table>
If you inspect this button you generated it will probably have the following attribute: onClick="deleteEntry([object Object])
I think what you want is:
result += "<td><button class=\"btn\" onClick=\"deleteEntry(" + entry.id + ")\">Delete</button></td>";
I guess you have a list variable "entries" somewhere.
In the delete function you can find the clicked entry with the inputed Id.

Copy a row of data to the textfields of same page on selecting a row through radio button

Dynamically generating rows by jquery
$("#showbtn").on("click", function() {
var tblRow;
$.getJSON('multimob.action', $("#mobileno").serialize(), function(data) {
if (data.mobileno === null) {
alert("Wrong Mobile No.,please Check");
} else {
$.each(data.ls, function(index, value) {
var count = index;
tblRow = $("<tr><td> <input type='radio' id='chk' name='chk' onclick='copyrecord('" + count + "');'/></td><td id='fidrow" + count + "'>" + value.id + "</td>"
+ "<td>" + value.name + "</td>" + "<td>"
+ value.mobileno + "</td>" + "<td>" + value.addres + "</td></tr>");
alert(count + tblRow.toString());
$("#farmTable tbody").append(tblRow);
});
});
The data rows are dynamically created ,Once I select the radio button, it should take the data from that row and it has to be copied to the textfields in the same page .
Help me to get rid of this iisue.
Try this example
Use class
<input type='radio' id='chk' name='chk' class="chk"/>
HTML
$(document).on('click','.chk',function(){
var text=[];
$(this).parents('tr').find('td:not(:first)').each(function(){
console.log($(this).text())
text.push($(this).text())
});
$('#name').val(text[0]);
$('#no').val(text[1]);
$('#add').val(text[2])
});
DEMO
As per your comment: I can change the id and name as 'chk"+count+"' something like this. But how can I copy the row data on selecting the row by radio button
You can get it this way:
$("#farmTable").on('change', '[id^="chk"]', function(){
var tblVals = $("#farmTable tr").map(function(){
return $(this).find('td:not(:first)').text();
});
console.log(tblVals);
});

Removing row refresh page jquery

I am facing an issue with my jquery. I have used jQuery to add controls to table, along with a remove button to remove that particular row in table. here is my code on how i am creating controls in table.
HTML
<table id="controls" cellpadding="10" cellspacing="10">
</table>
<input id="btnAdd" type="button" value="Add" />
my jquery code looks like this
jquery
$(document).ready(function() {
$("#btnAdd").click(function() {
var field = $("#field").val();
var year = new Date().getFullYear()
var DDL_fromProfession = "<select name='ParametersFromProf' id='DDL_FromProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToProf' id='DDL_ToProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_ToProfession += "</select>";
var newRow1 = "<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
var input = "<input name='parameters' id='field' type='text' />";
var input1 = "<input name='parametersCompany' id='field' type='text'/>"
//var inputCurrent="<input name='Current' id='Currfield' type='hidden'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " + input1 + "</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
to remove last row i am using.
jquery
$(document).ready(function() {
$("#controls").delegate("#btn_rmv", "click", function() {
$(this).closest("tr").remove();
return false;
});
});
clicking on remove button refresh the page and remove all the rows that i have added instead of last one.
NOTE: What i ahve digged out is .delegate is server side and it refresh the page. i am unable to remove last row with $("#btn_rmv").click(function() on my page
Please point me to right direction.
Thanks in advance
The code in question does not work as k is not defined, as used in the line
value='" + k + "'
If this error is corrected then the next problem is that you are creating multiple elements with the same id, as seen here
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
which in invalid HTML and will cause problems for jQuery in finding the element with the unique id.
By changing k for 0 and changing the id to a class, the remove code will only remove the current row with the button on. I assume that you really want to remove that row and also the preceding 2 rows.
$('#controls').delegate('.btn_rmv', 'click', function() {
var index = $(this).closest('tr').index() + 1 // as nth-child is 1-based indexing
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove(); // remove 3 rows
return false
});
See demo
Please note that since jQuery 1.7, .delegate() is superseded by .on() so the updated function is:
$('#controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 1
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove();
return false
});
I had a similar experience: I was using Google Chrome and it would refresh the page everytime I called a function. You will have to return false. My problem was when I called a function from an element using "onclick". When I called the function from onclick I had to include the "return false;":
onclick="return false; functionName()"
Try this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
return false;
});
});
Or this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
});
return false;
});
Sorry my Javascript is not very good :(
You can do it in this way..
var RowCount = 0;
$(document).ready(function() {
$("#btnAdd").click(function() {
RowCount = RowCount + 1;
var newRow1 = "<tr id='tr" + RowCount + "'><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv' onclick='RemoveRow(" + RowCount + ")'>Remove</button>";
});
});
function RemoveRow(RowID) {
$('#RemoveRow' + RowID).remove();
}
It looks like you are hooking up the remove click handler on $(document).ready.
On document.ready, the remove buttons do not yet exist (since they are generated dynamically when clicking 'Add', after the document.ready code has run). That's why $("#btn_rmv").click(function()... is not working.
So, after dynamically inserting a remove button in the $("#btnAdd").click event, you explicitly have to add a click handler to it.
EDIT:
If you generate your remove buttons with a unique id (eg. btn_rmv_1, btn_rmv_2, etc), you can add the following to your Add-handler (after appending the new button to the DOM):
$('#btn_rmv_1').click(removeButtonFunction);

how to store array data in table?

I wanted the user to enter any alphabet in a text field, when he/she clicks on the Find! button, it will go through my php file and find a list of words that start with that alphabet (of course it's only a limited amount of words). And I want to output it to a table, with 5 columns, each cell containing one word.
Something like this:
in my HTML:
<label>
Enter any alphabet:
<input name="alphabet" type="text" id="alphabet"></label>
<input type="button" value="Find!" id="goFind">
<table border="1" id="output">
</table>
and Javascript:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var bunchOfWords = function (data) {
var listOfWords = "";
if(!Array.isArray(data)) {
return false;
}
else {
for(i = 0; i < data.length; i = +5) {
listOfWords += "<tr><td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td></tr>";
}
}
};
$("#goFind").click(function () {
var theWord = $("#alphabet").val();
$("#output").html("Loading..."); //gives the user an indication that it's loading
$.getJSON("wordslookup.php", "startswith=" + theWord, listOfWords);
});
});
Can't seem to figure out what's wrong.
listOfWords is out of scope in $.getJSON also its not a function, you should pass bunchOfWords to $.getJSON instead. To put the data in the table simply replace the current inner html, $("#output").html(listOfWords);

Categories

Resources