Jahan Ahmed Abbasi Jahan Ahmed Abbasi - 2 months ago 10
ASP.NET (C#) Question

passing asp.net control id to jquery function by parameter

how can i pass asp.net control id dynamically to jquery function parameter?
here is how i am trying to do that

SelectedDivAnimation('#'+<%=txtFirstName.ClientID%>);
SelectedDivAnimation('#'+<%=txtLastName.ClientID%>);

function SelectedDivAnimation(aspControl) {
$(controlid).on('focus', function () {
$(this).css({'width':'100%','transition':'1s'});
});
$(controlid).on('focusout', function () {
$(this).css({ 'width': '50%', 'transition': '1s' });
});
}


i even try this

SelectedDivAnimation('#<%=txtFirstName.ClientID%>');
SelectedDivAnimation('#<%=txtLastName.ClientID%>');


when i run this it doesn't work as expected and nothing happens.

Answer

Everything between <% and %> happens on the server so all you need to do is drop the + and move the second quote to after the %> -

SelectedDivAnimation('#<%=txtFirstName.ClientID%>');
SelectedDivAnimation('#<%=txtLastName.ClientID%>');

Assuming that it is in an ASP page.

So suppose that txtFirstName.ClientID is set to client_a the server will replace <%=txtFirstName.ClientID%> with client_a before sending it to the client. So the client will actually see this -

SelectedDivAnimation('#client_a');

If you are seeing the correct id's on your client then that's good, however you have another issue -

function SelectedDivAnimation(aspControl) {
    $(controlid).on('focus', function () {
        $(this).css({'width':'100%','transition':'1s'});
    });
    $(controlid).on('focusout', function () {
        $(this).css({ 'width': '50%', 'transition': '1s' });
    });
}

You pass the variable aspControl into your function however you are using a variable called controlid; you probably want to set them both to be the same, i.e. -

function SelectedDivAnimation(aspControl) {
    $(aspControl).on('focus', function () {
        $(this).css({'width':'100%','transition':'1s'});
    });
    $(aspControl).on('focusout', function () {
        $(this).css({ 'width': '50%', 'transition': '1s' });
    });
}
Comments