Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a Javascript function that makes a click on a (hidden) button or link

Tags:

jsf

primefaces

I call a javascript function that makes a click on a hidden commandButton but the click run when the page loads, not when I call the function. this is the html code :

<p:inputText id="aa" value="#{bonBonneManagedBean.sel}" onkeyup="fnc()" />
<h:commandButton id="hh" onclick="#{bonBonneManagedBean.kk()}" style="display:none"/>

and the javaScript function :

function fnc()
{
    length = document.getElementById('form:aa').value.length;
    if(length == 10)
    {
        $("#hh").click();
        document.getElementById('form:aa').value = "";
    }
}
like image 936
Bob Samadi Avatar asked Feb 27 '26 21:02

Bob Samadi


2 Answers

You should use the action attribute instead of onclick like this

<h:commandButton id="hh" action="#{bonBonneManagedBean.kk()}" style="display:none"/>

Note that you might have to add form prefix to the selector, like this

$("#myFormId\\:hh").click();

The same would work for a commandLink or any other 'clickable' component.

like image 154
Daniel Avatar answered Mar 01 '26 12:03

Daniel


Must there be a button on this page(which I doubt, seeing as you're hiding it anyways)? You're better served using something like <p:remoteCommand/> here

Ditch the hidden button and replace with

<p:remoteCommand name="fnc" actionListener="#{bonBonneManagedBean.kk}"/>

But, if it's an absolute requirement, you can very easily emulate a button click in js with the click() method from your function you need to

  1. Change the <h:commandButton/> to a <p:commandButton/> so you can assign the button a widgetVar attribute(to guarantee the name of the element in the DOM). The widgtetVar attribute can be set on almost all primefaces components to make your life easier

  2. Using the widgetVar, just call the click() method in your function

    <p:commandButton ajax="false" widgetVar="theButton" id="hh" action="#{bonBonneManagedBean.kk()}" style="display:none"/>
    <p:inputText id="aa" widgetVar="theTextBox" value="#{bonBonneManagedBean.sel}" onkeyup="fnc()" />
    

    and in the function:

     function fnc(){
         length = theTextBox.value.length;
         if(length == 10){
           theButton.click()
            theTextBox.value = "";
               }
             }
    
like image 22
kolossus Avatar answered Mar 01 '26 12:03

kolossus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!