Issue with JQuery onchange() event
So I have a drop-down list and a text-box:
<table>
<tr>
<td>Group Name: </td>
<td><%= Html.DropDownListFor(m => m.IndicationCalculatorGroupId, DropDownData.IndicationsGroup(SessionManager.Company.EntityID, ICConstants.IndicationsCalculatorGroupType), "", new { propertyName = "IndicationCalculatorGroupId", onchange = "UpdateField(this, false);GroupNameChange();" })%></td>
</tr>
<tr id="newGroupNameRow">
<td>New Group Name: </td>
<td><%= Html.TextBoxFor(m => m.IndicationCalculatorNew开发者_如何学PythonGroupName, new { @class = "economicTextBox", propertyName = "IndicationCalculatorNewGroupName", onchange = "UpdateField(this);" })%></td>
</tr>
</table>
I have JQuery on the page that shows/hides the text-box based on the drop-down selection.
function GroupNameChange()
{
$("#IndicationCalculatorGroupId").change(function() {
if ($("#IndicationCalculatorGroupId option:selected").text() == 'Create a New Group')
{
$("#newGroupNameRow").show();
}
else{
$("#IndicationCalculatorNewGroupName").val('');
$("#newGroupNameRow").hide();
}
});
}
But it seems that the first time you change the drop-down to "Create a New Group", the text-box doesn't show or do anything, it's only when you select some other value and THEN select "Create a New Group" does the code start to work.
What's not wired up correctly?
try to put your code when the page is loaded:
$(function() {
$("#IndicationCalculatorGroupId").change(function() {
if ($("#IndicationCalculatorGroupId option:selected").text() == 'Create a New Group')
{
$("#newGroupNameRow").show();
}
else{
$("#IndicationCalculatorNewGroupName").val('');
$("#newGroupNameRow").hide();
}
});
});
Instead of:
function GroupNameChange()
{
...
}
Use:
$(document).ready(function()
{
$("#IndicationCalculatorGroupId").change(function() {
if ($("#IndicationCalculatorGroupId option:selected").text() == 'Create a New Group')
{
$("#newGroupNameRow").show();
}
else{
$("#IndicationCalculatorNewGroupName").val('');
$("#newGroupNameRow").hide();
}
});
});
Right now GroupNameChange() has to be called once (the first call) for the change handler to be registered. You want that to happen on page load (at the ready event). You don't need the call to GroupNameChange() in the onchange, either. .change() will automatically be wired in. You can remove onchange altogether and call updateField from the .change() handler you have.
Alternatively, if you want to keep GroupNameChange, remove
$("#IndicationCalculatorGroupId").change(function() {
});
and just keep the lines where the function is. This will have GroupNameChange called every time as you've suggested without the other anonymous change handler being called.
The onChange event is triggered once the value has been changed (ie: once you click out the selectbox). You should use the mouseDown() event.
精彩评论