Reputation: 4727
I have written a jquery code where I want the user to put some value in a textbox, and if user does not put any value, the user should be alerted with message to fill the textbox. The problem is that, when I put some value in textbox and submit the button the textbox loses its value and gives me the alert message. Please see the code for your reference. What should I do to prevent from losing its value.
<script type="text/javascript">
$(document).ready(function () {
$('#ctl00_ContentPlaceHolder1_btnSubmit').click(function () {
if ($('#ctl00_ContentPlaceHolder1_ddlGraduation').val() == 'Other' && $('#ctl00_ContentPlaceHolder1_txtOther').val('')) {
alert("Please specify your other education details");
return false;
}
else {
return true;
}
});
});
</script>
Upvotes: 0
Views: 203
Reputation: 167192
When you do the below:
&& $('#ctl00_ContentPlaceHolder1_txtOther').val('')
It resets the textbox. Remove that code. To check the emptiness, do this:
&& $('#ctl00_ContentPlaceHolder1_txtOther').val() === ''
By this way, your full code becomes:
if ($('#ctl00_ContentPlaceHolder1_ddlGraduation').val() == 'Other' && $('#ctl00_ContentPlaceHolder1_txtOther').val() === '') {
Clearing for the second time
else {
$('#ctl00_ContentPlaceHolder1_ddlGraduation').val()
$('#ctl00_ContentPlaceHolder1_txtOther').val()
return true;
}
Upvotes: 1
Reputation: 21887
Using val('')
resets the textbox:
$('#ctl00_ContentPlaceHolder1_txtOther').val('')
I'm assuming you want to check if the value is empty, so use this instead:
$('#ctl00_ContentPlaceHolder1_txtOther').val() === ''
Upvotes: 1