Bob Samadi
Bob Samadi

Reputation: 147

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

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 = "";
    }
}

Upvotes: 3

Views: 34638

Answers (3)

Daniel
Daniel

Reputation: 37061

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.

Upvotes: 7

Jamie Smith
Jamie Smith

Reputation: 131

If the top answers from Daniel and Kolossus doesn't help out someone: I found that characters got put in front of the id I set in my case, therefore this helped me:

$('[id$=hh]').click();

Basically the selector is saying the id ends with 'hh' but may not be the full id.
This is also helpful in SF development as the same thing happens with comandButtons, etc.

Upvotes: 1

kolossus
kolossus

Reputation: 20691

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 = "";
               }
             }
    

Upvotes: 4

Related Questions