I want to pass a field of a domain object to a javascript function in my view.gsp (grails) , but I am getting a syntax error.
Here is my gsp and javascript - please let me know if you see the syntax error. Thanks!
/*HTML*/
<td>${fieldValue(bean: studentInstance, field: "active")}</td>
/*JS*/
<script type="text/javascript">
var id = 0;
function setID(userId){
console.log("userId: " + userId);
id = userId;
}
</script>
The issue is you have function in your onclick. You don't need it there. Remove it so your onclick looks like this:
onclick="setID( ${studentInstance.id})"
Related
I'm trying to pass 2 variable using onClick inside of <a> tag
Here's my code:
<a onClick="pbDiv(id=1);">Enter</a>
<script>
function pbDiv(id){
alert(id);
}
</script>
This works perfectly as it should be.
But the problem is I need to pass 2 variable
Example of variable
id=1
name=myname
inside of onClick
Is that even possible?
tried this one onClick="pbDiv(id=1,name=name);"
seems not working to me.
In javascript, you define the name as an argument, and never pass in the name of the argument as a parameter. TypeScript (a version of javascript) does this, however.
function pbDiv(id, name){
alert("id: " + id + ", name: " + name);
}
<a onclick="pbDiv(1, 'foo');" href="#">Enter</a>
Pass object instead
<a onClick="pbDiv(options={id:1, name: 'deepak'});">Enter</a>
<script>
function pbDiv(options) {
alert(options.id + options.name);
}
</script>
In my controller I have this function:
Function AppError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
Return RedirectToAction("main", myScript)
End Function
With this function I want to call my razor page where I have a Javascript named popup whith a parameter Properties.postError.
My script is:
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
</script>
What I need is to popup the error message.
I follow the programm thru my debugger and I saw that it goes to my page.
But no error message window raise up.
I have already search in the web for this option without any success.
Is someone to assist me on this issue?
ADDITION - 16/2/19 12:50
what I have done so far is the following:
Function CBError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
ViewData.Add(New KeyValuePair(Of String, Object)("ScriptName", myScript))
Return View("main", myScript)
End Function
As we can see I've change the function by addiding the ViewData
I Add a value pair arguments 1) the name 2) the value
The action of addition it works just fine and the dictionery receive it.
I my script (which is in my reazor page) I put the following:
<script type="text/javascript">
var vd = #ViewData.Item(0);
function popup(msg) {
var errMsg;
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
//{ window.location.href = "/" }
}
</script>
When I stop (with the bebugger) in the instruction var vd = #ViewData.Item(0); I see that the ViewData is complitely empty. No values no nothing.
I also add this window.onload = #Html.Raw(ViewBag.MyScript);
And in debugger threw me an error
"Uncaught SyntaxError: Unexpected token ;"
Is there somone to instruct me why that happen?
ADDITION - 16/2/19 20:00
New version of function and Script
Function CBError() As ActionResult
Dim myScript As Object = Properties.postError
ViewData.Add(New KeyValuePair(Of String, Object)("Message", myScript))
Return View("main")
End Function<br/>
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewData.Values(0)");
});
</script>
With this version I put the message value to the ViewData
But when the program comes to the point of script then all the ViwData is empty.
No Values no Keys no nothing.
It seems somewhere in the middle it lose all the data
FINAL UPDATE 17/2/19 11:13
The problem has been solved ... but not by the way we are wearing.
It was solved in an extremely simple way.
What we were asking for was to get the error message on the page we are in. From any point of the code.
So I followed the method of rendering the message to property and I read this message from the page with the following Javascript.
The function is:
Function CodePage_Error() As ActionResult
Return View("main")
End Function
End the Javascript is:
<script type="text/javascript">
$(document).ready(function () {
if ("#Properties.InnerError" !== "") {
var msg = "#Properties.InnerError";
window.alert(msg);
} else {
return false;
}
});
The Javascript is placed in the mainLayout.vbhtml file
Generally speaking, it turned out that the transfer method from the controller to the page is not possible in the MVC4 environment
You could pass the error message to the page via Viewbag, and then put the pop up script inside the document ready javascript function to check the message and display the error if required.
Controller:
public IActionResult Index()
{
ViewBag.Message = "this is your message";
return View();
}
View:
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewBag.Message");
});
I think passing JS code through RedirectToAction route value parameter is not a good idea because some special characters will be encoded. You should use either ViewBag or viewmodel properties and pass the script to view in unencoded state.
Here is an example setup:
1) Use ViewBag or a viewmodel property to contain the script you want to execute in the view.
Public Function AppError() As ActionResult
' define Properties.postError here
Dim myScript As String = "popup(" + Properties.postError + ")"
ViewBag.MyScript = myScript
Return View()
End Function
2) Use an event handler e.g. window.onload assigned with #Html.Raw() from ViewBag or viewmodel property to pass unencoded function call inside <script> tag. The event handling must be placed outside function block.
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
// the popup will be called here
window.onload = #Html.Raw(ViewBag.MyScript)
</script>
Note that window.onload will pop up the message after the view is loaded, if you want to pop up the message in another event use any desired event handler instead (also check list of available JS DOM events).
I am doing:
var url = '#Url.Action("Attachments", "Transactions")';
url += '/?id=' + 3201;
$("#attachments").load(url);
However, on load it doesn't do anything. Am i missing something?
I essentially want to call something similar to:
#{Html.RenderAction("Attachments", "Transactions", new { id = 3301 });}
I get the following error on console:
http://server:54137/Transactions/#Url.Action(%22Attachments%22,
You must be using an external JavaScript file which will not parse your razor syntax hence the error in your console of #Url.Action(%22Attachments%22..
You have a couple of options:
Create a JavaScript function and pass in the url:
function loadUrl(url) {
$("#attachments").load(url);
}
Then in your razor call it within a script tag:
loadUrl(#Url.Action("Attachments", "Transactions", new { id = #Model.Id })
Add the url to the html element as data and read it from your JavaScript with the data method.
In your razor markup add this:
<button data-url="#Url.Action("Attachments", "Transactions", new { id = #Model.Id })" />
From your JavaScript event handler read it with:
var url = $(this).data('url');
$("#attachments").load(url);
I prefer the second option.
You Need to use Html.Raw check below
var url = "#Html.Raw(Url.Action("Attachments", "Transactions"))";
url += '/?id=' + 3201;
$("#attachments").load(url);
In my jsp I use <%String base = (String)application.getAttribute("base");%>
I tried to use 'base' in javascript but not work. Below is my javascript:
<script>
var newBase = <%=base%>;
</script>
Can anyone help me to solve this?Thanks
This is the eplanation www.w3schools.com give for location object property pathname:
pathname: Sets or returns the path name of a URL
In our case the javascript file wich is in your context.
The first element is that pathname is the context
So you split the attribute (see the split method in javascript String) and return it.
This should do.
<script language='javascript'>
function servletContext() {
var sc = window.location.pathname.split( '/' );
return "/"+sc[1];
}
</script>
You can rather try it out like this ,
set the value to the hidden field ,
input type="hidden" id="hidVal" name="txt2" value="${base}"/>
And in your java script ,
<script>
var x = document.getElementById('hidVal').value;
alert(x);
</script>
Update :
var newBase = '<%=base%>';
You are missing the quotes to treat the value as string .
Hope this helps !!
Alright, so I'm making a form validation everything is good in this JS, but now I'm facing a problem in the output, I am trying to display all the chosen data. So I used the action attribute and called the following function:
function funcs()
{
var favor = document.reg.favor[selectedIndex].value; //Select input
var fname = document.reg.fname.value; // text input
var lname = document.reg.lname.value; // text input
var email = document.reg.email.value; // text input
var pass = document.password.value; //text input
for(i=0;i<document.reg.rad.length;i++)
{
if(document.reg.rad[i].checked == true)
{
var rad = document.reg.rad[i].value; // Radio input
}
}
if(document.reg.bike.checked == true)
{
var bike = document.reg.bike.value; //CheckBox input
}
if(document.reg.car.checked == true)
{
var car = document.reg.car.value; //CheckBox input
}
document.write('<head><link type="text/css" rel="stylesheet" href="registrationtable.css"/></head><body>');
document.write("<div class = 'team'>");
document.write('<table>');
document.write("<tr><td> שם פרטי: </td><td>" + fname + "</td></tr> <tr><td> שם משפחה: " + lname + "</td></tr> <tr><td> אימייל: " + email + "</td></tr> <tr><td> סיסמא: " +pass +"</td></tr>");
document.write("<tr><td> השחקן האהוב עליך הוא " + favor +"</td></tr>");
document.write("</table>");
document.write("</div></body>");
}
Here's the form header:
<form name ="reg" action ="Javascript:funcs()" onsubmit ="return checkValidation()">
I'd like to clear that all the other javascript code is working perfectly, it must be something with this function.
When I'm pressing the send button, it won't do anything. Anyone knows whats the problem?
Thanks in advanced.
You can't shouldn't have a javascript function in your action attribute, it needs to be a URI. You can just call the funcs onsubmit if validation succeeded.
As Aquinas has shown that calling a javascript function in the action attribute is in fact possible, it is advised that you not put js code in the action attribute.
As I suspected. One problem is this line:
var favor = document.reg.favor[selectedIndex].value;
It should be
var favor = document.reg.favor[document.reg.favor.selectedIndex].value;
And your second problem is this:
var pass = document.password.value;
Should be:
var pass = document.reg.password.value;
See updated fiddle: http://jsfiddle.net/x7SBy/1/
Finally, you should use Firefox and download Firebug. It is invaluable for debugging JS problems like this.
Edit: There are other problems with your JS that I won't get into in detail, but in general you don't want to use document.reg.password, because of issues like this. You should really use document.getElementById. FYI.
It looks like you are trying to validate a form, then if valid call the funcs function to alter HTML on the page.
Maybe something like this:
<form name="reg" action="" onsubmit="checkValidation()">
Then a checkValidation function to pause form submission and if valid, call the funcs function:
function checkValidation(e) {
e.preventDefault();
if (checkValidation()) {
funcs();
}
}
But if this is the case, your funcs function should not be writing <head> tags and such. Maybe you could just add HTML to the body instead of trying to lay a new HTML document into the DOM with javascript.
Alternate solution:
function checkValidation() {
... do your validation
return true; // or false if invalid
}
Then use a real HTML page/resource in your action tag of the form.