error call data with javascript onclick - javascript

I have created a javascript function, and the function is contained within the onclick function in the html code. when the variable "data.nik" called with a value 10.34.099 or "10AXMN.09" onclick function is not functioning properly and displays an error message. if "data.nik" worth 101011 then the onclick function can be run well.
The following javascript code
function tabelListPegawai(data){
var statusPegawai;
if (data.status==1){
statusPegawai = 'Karyawan Tetap';
}else if(data.status==2){
statusPegawai = 'Karyawan Tidak Tetap';
}
return baris = $("<tr>\
<td>"+data.nik+"</td>\
<td>"+data.nama_pegawai+"</td>\
<td>"+data.nama+"</td>\
<td>"+data.nama_jabatan+"</td>\
<td>"+statusPegawai+"</td>\
<td style='text-align: center;'>\
<a class='btn btn-small aksi_atas' rel='tooltip' title='Ubah' onclick='editPegawai("+data.id_pegawai+")'><i class='icon-edit'></i></a>\
<a class='btn btn-small aksi_atas' rel='tooltip' title='Hapus' onclick='hapusPegawai("+data.id_pegawai+", "+data.nik+")'><i class='icon-remove'></i></a>\
</td>\
</tr>");

You should insert the quotes around the argument
onclick='editPegawai(\""+data.id_pegawai+"\")'>

Related

How to pass parameters in onclick function of generated html

In my controller code contain html code in appened form.When i pass the parameters to the onclick function, I didn't get the parameters in the corresponding function.
controller
foreach ($cart as $item){
$row_id = $item['rowid'];
// $count++;
$output.='
<tr>
<td>'.$item['name'].'</td>
<td>'.$item['price'].'</td>
<td>'.$item['qty'].'</td>
<td>'.number_format($item['subtotal'],2).'</td>
<td> <i class="zmdi zmdi-close"></i></td>
</tr>
';
}
script
function remove(row_id)
{
alert(row_id);
}
Onclick function remove(), alert is not working
your old code is producing
<td> <i class="zmdi zmdi-close"></i></td>
which is an incorrect HTML
just replace this
onclick="remove("'.$row_id.'")"
with this
onclick="remove(\''.$row_id.'\')"
see a demo : https://eval.in/830107
onclick="remove("'.$row_id.'")"
Will result in:
onclick="remove("123")"
See where its going wrong? Onclick now contains only the portion remove(, because than a double quote termintes the onclick content.

How to concat #Url.Action with jquery syntax

I'm using bootstrap datatables to create a column displaying a link button to redirect to another view, the problem is that I'm getting syntax error from jquery and I'm not beign successful fixing it.
Here is the relevant part where I get the syntax error:
return '<button type="button"class="btn btn-default" onclick="location.href='#Url.Action("IncidentesDetalle", "ServiciosController", new { Id = "1" })'"><i class="fa fa-eye"></i></button>'
Any help will be appreciated.
I guess you should change your string to:
return '<button type="button" class="btn btn-default" onclick="location.href=\'#Url.Action("IncidentesDetalle", "ServiciosController", new { Id = "1" })\'"><i class="fa fa-eye"></i></button>'
Because in your original code single quotes just closed after href= and opened before ><i again. So part of the returning string like #Url.... became just invalid code. Hence the error.
Try this, it will work:
string path = "'#Url.Action('IncidentesDetalle', 'ServiciosController', new { Id = '1' })'";
return "<button type='button' class='btn btn-default' onclick='location.href="+path+"'><i class='fa fa-eye'></i></button>";

How to add variable to a href

I want to do something like this
var myname = req.session.name; <------- dynamic
<a href="/upload?name=" + myname class="btn btn-info btn-md">
But this does not work. So how do I properly pass in a dynamic variable to href? <a href="/upload?name=" + req.session.name class="btn btn-info btn-md"> does not work either
Actually there's no way to add a js variable strictly inside DOM. I would suggest you to apply an id attribute to that a element, refer to it and apply given variable as a new href attribute.
var elem = document.getElementById('a'),
myname = 'req.session.name'; //used it as a string, just for test cases
elem.href += myname;
console.log(elem.href);
<a id='a' href="/upload?name=" class="btn btn-info btn-md">Link</a>

Pass Anonymous function that requires a parameter, to another function as an argument which will be assigned to an onclick

I have a function that I want to reuse throughout my program. Basically it's a bootstrap dialog box that has a confirm and a cancel button. I setup the helper function to accept two anonymous functions, one for the cancel and one for the confirm. I have everything working except I am not sure how to properly assign it to the onclick when building the html. I want to avoid using a global variable but this is the only way I was able to get this to work.
Custom function:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + cancelFunc + ')()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + confirmFunc + ')()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
I have to do, onclick = "(' + cancelFunc + ')()"> because if I do, onclick = "' + cancelFunc() + '"> it shows up as undefined. The current way will basically just print the anonymous function out and assign it to the onclick (almost as if I just typed out the anonymous function right at the onclick)
here is where I call the function:
var transTypeHolder;
$("input[name='transType']").click(function () {
var tabLength = $('#SNToAddList tbody tr').length;
if (tabLength == 0) {
var selection = $(this).attr("id");
serialAllowableCheck(selection);
resetSerialNumberCanvasAndHide();
$("#Location").val("");
$("#SerialNumber").val("");
}
else {
transTypeHolder = $(this).val();
var confirm = function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+transTypeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
var cancel = function () {};
confirmMessageBox("This is a test", cancel, confirm);
return false;
}
});
Is there a way to some how pass a variable to the anonymous function without using the global variable I have as, "transTypeHolder" ?
Before I get the, "Why are you doing it this way??" response; Javascript isn't a strong language of mine, as I am using ASP.NET MVC4. I haven't had a chance to sit down and learn Javascript in detail and I sort of picked it up and search what I need. So if there is a better way of tackling this, I am open for constructive criticism.
Don't make event handler assignments in HTML at all. If you want people to be able to supply their own functions for canceling and confirming use on:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default cancel" data-dismiss="modal">Cancel</button></td><td><button type="button" class="btn btn-default confirm" data-dismiss="modal">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$("#confirmMsgContainer").off('click', '.confirm').on('click', '.confirm', confirmFunc);
$("#confirmMsgContainer").off('click', '.cancel').on('click', '.cancel', cancelFunc);
$('#ConfirmMsgModal').modal('show');
}
Note that I've edited the HTML you're using to remove the onclicks and added a class to each button. I'm also using off to be sure any previously added event handlers are removed.
As far as passing the variable to the confirm function without using a global, use a closure:
var transTypeHolder = $(this).val();
var confirm = (function (typeHolder) {
return function () {
var $radios = $('input:radio[name=transType]');
$radios.filter('[value='+typeHolder+']').prop('checked', true);
resetSerialNumberCanvasAndHide();
$('#Location').val('');
$('#SerialNumber').val('');
};
})(transTypeHolder);
That tells JavaScript to create a function, which returns a function that does what you want it to do. That "function creator" takes in the variable you want to keep around, allowing it to be used elsewhere.
Now, I haven't tested this, so you may have some debugging in your future, but hopefully it gives you a jumping-off point.
You should be able to do it by having the function being acessible from global context under a generated name (which can be multiple if you have more than one instance of the box), like so:
function confirmMessageBox(msg, cancelFunc, confirmFunc) {
window['generatedCancelFunctionName1'] = cancelFunc;
window['generatedConfirmFunctionName1'] = confirmFunc;
var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedCancelFunctionName1()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "generatedConfirmFunctionName1()">Confirm</button></td></tr></table></div></div></div></div></div>';
$("#confirmMsgContainer").html(html);
$('#ConfirmMsgModal').modal('show');
}
This way you are not obliged to expose the function code. You can also set an id attribute to the element and set a jquery click() function like in the second part (but you would need the html to be created before you set the click)

Javascript function not working with variables having special character

Javascript function:
var Id ; //global variables
var Name; //global variables
function getServiceId(id,name){
Id=id;
Name = name;
alert(Id);
}
And this my jsp code
<core:forEach var="service" items="${listServiceBO}">
<tr>
<td><a href="Javascript:void(0);">
${service.name}
</a></td>
<td>${service.multiplicity}</td>
<td>${service.scheduleType}</td>
<td>
<button type="button" id="serviceDeleteButton(${service.id})" name="serviceDeleteButton"
onclick="getServiceId(${service.id},'${service.name}');" title="Delete"
class="btn btn-link btn-inline" data-toggle="modal"
data-target="#deleteServiceModal">
<span class="glyphicon glyphicon-remove"></span>
<span class="sr-only">Delete</span>
</button>
</td>
</tr>
</core:forEach>
if my service.name contains any special character....my values are not getting set in Javascript. But if I do not have any special character in that name then it is working fine.
Because of special character I am not able to set any of the two values. Any solution ???
Can you try this:
onclick="getServiceId(${service.id},"${service.name}");"
Or, the best thing to do would be escaping all values in Java:
Base64.encode(str);
and in Javascript doing a decode:
decodeURIComponent(str);
edit:
Try just escaping it:
var Id ; //global variables
var Name; //global variables
function getServiceId(id,name){
Id=id;
Name = escapeRegExp(name);
alert(Id);
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
jsp not strong suit,but maybe change this:
onclick="toggle('getServiceId(${service.id},'${service.name}')');"
to:
onclick="toggle('getServiceId(${service.id}, \"${service.name}\")')"

Categories