How to add variable to a href - javascript

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>

Related

Passing the parameter via an automatically generated JavaScript link to the controller

I have a problem with passing the parameter via the link to the controller. The view in which I have a problem is to dynamically display the list of users, along with the possibility of searching for them. I did this part in js and it works fine. In this functionality in js I generate a link to the buttons, so that later, after pressing the button, you can save the selection in the database. Each link has an assigned user ID and user group ID. My problem is that when I press the button, nothing happens.
The following code represents the functionality described above. I would be very grateful for your help.
#if(ViewData[Enums.States.UserSelectWindow.ToString()].ToString() == "True")
{
<script type="text/javascript">
$("#UserlistCollectionId").css('height', $("#WindowUserSelectId").height() + 'px');
let users = #Html.Raw(Json.Serialize(UserModel.GetUsers()));
function Clear() {
$("#UserlistCollectionId").empty();
}
function FillAll(users) {
Clear();
for (user of users) {
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-action="AddUserToGroup" asp-controller="Settings" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
}
}
FillAll(users);
$("#SearchInputId").keyup(function () {
Clear();
let searchValue = $("#SearchInputId").val();
if (searchValue === "")
FillAll(users);
else {
for (user of users) {
if (user.name.includes(searchValue)) {
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
}
}
}
});
</script>
}
In the above code, automatic link generation is performed using JQuery as follows:
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
Unfortunately it doesn't work. In the inspection of the page you can see that the tag "a" does not have the attribute "href", only automatically puts all the code in quotes:
Screen of the html fragment in the browser
Firstly, you need read the doc about what does asp-route-{value} generate the url:
Any value occupying the {value} placeholder is interpreted as a potential route parameter. If a default route isn't found, this route prefix is appended to the generated href attribute as a request parameter and value
(/home/index?value=aaa). Otherwise, it's substituted in the route template. More explantion you could refer to the document.
Secondly, you do not specify the controller and action name, so the url will generate depending on your request url. That is to say, if the tag helper exists in Home/Privacy.cshtml, it will generate to:href="/home/privacy?value=aa".
Finally, Tag Helpers are interpreted. In other words, Razor must see them as actual tags in order to replace them. So what you did in js will not follow the tag helper generation principle, it's just a JS string. You need change the url like below:
<a class="btn btn-sm btn-success" href="/home/index?groupId=' +#Model.Group.Id+'&userId=' + user.id+'">Wybierz</a>
If the url matches the default route template, the url may like below:
<a class="btn btn-sm btn-success" href="/home/index/' +#Model.Group.Id+'/' + user.id+'">Wybierz</a>

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

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 get recognize button to click

I am making a Chrome extension and I need this button to be clicked so how can I get the click to be recognized?
<button class="btn btn-lg btn-danger btn-bet" onclick="system.play.bet.red();">RED</button>
I tried var test= document.getElementsByClassName("btn btn-lg btn-black btn-bet");
test.click();
but it fails at the beginning.
Document.getElementsByClassName() returns an array-like object of all child elements which have all of the given class names. Unfortunately, it's not a true JS array. To work with it, you need to "Arrayify" it:
var testElements = document.getElementsByClassName('test');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
return testElement.nodeName === 'DIV';
});
In your case, this should work:
var test= document.getElementsByClassName("btn btn-lg btn-black btn-bet")[0];
test.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