Textbox and button

0

I can not find the error.

I have a Textbox :

<asp:TextBox ID="un_textbox" runat="server"></asp:TextBox> 

then a button:

<asp:Button ID="Button1" runat="server"
        Text="Pulsa"
        OnClientClick="return comprueba();" /> 

And this I have in a script:

<script type="text/javascript">
    function comprueba() {
        var txt = document.getElementById("un_textbox").value;
        if (txt == "hola") {
            return confirm("Confirme el postback");
        }

        else {
            return false;
        }
    }

Is the error in the way of capturing in txt like this: document.getElementById("un_textbox").value; ?

In the script it always goes by the else , never takes the if , as if it did not have to compare the "hello"

    
asked by Necroyeti 26.07.2017 в 17:39
source

3 answers

1

I think your problem is when you try to get the value of the TextBox, try with this code var txt = document.getElementById('<%=un_textbox.ClientID%>').value;

In case you want to check that your line of code brings you a log to your javascript and look at it in the browser with the F12 option and the console tab.

console.log("Valor Text:" + txt);

    
answered by 26.07.2017 в 17:47
1

To identify a WebForms control you must use the property ClientId of control un_textbox :

  function comprueba(control) {
            var txt = document.getElementById(control).value;
            if (txt == "hola") {
                return confirm("Confirme el postback");
            }

            else {
                return false;
            }
        }

Update:

As you mention, you have the function in the master and control another page. What you can do is then pass the control id as a parameter to the function when you click:

<asp:Button ID="Button1" runat="server"
        Text="Pulsa"
        OnClientClick='return comprueba("<%= un_textbox.ClientId %>");' /> 
    
answered by 26.07.2017 в 17:48
0

It's good that you specify that part, well up to that point we already have something more compressible to work on I recommend that you do a generic method in charge of receiving the id what I mean is that your script receives the controlID

function comprueba(controlId ) {
 jqControl = eval("'#" + controlId + "'");
    var txt = $(jqControl).val();
    if (txt == "hola") {
        return confirm("Confirme el postback");
    }
    else {
        return false;
    }
}

When you call your method you simply send the ID. comprueba(un_textbox.id);

    
answered by 26.07.2017 в 18:10