Question

i have the following cenario:

<asp:HiddenField ID="tab_indexer" runat="server" Value="tab_id" />
<ul class="tabs">
    <li>
        <input type="radio" name="tabs" id="tab_id" />
        <label for="tab_id">Identificação</label>
        <div class="tabcontainer"></div>
    </li>
    <li>
        <input type="radio" name="tabs" id="tab_message" />
        <label for="tab_message">Mensagem</label>
        <div class="tabcontainer"></div>
    </li>
</ul>

Without changing the structure of the page (because my ASP.net Application is already working under this built) i need to, when the input[type="radio"] changes the checked attribute, it saves it's id on the "tab_indexer" hiddenField, and, when the page loads, gets the input[type="radio"] by the Id stores in the HiddenField value and set it checked.

What would be the Javascript for that (i already binded the JQuery js package on the page)?

So far, thanks to another question i did on Stackoverflow, i got:

$(document).ready(function(){
  $("input[type=checkbox]").on('click', function(){$("tab_indexer").attr("value", $(this).attr("id"));});
  $($("tab_indexer").val()).attr('checked', 'checked');
});

But without sucess.

Was it helpful?

Solution

As tab_indexer is a ASP.NET control, you have to use Control.ClientID

In jQuery when you want elemnts to be selected using use ID Selector (“#id”), i.e. prefix id with #

Change your code as

$(document).ready(function () {
    //Get tab_indexer element
    var tab_indexer = $("#" + <%= tab_indexer.ClientID %> );
    //Set checkbox checked with value stored in tab_indexer
    $('#' + tab_indexer.val()).prop('checked', 'checked');

    $("input[type=checkbox]").on('click', function () {
        $(tab_indexer).val($(this).attr("id"));
    });
});

OTHER TIPS

You need to check for type=radio and needs to use proper id selector for tab_indexer, i.e $("#<%=tab_indexer.ClientID") and a logic to set the value

$(document).ready(function(){
  //bind event click
  $("input[type=radio]").on('click', function()
           {$("#<%=tab_indexer.ClientID").attr("value", $(this).attr("id"));});

  //set selected radio button checked
  var selectedRadioId=$("#<%=tab_indexer.ClientID").val();
  $('input[type="radio"]').each(function(){
    if(this.value==selectedRadioId){
      this.checked=true;
    }
  });

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top