Jsp with javascript parameter inside javascript onclick - javascript

I would like to insert a call to a function to get a parameter for my JavaScript onclick function. What I would like to do is something like:
<input class="refreshbutton"
type="button"
id="searchUfficiPopup"
onClick="javascript:postColorbox('/DeliDete/searchUfficiPopupBySettoreId', **'&settoreIdKey=${javascript:getSettoriId()}'**, 'tabUfficiForm', 'initScriptUffici')"
value="<fmt:message key="navigation.searchUffici"/>" />
This way Eclipse tells me the function javascript:getSettoriId() is undefined. I defined this function in an external .js file, loaded at runtime with jQuery's .getScript, so I would not like to insert it into the jsp (anyway I tried to insert it into the jsp but the IDE still says that the function is not defined).
The function postColorbox is defined as:
function postColorbox(url, parameters, formName, initScript)
The function getSettoriId() returns the value of a previously entered form element, Settori, which I need to perform a restricted query (I need to obtain all Uffici entities related to the selected Settori entity)
Told this, I would like to ask you experts:
Is it even possible to use a JavaScript function as a parameter of an onclick JavaScript function?
If I put this function to be called in an external .js file will the jsp be able to see it and call it?
Thank you all for your help!
Andrea

Remove the onClick on your <input> and do it with a jQuery event handler instead:
$('#searchUfficiPopup').click(function() {
var settoriId = getSettoriId();
postColorbox('/DeliDete/searchUfficiPopupBySettoreId',
'&settoreIdKey=' + settoriId,
'tabUfficiForm',
'initScriptUffici');
return false;
});

Calling functions from inside the HTML element is not a preferred way. If you can - just assign the element an id or class, and then add a listener to it using javascript on page load.
This way you don't have your data and operations mixed. It will be also easier to modify the code, as your code will be located in js files.

Related

Why do I need 'javascript:' in the call to my javascript function?

Newer to javascript and trying to learn why this works, searching Google has led to no answers (although I maybe searching using the incorrect terms).
I'm am making a call to a function during an onclick event within an <a></a>. I was able to get the function finally working (with a suggestion from a coworker) by adding in 'javascript:' before making the function. Without the javascript: portion in the onclick, my function was not being called upon.
It now works but I don't understand what that is doing, the other programmer who suggested putting it in the call also isn't sure what exactly it does.
Here is a simplified version of the code used:
#1 .jspf higher up which includes page #2 to display it's contents
function createTagging(1, 2) {
cmCreateElementTag(1 + ", " + 2,"TagName");
}
HTML in .jspf file #2 further down website makes the call to function in file #1
<a id="CatEntry" href="https://aurl"
onclick="javascript: createTagging('parameter1', 'parameter2');"
title="atitle" aria-label="alabel">
<img id="ThumbNailImage_59244" src="https://image.jpg"
alt="" border="0"/>
</a>
-Troy
Why do I need 'javascript:' in the call to my javascript function?
You don't. It's an onclick handler. You use the javascript: pseudo-protocol where a URL is expected (for instance, if you'd used href instead of onclick). onclick expects JavaScript code.
In fact, it only works because JavaScript has labelled statements, and javascript: is a valid label. It's completely ignored.
Without the javascript: portion in the onclick, my function was not being called upon.
With respect, that must have been observational error. Again, in an onclick handler, it makes no difference whether you have javascript: in front of it or not. If it wasn't working, and then it was working, you changed something else at the same time you added javascript:.
onclick attribute is always calling javascript in HTML.
onclick="createTagging('parameter1', 'parameter2');"
It is only necessary if you use not an event, but href. There you need to add the protocoll as well for Javascript.

unable to call a function on click Event of an image in java script

I have defined a Variable containing the Image in a java script file
var route ='<img src="http://s31.postimg.org/mwewcja1j/146117012724825.png" alt="route" id="routeimg" onclick="myFunction()" style="width:50px;height:35px;">';
function myFunction{alert("hello")}
Error myFunction is not defined.
or
var route ='<img src="http://s31.postimg.org/mwewcja1j/146117012724825.png" alt="route" id="routeimg" style="width:50px;height:35px;">';
document.getElementById("routeimg").onclick= "alert("hello")";
Error :routeimg is not defined
I have googled for all posts of this type & replicated the Exact Procedure but nothing helped me out
Your function has incorrect syntax. It's missing the parentheses:
function myFunction(){
alert("hello")
}
For this to work, your route has to be added to the DOM of course.
The second code snippet will fail for a different reason. Whilst parsing the HTML document converts a tag attribute value of onclick="alert('hello')" into a HTML event handler function of form
function(event){ onclick_attriute_text_from_HTML_source };
and adds it as the onclick property of the HTMLelement created for the tag in the DOM, you can't set the attribute to text in code. It must be set to a function object instead. E.G.
document.getElementById("routeimg").onclick= function(){alert("hello")";};
As before, you must have added the element to the DOM first.

Passing a parameter to a Javascript function using data attributes in an <a> tag in MVC 5

I am building an MVC 5 web app using Visual Studio 2013.
I am trying to create a list of Courses using anchor tags which when clicked will pass as a parameter the selected Course to a Javascript function. The Javascript function will in turn use Ajax to call a second function to retrieve a list of Students enrolled on the selected Course.
In the View I have:
#model IEnumerable<School.Models.Course>
...
#foreach (var item in Model)
{
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="#item.CourseName">#item.CourseName</a>
}
The Course list gets created as expected:
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="Chemistry">Chemistry</a>
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="Physics">Physics</a>
My Javascript function is defined as follows:
function selectedCourse() {
var selectedCourseName = $(this).data('cname');
}
The code reaches the Javascript function but the value of selectedCourseName is always 'undefined'.
Am I missing something really basic for this to work?
Any help would be greatly appreciated.
Walter
The reason that it's not working is because the context of this on an inline event handler is not the element itself, but the window element. Change your code so that the handler is applied separately from your markup, this is a best practice anyway, and the context will be correct.
$('.selectedCourse').on('click', function(e) {
e.preventDefault();
var selectedCourseName = $(this).data('cname');
...
});
An alternative, and one I don't recommend, is to add a parameter to your inline handler and pass this as the parameter. The value of the parameter will be the element that was clicked.
Don't do this!
See examples at http://jsfiddle.net/cJZpK/

javascript function gets called twice

I am trying to call a javascript function on clicking a link. Actually i want to submit a form on clicking a link using post method so i am trying to do the below-
<a href="javascript:submitCategory(this)" >Handicrafts</a>
and in javascript
function submitCategory(varthis)
{
alert(varthis.value);
}
I have few important questions:
1>When i click on the link the function submitCategory gets called twice. After much analysis found that i had two js files included and removing one of them made the function getting called only once.
meaning
when i have included
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="cWed.js"></script>
submitCategory function gets called twice
and when i remove one of them and include
<script type ="text/javascript" src="jquery.js"></script>
submitCategory function gets called only once.
Why is it like this?
2> alert(thisvar.value) should return Handicrafts but it returns undefined. why could this be?
3>what exactly is the meaning of href="javascript:submitCategory(this)"? i have not come across this in any tutorial. and including this here should refer to the element "a" right?
1. You do not need to use the qualifier 'javascript:'
2. when you hook the event in html, always try to do it like event_handler(event). Note : event is the event object. and not some random variable here. You can read more about it in numerous places on the web. In your case varthis is the event object. to access this element use varthis.target and then to get its inner html you can use varthis.target.innerHTML
3. when the function is called you have to either explicitly get the html content of the calling element via the event tag, or just use jquery. You cannot pass variables in the way you think you are passing right now.
4. if you are actually trying to submit a form, I would recommend hooking the onSubmit event in script rather than HTML and put your custom form submit code there. If you do not need to do anything custom in form submission, you can just put the url of the target server function in the action attribute of the form.
Sample code :
<form>
Submit Category
</form>
<script type="text/javascript">
$('#submitCategoryLink').on('click', function (e) {
alert(e.target.innerHTML)
});
</script>
Since you haven't posted the contents of cWed.js it's difficult to know why you're getting a double submission, but my guess is that it contains a click handler of its own, which is duplicating the default handler.
The reason varthis.value doesn't work is because .value is only used for <input> and <select> elements, it contains the value that the user entered or selected from the menu. To get the text content of an element you should use .innerHTML.
A URI that begins with javascript: means that instead of fetching a page from a network location, the browser should execute the Javascript code after that prefix. It's not an officially recognized URI scheme (there was an Internet-Draft RFC, but it expired 2 years ago) , but all browsers support it.
When code is executing from a javascript: URI, this is the window, not the element that was clicked on. You need to use an onclick handler to get this set to the element.
The following works:
<a href="javascript:void(0)" onclick="submitCategory(this); return false;" >Handicrafts</a>
function submitCategory(varthis)
{
alert(varthis.innerHTML);
}
FIDDLE

Javascript function is not getting called onclick of hx:commandExButton

When I click on the hx:commandExButton the Javascript function should get called, but it is not getting called. The Javascript function is as follows:
function test() {
alert('ss');
return "true";
}
The hx:commandButton is as follows:
<hx:commandExButton
type="submit"
value="Search"
styleClass="action2" id="searchButton"
onclick="return test();"
action="#{pc_WorkInProgressUserGrid.doSearchButtonAction}"
immediate="true">
</hx:commandExButton>
Any suggestion would be helpful.
First step would be to check the generated HTML output to verify if it looks right. It may for instance happen that the hx:commandExButton itself didn't take the onclick attribute value correctly into account. As a test, you could try to get rid of it and use the standard JSF h:commandButton instead.
Further I also recall something about a crazy <hx:scriptCollector> tag which you are supposed to wrap the piece of JSF code with whenever you'd like to use Javascript in combination with IBM Faces Client components.
E.g.
<hx:scriptCollector id="someid">
<hx:form>
<hx:commandExButton />
</hx:form>
</hx:scriptCollector>
I don't know JSF, but it's immediately obvious that you have omitted a " after true, and also a >
Are those ** supposed to be there? And writing method before a function is definitely not part of standard JavaScript.

Categories

Resources