简体   繁体   中英

Set asp:HiddenField value on anchor click in jQuery

I have a HiddenField and two anchors:

<asp:HiddenField ID="hfForm" runat="server" />

<a href="javascript:;" id="signup" onclick="signupClick()">Sign Up</a>
<a href="javascript:;" id="login" onclick="loginClick()">Login</a>

I'm trying to set the value of clicked anchor to the hidden field as like:

$(document).ready(function() {            
    $("a").click(function() {
        $("<%= hfForm.ClientID %>").val($(this).val());
    });
});

But it's getting empty in page_load on postback:

if (this.IsPostBack)
{
    string val = hfForm.Value; // getting "" val
}

How I can solve this?

Any help will be appreciated!

Updated:

JavaScript functions (Where I'm setting a value to the asp:Label value):

function loginClick() {
  document.getElementById('<%=lbl.ClientID%>').innerText = 'Login';
}
function signupClick() {
  document.getElementById('<%=lbl.ClientID%>').innerText = 'SignUp';
}

it's an anchor you should use $(this).text() rather than .val() inside the click event, you can use .val() on elements that have a value attribute, change your

 $("<%= hfForm.ClientID %>").val($(this).val());

to

 $("<%= hfForm.ClientID %>").val($(this).text());

EDIT

You have signUp() and signOut() on the same anchors where are those functions and what do they do ? and why are you not utilizing those funtions to assign the value to the hidden field.

and you are using href value as href="javascript:;" instead it should be href="javascript:void(0);" or you can add the e.preventDefault() inside your click event.

Your function will look like below

$(document).ready(function() {            
    $("a").on('click',function(e) {
        e.preventDefault();
        $("<%= hfForm.ClientID %>").val($(this).val());
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM