Passing html element to oncomplete function of a4j:jsFunction - javascript

I need to pass the calling html element of a <a4j:jsFunction> to its oncomplete function. I saw this answer but I don't think passing the html element (as a string, I suppose?) to the bean and back is very elegant, and I think it's a bit messy.
Here's my code
<td class="col-md-2 clickable text-right"
onclick="orderBy('getAmount','DESC')">
#{msg.label_amount}
</td>
<a4j:jsFunction name="orderBy" action="#{backingBeanRef['orderBy']}"
oncomplete="afterOrderBy()"
render="list_form" >
<a4j:param name="ref" assignTo="#{backingBeanRef['orderByMethodName']}"/>
<a4j:param name="ref2" assignTo="#{backingBeanRef['orderBySortOrder']}"/>
</a4j:jsFunction>
Question
Is there a way to pass an html element to the a4j:jsFunction, and have that one pass it to its oncomplete callback function, without sending the html element to the bean and back?
The ideal solution would be to add a param to the invoking side like orderBy(... , this) and the corresponding param to the jsFunction like <a4j:param name="element"/> :
<td class="col-md-2 clickable text-right"
onclick="orderBy('getAmount','DESC',this)">
#{msg.label_amount}
</td>
<a4j:jsFunction name="orderBy" action="#{backingBeanRef['orderBy']}"
oncomplete="afterOrderBy(element)"
render="list_form" >
<a4j:param name="ref" assignTo="#{backingBeanRef['orderByMethodName']}"/>
<a4j:param name="ref2" assignTo="#{backingBeanRef['orderBySortOrder']}"/>
<a4j:param name="element"/>
</a4j:jsFunction>
But it doesn't work. I have a breakpoint in the first line of the js function and it doesn't get called.
I just added the ..,this) to the amount column (the only one I'm showing), so if I click on the other columns (which don't have the ..,this)) my js function does get called, only the parameter comes undefined.
So, is it possible to do this?
Edit
If I try to not add any <a4j:param>, and do oncomplete="afterOrderBy(this)" as pointed by this answer the element sent to the js function is a span (when I debug/log it to console, it has no .source child, and is
...
outerHTML: "<span id=\"sgfrmId:j_idt601\" style=\"display: none;\"></span>"
...
This answer also points out some ways to do something similar but not this exactly.
Edit2
Just read in the docs that
[...] It is not recommended to use use keyword this inside the
EL-expression, because it will not always point to the component where
Ajax request was initiated.[...]
So doing the oncomplete="afterOrderBy(this)" was wrong.
Thanks in advance.

The a4j:jsFunction only serves to trigger an ajax request, the oncomplete is executed as part of the server response (i.e. not within context of the function), simply save the element reference to a global variable and have the oncomplete code use that variable.
E.g.
<td onclick="sourceElement=this; orderBy();">…</td>
afterOrderBy = function() {
// do something with sourceElement …
}

Related

Need to display javascript value in anchor tag of jsp

I need to pass the userid variable through anchor tag .. Here I attached code for that.
Code :
<td colspan="2" align="right"><div align="center">User Id</div></td>
<td><input class="textbox" type="text" id="userid" ><a href="access.jsp?userid='+userid'"
"></a></td></tr>
Javascript :
var userid ="MK";// this value is getting fetched correctly using document.getElementByName
Just I need to display in anchor tag.How can I do this?
Please, try to be more clear with your Question.
You should show all related parts of your code so people can figure out what exactly you need.
Also Stackoverflow provides some markup so you can insert blocks of code - very useful, I recommend looking it up :)
Assuming you already have the anchor <a> tag
HTML
JS
// your code (fetching data) ...
document.getElementById('anchor').setAttribute('href', 'google.com?userid=" + userid)

Pass cliendid from a control as a parameter from ASP to javascript function

I have a function that shows the password on a textbox and another the hides it and hows the dots.
Here's one of them:
function MouseOver_MudarTipoPassword() {
document.getElementById('<%= tb_PalavraPasse.ClientID %>').setAttribute('type', 'singleline');
}
And the control that has the events:
<img id="img_Eye" runat="server" src="~/Recursos/Imagens/eye-icon.png" onmouseover="MouseOver_MudarTipoPassword()" onmouseout="MouseLeave_MudarTipoPassword()" />
So, I I've been cleaning up the code because there are functions being used on several pages and I'm combining them into a javascript file. It works like this if I put it in the head section of the page. But I want to pass an argument instead. I want to pass the textbox clientid. How can I do that?
Make the function take a parameter:
function MouseOver_MudarTipoPassword(elementId) {
document.getElementById(elementId).setAttribute('type', 'singleline');
}
Pass the id into the function call:
<img id="img_Eye" runat="server" src="~/Recursos/Imagens/eye-icon.png" onmouseover="MouseOver_MudarTipoPassword('img_Eye')" onmouseout="MouseLeave_MudarTipoPassword('img_Eye')" />
Update
Apologies, I didn't pay enough attention to the question. The problem with my answer is that the script must run before the DOM is created, like in the HEAD.
To make it work like you want you will have to attach an event listener to your elements. You also need a way to dynamically associate the target of the listener code. You can do that with data-* attributes.
See this fiddle for working example
The sample markup:
<input type="text" id="theTextBox" value="The IT Crowd" />
<hr />
<img id="Moss" src="https://media0.giphy.com/media/TrDxCdtmdluP6/giphy.gif" data-target="theTextBox" />
The
sample javascript:
var test = document.getElementById("Moss");
test.addEventListener("mouseover", MouseOver_MudarTipoPassword, false);
function MouseOver_MudarTipoPassword( event ) {
var theImg = event.srcElement;
var target = theImg.dataset.target; //re-use this function by applying data-target to all elements that need it (does not have to be named "target")
document.getElementById(target).setAttribute('type', 'password');
}

Call Javascript Function from .ascx file

I have one javascript function named 'change2()' which is define in .ascx page's script tag.
I want to call that function from onclick event of img tag (Note : img tag is also on the same page).
It is compulsory to use img tag only for image.
I tried all the below ways, but unfortunately It doesn't work for me.
Test.ascx
<script language="javascript" type="text/javascript">
function change2() {
alert("Hi");
}
</script>
<table>
<tr>
<td class="list">
Most liked
</td>
<td>
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" onclick="change2();" alt="Slider" />
</td>
</tr>
</table>
Second Way :
<table>
<tr>
<td class="list">
Most liked
</td>
<td>
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" alt="Slider" />
</td>
</tr>
</table>
Please give me your suggestions to call javascript function from same page.
As I can see, the img id is imgLkU, so, instead of including the call in the img tag itself, you can subscribe the event "from the outside", i.e. do it like using $.on, (or $.click) like this:
$.on('click','#imgLkU', function() { change2(); });
// or equivalent $.on('click','#imgLkU', change2);
or
$.('#imgLkU').click(function() { change2(); });
// or equivalent $.('#imgLkU').click(change2);
Do it right after defining change2 in the same script tag.
I'd also recommend you doing the change2 definition and the event subscription inside an inmediately invoked function expression to avoid polluting the global javascript namespace.
(function() {
// define and subscribe here
})();
Because your elements all have runat="server", their onclick property is reserved for a backend-code actionlistener which will be executed at postback.
the onClientClick property is reserved to allow you to still attach javascript "listeners" to what is considered the client-side onclick.
keep in mind that returning false from an onClientClick handler will prevent postback from happening if an onclick listener is also hooked up. (onClientclick is executed before initiating the postback)
try this :
<img id="imgLkU" src='<%# WebHelper.GetBaseURL(Request) + "/images/slide_btn_down.png"%>'class="icon_right_panel" runat="server" onclientclick="change2();" alt="Slider" />
The following function can be directly called from document.ready function like
$(function () {
$('#imgLkU').click(function () {
//do what ever you want
})
});
First, take out the runat="server" on your image since you are already using server tags to set the url. If you still want to use runat="server", you can either:
1: change your img into an <asp:Image> tag and use ImageSource instead of src and OnClientClick instead of onclick.
2: set the src attribute in the code behind.
After that, any click method - from your question to all the answers - should work.
If that still does not show the alert, then start taking out code until it does and work your way from there...

is ID of html controls which called by javascript casesensitive or not

i have this control
<input id="btnBackMP" type="button" value="<" onclick="BackGroup('MP') ;"
disabled="disabled" style="background-color: #BF0000; width: 28px;" />
inside backGroup Function i used this Code Line :
document.getElementById('btnback' + Key).disabled = true;
this line works fine on Web Dev but when i published my site on server (iis 7)
this line stop working till i changed it to the following :
document.getElementById('btnBackMP'+ Key).disabled = true;
any one have idea ?
thanks
Have you changed in calling function argument too since before your are passing 'MP' as argument and using as key
<input id="btnBackMP" type="button" value="<" onclick="BackGroup() ;"
disabled="disabled" style="background-color: #BF0000; width: 28px;" />
and why do not you directly change to this line only :-
document.getElementById('btnBackMP').disabled = true;
Element id is case sensitive. The id must be unique but in theory you could use id="elementa" and id="elementA" in the same document to refer on two different nodes.
This is not recommended
Further details on
https://developer.mozilla.org/en-US/docs/DOM/element.id
The id attribute values are case-sensitive by HTML specifications; see e.g. HTML 4.01 on id. They are thus case-sensitive when used in JavaScript too. Note that the document.getElementById method queries the DOM, which must follow HTML conventions here.
So btnbackMP and btnBackMP are distinct id values. Your code seems to have another error too, as pointed out, but this might be just an issue in formulating the question. (I suppose the last code line was meant to have btnBack not btnBackMP.)

Jquery change onclick function name

My question is! I am copying content from one table to another table and when I am doing this I need the function name to change to talentselect instead of driverselect which is attached to each table row. I still need to keep the variable values to parse. Just wondering if anyone can help me with this. I know that I should be binding the events to the elements with Jquery and not using OnClick but for now I need a solution to achieve this with the OnClicks.
Many Thanks!
The copying of the table
<table id="driverselectiontable" cellspacing="0">
<tr class="chosen" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="odd" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="even" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="chosen" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
<tr class="even" onclick="return driverselect(this, value, value);">
<td>driver</td></tr>
</table>
<table id="talentselectiontable" cellspacing="0">
</table>
$("#talentselectiontable").html($("#driverselectiontable .chosen").clone(true).attr("class","odd"));
So basically I am copying all of the table rows that have the class named "chosen" but upon doing so I need to change the function call name to "talentselect". But each row in the table has different parameters being parsed which is allocated with PHP.
I have tried this piece of code but it is not working still
$("#talentselectiontable tr").attr("onclick").replace("driverselect", "talentselect");
I can't see the actual HTML of your table, so this may be slightly incorrect, but should get you started.
$("#talentselectiontable tr").attr("onclick", "return talentselect(this, value, value);");
This whole problem would actually be a lot easier if you used event handlers rather than inline onclick attributes. You could then use the jQuery live() function (see http://api.jquery.com/live/) that would mean that JQuery would take care of changing the function for you. Your solution would look something like this:
$("#driverselectiontable tr").live('click', driverselect);
$("#talentselectiontable tr").live('click', talentselect);
And then whatever code to ensure that your cloning code gets called.
Edit: In response to the comment, it looks like this is what you're after:
var clickval = $("#talentselectiontable tr").attr("onclick");
$("#talentselectiontable tr").attr("onclick", clickval.replace('driverselect', 'talentselect'));
That should get you going.
With a view to better JavaScript practice however, I would recommend another approach entirely. Rather than storing your parameter values in the 'onclick' attribute, store them in a data attribute. So your HTML would look something like this:
<table id="driverselectiontable" cellspacing="0">
<tr class="chosen" data-myparam1="value" data-myparam2="value"><td>driver</td></tr>
And so on. You can then use JQuery to parse the values:
function driverselect() {
var row = $(this),
param1 = row.attr('data-myparam1'),
param2 = row.attr('data-myparam2');
// rest of the code goes here
}
Your markup will be cleaner, and you can use the live() jQuery functionality as described above.

Categories

Resources