3

I have a textbox with these rules: 1) I populate the textbox.text from a dictionary in session 2) If the user enters a new value, setTextBoxData will save it in the dictionary 3) On entry (on focus) the field text is blanked. 4) On blur, if the field is still empty, I want to set it to the original value.

<asp:TextBox ID="txtNumberEmployees" runat="server" Width="50px" onfocus="this.value='';"  
onchange= "javaScript:$(function()setTextBoxData('NUMBEREMPLOYEES','txtNumberEmployees');});"
onblur="javaScript:restore ('txtNumberEmployees', 'NUMBEREMPLOYEES');"/>

The "restore" function referenced above is:

function restore(control, input) {
    var data = getInputData(input);
    $('#' + control).val(data);
}

getInputData returns the data value correctly. The problem is with the last line.

I have tried many ways to set this, but none seem to work. It should be a simple problem, but I can't get it to work yet.

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
Bob Jones
  • 2,049
  • 5
  • 32
  • 60
  • looks like a syntax error: `javaScript:$(function()setTextBoxData('NUMBEREMPLOYEES','txtNumberEmployees');});` shouldn't it just be `javaScript:setTextBoxData('NUMBEREMPLOYEES','txtNumberEmployees');` – Brian Glaz Oct 26 '12 at 19:22

2 Answers2

1

The problem is ASP.NET will generate an ID that will not be txtNumberEmployees. ASP.NET will generate an ID for your input that will end with txtNumEmployees.

Change this line:

$('#' + control).val(data);

to this:

$('[id$=' + control + ']').val(data);

It will work because this is the Attribute Ends with Selector.

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
  • Thanks. I think of programming as a form of sorcery. If we don't utter the right spell, the brooms will pick up the buckets and playing mischievously. If you don't understand the reference, watch "Fantasia". – Bob Jones Oct 26 '12 at 20:57
  • When it comes to Javascript and jQuery, your comparison is totally valid. And I kinda like it :-) – Adriano Carneiro Oct 26 '12 at 21:47
1

1: Make sure you have no javascript errors. I see there's a missing '{' in the onchange.

2: You can simply pass 'this' as the textbox reference and update it like below:

<asp:TextBox ID="txtNumberEmployees" runat="server" Width="50px" onfocus="this.value='';"  
onchange= "javaScript:$(function(){setTextBoxData('NUMBEREMPLOYEES',this);});"
onblur="javaScript:restore (this, 'NUMBEREMPLOYEES');"/>

then simply set the value like:

$(control).val(data);

3: There are other ways as well to grab an asp.net element like shown here. Find ASP.NET ClientID in jquery

TrekStir
  • 130
  • 8