views:

225

answers:

3

I have a form with 2 text boxes that all do the same thing. They each call the JQuery function below after each keypress. Since I have 2 textboxes that all do the same thing, I'd like this function to work for both. How do I change this function so that it'll grab the textbox's ID that is currently being edited instead of just the one?

The part where I'd like to insert my textbox's id is '#DocId'.

$(function() {
    $('#DocId').live('keydown', function() {    
        var styleValue = $(this).val();
        $('#tableContent').load(
            '/CurReport/TableResults',
            { style: styleValue }
        );
    })
});

Here is my HTML:

<td><%= Html.TextBox("DocId") %></td>
<td><%= Html.TextBox("LangCode") %></td>

Thank you,

Aaron

A: 

Something like this maybe:

<body>

<textarea class="commonClassName" name="DocId" id="DocId" rows="8" cols="40"></textarea>
<textarea class="commonClassName" name="DocId2" id="DocId2" rows="8" cols="40"></textarea>

<div id="tableContent" style="border: 2px solid #678;padding: 1em;">

</div>
<script type="text/javascript">
$(function() {
    $('.commonClassName').live('keyup', function() {    
        var styleValue = $(this).val();
        // do your own magic here
        $('#tableContent').html(styleValue);
    })
});

</script>
</body>

Using a classname to attach live to both elements here.
I used keyup to avoid a one-character lag.

npup
This works but I need to grab the id and not the class.
Aaron Salazar
You don't need the id at all it seems (you never do anything with it)? And if you do, you can get ahold of it easily with `var currentElemId = this.id;` But i can understand if you'd rather pass 2 ids if you got so few of the elements right now. What i proposed was just a tiny bit more general approach.
npup
A: 

You can get the ID by $(this).attr('id') and change your selector to $('#DocId, #LangCode').

Mark
A: 

Based on your edit, this will work:

$('#DocId, #LangCode, #ThirdBoxIDHere').live('keyup', function() {    
  $('#tableContent').load('/CurReport/TableResults', { style: $(this).val() });
})

This is assuming they all use #tableContent, if not then it'll need to be able to get at an attribute on something to determine that.

Nick Craver
This works just fine and since I have so few textboxes it'll work great. Thank you.
Aaron Salazar