I have a simple form with two field 1. Amount
and 2. Creditcard type
(Dropdown). Functionality wise dropdown is working fine and whatever I select I am able to get that in my backend code. But somehow I am not able to access the selected value of dropdown using JQuery. Kindly guide me. Below is code snippet
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2 required" })
<div class="col-md-10">
@Html.TextBox(Model.ModelPropertyPrefixName + "Amount", Model.Amount,
new { @class = "form-control required" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CreditDetails.CreditCard, htmlAttributes: new { @class = "control-label col-md-2 required" })
<div class="col-md-10">
@Html.DropDownList(Model.ModelPropertyPrefixName + "CreditDetails.CreditCard", SimUtils.PayTypesSelect,
new { @class = "form-control", id = Model.ModelPropertyPrefix + "CreditDetails.CreditCard" })
</div>
</div>
Some of my attempts to get the value or the text of dropdown. I always get output as undefined
.
var x = $('#CreditDetails.CreditCard :selected').val();
var t = $('#CreditDetails.CreditCard').val();
var f = $('#@(Model.ModelPropertyPrefixName + "CreditDetails.CreditCard") option:selected').val();
$("#SelectedCountryId option:selected").text()
var d = $('#CreditDetails.CreditCard option:selected').text();
var s = $('#@(Model.ModelPropertyPrefixName + "CreditDetails.CreditCard") option:selected').text();
I am successfully able to get the amount value entered by the user
var amountText = $('#@(Model.ModelPropertyPrefix + "Amount")').val() // WORKS FINE
Generated Code in Front End:
<select class="form-control" data-val="true" data-val-number="The field Card Type must be a number." data-val-required="The Card Type field is required." id="CreditDetails.CreditCard" name="CreditDetails.CreditCard"><option selected="selected" value="-6">Amex</option>
<option value="-4">Discover</option>
<option value="-3">Master Card</option>
<option value="1">test</option>
<option value="-5">Visa</option>
</select>
<div class="col-md-10">
<input class="form-control required" data-val="true" data-val-number="The field Amount must be a number." id="Amount" name="Amount" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="Amount" data-valmsg-replace="true"></span>
</div>
I know the dropdown and the amount code looks dirty but bear with me here. Everything is working fine. I just want to access the dropdown value before the form gets submitted. But I don't know why I am not able to do so.