Javascript function not working with variables having special character - javascript

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}\")')"

Related

$(this).attr('id') gives blank values in jQuery

I have a link as follows:
<a href="#" id="<?php $res['id'];?>" class='bid_accept'>Accept</a>
I need to pass the value of id to another page using Framework7 as follows:
$$('.bid_accept').on('click', function (e) {
e.preventDefault();
var value = $(this).attr('id');
var jsonstring = JSON.stringify(value);
myApp.confirm('Are you sure?', 'Custom Title',
function (jsonstring) {
myApp.alert('Your name is "' + value + '". You clicked Ok button');
},
function () {
myApp.alert('You clicked Cancel button');
}
);
});
I receive alerts as:
Your name is "". You clicked Ok button
I also tried:
var value = this.id;
Why am I not getting the id value?
If you use JSON.stringfy(value) it means you are setting that ID out of a JSON value, i do not know if i am write but the ID attribute takes a 1 word name and JSON.stringfy() produces multiple words separated by spaces. Let alone i think IDs have a specific number of characters so you might be intializing a very long name.
Not really sure what you want to achieve but HTML allows you to add attributes of your own and read them in JQuery like:
<a href="#" myAttr="<?php $res['id'];?>" class='bid_accept'>Accept</a>
such that when you click your code will be like:
$$('.bid_accept').on('click', function (e) {
var value = $(this).attr('myAttr');
....
}
This line has error
<a href="#" id="<?php $res['id'];?>" class='bid_accept'>Accept</a>
change it to
<a href="#" id="<?php echo $res['id'];?>" class='bid_accept'>Accept</a>
And in jquery part instead of $ you have to use $$.
var value = $$(this).attr('id'); // check $$ sign

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 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>

get autogenerated id of list item on click not working [duplicate]

Given this HTML code:
<td role-id="#Model.Id">
#Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole()'></div>
</td>
I need to retrieve role-id when clicking on the div.
JS code:
function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
Both values are undefined, how can I get role-id without this?
Better approach is to use jQuery event binding, but using your approach, pass this context from called function:
Problem: In your example, this is not the element on which event is invoked but window!
function UpdateRole(that) {
$("#ModalUser").show();
var role_id = $(that).parent().attr("role-id");
var user_id = $(that).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
<td role-id="#Model.Id">
#Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
Using jQuery event-binding:
function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
}
$('.update_user').on('click', UpdateRole);
<td role-id="#Model.Id">
#Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
You should register your event using jQuery, this makes it much easier to find the calling element:
$('.update_user').click(UpdateRole);
You can now:
function UpdateRole() {
var clickedElement = $(this);
$("#ModalUser").show();
var role_id = clickedElement.parent().attr("role-id");
var user_id = clickedElement.parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};
this is very simple you need to update this line with . data-* is html5 new attribute for setting and getting data
$(".update_user").on("click",function(){
elm=$(this).parent().data("role-id");
elm // this element consist of role id, now you can use this variable
});

error call data with javascript onclick

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+"\")'>

Categories