views:

182

answers:

2

I have a ASP.NET MVC project with a large list of input textboxes which I want the user to control them independently. Here is the link how it looks like now.

Here are some things I want to have:

  1. Each enable/disable link only controls each row.

  2. The number of rows is not fixed and it will be generated dynamically. It can be 10 or 20 rows.

What is a generic way to do this?

Here is my code sample:

<script type="text/javascript">

    // first set
    $(document).ready(function() {
        $(".controller").toggle(

    function() {
        $('#target1').removeAttr("readonly");
        $('.controller').empty().append("Disable");
    },

    function() {
        $('#target1').attr("readonly", "readonly");
        $('.controller').empty().append("Enable");
    });
    });

</script>

<ul>
    <li>text field:
        <input type="text" readonly="readonly" id="target1" value="Change me" />
        <a href="#" class="controller">Enable</a><br />
    </li>
    <li>text field:
        <input type="text" readonly="readonly" id="target2" value="Change me" />
        <a href="#" class="controller">Enable</a><br />
    </li>
    <li>text field:
        <input type="text" readonly="readonly" id="target3" value="Change me" />
        <a href="#" class="controller">Enable</a><br />
    </li>
    <li>text field:
        <input type="text" readonly="readonly" id="target4" value="Change me" />
        <a href="#" class="controller">Enable</a><br />
    </li>
</ul>
A: 
$('li .controller').click(function() {
    $(this).prev().removeAttr('readonly');
});

Or as following your example:

$(document).ready(function() {
    $(".controller").toggle(
        function() {
            $(this).text("Disable").prev().removeAttr("readonly");
        },
        function() {
            $(this).text("Enable").prev().attr("readonly", "readonly");
        }
    );
});
David
Thank you David.
Daoming Yang
A: 

Try this

$(document).ready(function() {
    $(".controller").toggle(
        function() {
            $(this).prev("input[type='text']").removeAttr("readonly");
            $(this).text("Disable");
        },
        function() {
            $(this).prev("input[type='text']").attr("readonly", true);
            $(this).text("Enable");
    });
});
rahul
Hi rahul, thanks. What's the difference between .prev("input[type='text']") and .prev()?
Daoming Yang