JavaScript code in a tag onclick - javascript

I need to do some ugly stuff. But I cannot do it another way. what I need is
<a href='some/url/?with&params' onclick="(if confirm('Do you wanna submit?')
{some code to submit form in href property})">
but I don't know how to make inline script work... and I hesitate about the way of submitting it with window.location or document.location. Any ideas?

Try this:
on html:
Submit
<script type="text/javascript" src="myValidation.js" />
myValidation.js
I used json and javascript closures on this answer.
; //starts with this to close other js not yet closed
var MyValidation = {
actionSubmit : function() {
//your code go here
//example of calling another function
MyValidation.anotherFunction();
//example of accessing a global variable (for your validation)
MyValidation.variable;
//example of declaring local variable
var word = "hello";
//example of calling another function with parameters
MyValidation.anotherFunctionWithParameters(word, MyValidation.variable);
//the returning
return MyValidation.someValidation(word);
}
//Yes, this is a comma.
//I'm putting in the beginning so we see this and didn't forget :)
,anotherFunction : function() {
//some code
//maybe a return
}
,variable : {}
,anotherFunctionWithParameters : function(param1, param2) {
//more code, maybe a return
}
,someValidation : function(parameter) {
//some validation
return true|false;
}
};
Take a look on this:
How do JavaScript closures work?
json

Have you heard about AJAX? Google it if you don't.
The onClick parameter accepts a function name with or without parameters, not "inline scripts".
<script type=text/javascript>
function doStuff(){
if(confirm("Submit?"){
//do your stuff with AJAX to some/url/?with&params
}
}
</script>
<a href='javascript:doStuff'>link</a>

Related

Calling a Javascript in my razor page from a controller in MVC4

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

Passing a field of a domain object into javascript function in grails

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

how to call javascript client side function from code behind file

How would I call showItems() function in aspx page from code behind.
<script>
function getItems(){
var items = [];
return items; //items=['a','b','c']
}
<form id="form1" runat="server">
<asp:Hiddenfield id="HiddenField1" runat="server"></asp:hiddenfield>
</form>
code behind:
ScriptManager.RegisterStartupScript(this, GetType(), "items", "<script type='text/javascript'>getItems()</script>", false);
A few things here...
First, you don't "call a client-side function from server-side code." What you can do is include some client-side code which itself will call the function, client-side. Which appears to be what you're doing, but I just want to make sure you understand the difference.
Second, your function is called showItems, but you're calling a function called getItems:
<script type='text/javascript'>getItems()</script>
Call showItems() instead? Like this?:
ScriptManager.RegisterStartupScript(this, GetType(), "items", "<script type='text/javascript'>showItems()</script>", false);
Third, the showItems function returns something. But you're not actually doing anything with that result. You're simply invoking the function and ignoring the result. So it's not really clear what you're trying to accomplish.
Like this:
Page.ClientScript.RegisterStartupScript(GetType(), "key", "showItems();", true);
Edit: To get the javascript return value at C# code behind Assign the values to the hidden control using the javascript code. Then you can access the Hidden control value in C# code. Take a look at this article. for example:
<script type="text/javascript">
function showItems() {
var items = new Array(3);
items[0] = "name1";
items[1] = "name2";
items[2] = "name3";
items[3] = "name4";
document.getElementById('<%=HiddenField1.ClientID%>').value = items.join(',');
}
</script>
And in the code behind:
string[] itemArr = HiddenField1.Value.Split(",".ToCharArray());

Syntax error on javascript

I am getting syntax error
Uncaught SyntaxError: missing ) after argument list
My code
<button onclick="alert('document.getElementById('todo.age').value');">onclick</button>
in controller add
$scope.alert = function(age) {
alert(age);
}
in html change like this:
<button ng-click="alert(todo.age);">onclick</button>
Try this:
<button onclick="alert(document.getElementById('todo.age').value);">onclick</button>
You shouldn't quote the argument to alert if you want to call the function.
It will start working better if you separate your HTML code and JavaScript.
Kind of this.
HTML:
<button id="button">onclick</button>
JavaScript:
window.onload = function()
{
var button = document.getElementById('button');
button.onclick = function()
{
//do some action here
}
}
This will help you to avoid simple syntax errors.
if u need value of the todo.age id values use the following code. <button onclick="alert(document.getElementById('todo.age').value);">onclick</button>
or else of u want to print the whole text document.getElementById('todo.age').value like this
use
<button onclick="alert('document.getElementById('todo.age').value');">onclick</button> code/

Running a function by typing in URL - Javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Running a function by typing in URL
On my website I have several functions that when a hyperlink is clicked on example.php page, the main content changes accordingly. Now I want to direct people from a single URL to that example.php page with the function already called. Example - www.example.com/example.php?AC ( which will call a function named AC and the content changes before the page loads)
I had already asked the same question, but forgot to tag javascript and tagged php.
Thanks in advanced.
You can use JavaScript to get the querystring, and call the functions accordingly.
How to get querystring in JavaScript: JavaScript query string
What I would do is read the query string by using something like this to figure out if the key is there
function doesKeyExist(key) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
return qs != null;
}
Then
if(doesKeyExist(AC)) {
// run my code
}
You could do:
var query = document.location.search;
var func = window[query];
if (func && typeof(func) == "function")
func();
<script language="javascript">
var k = document.location.toString().split('?');
if(k.length > 1)
{
if(k[1] == "AC")
AC();
}
</script>
You can add a window.onload handler, check the query string of the page and act accordingly.
For example:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>
You run a JS funciton like this.
<script type="text/javascript">
function test()
{
alert('test');
}
</script>
Now if you type javascript:test() in the url it will execute test function.

Categories