School Boy School Boy - 6 months ago 12
Javascript Question

Input type text value cannot be updated via jQuery

Below is the simple requirement in html, jQuery, servlet

Implementation: Forgot password module


  1. Username text field and send button. --> OK

  2. User enters username and press send button. --> Ok

  3. Fire jquery on click event, post method --> OK

  4. From DB get the security question for username --> OK

  5. Get result in jquery call --> OK

  6. display security question value in text field --> NOK



Some how I feel, the text field is updated and refreshed to old value.
so in my case,

step 1) Text value - placeholder property value

step 2) update from jQuery

step 3) again refreshed to placeholder property value

jQuery

$(document).on("click", "#btnuserName", function() {
$.post("/zmcwebadmin/ForgotPasswordServlet",function(securityQuestion) {
alert("I got the response in ajax "+ securityQuestion);//value is correct
$("input[type=text].txt_securityQuestion").val(securityQuestion); //problem here
console.log("txt_securityQuestion");
});
});


html

<input type="text" id="ForgotPassUname" name="user_name" class="changepassformat"placeholder="Enter Username">

<button class="buttonformat" id="btnuserName" name="btnuserName">SEND</button><br>

<input type="text" id="txt_securityQuestion" name="txt_securityQuestion" class="changepassformat" placeholder="Security Question"><br>

<input type="text" id="SecurityAns" name="SecurityAns" class="changepassformat" placeholder="Enter the Answer">


Entire html code

<body background="../Images/zebra_background.jpg">

<div id="header">
<span style="float: left">ZMC Server </span> <img
src="../Images/zebra_logo.png" width=150px height=50px
style="float: right; padding-top: 5px">
<form id="form_logout">
<input type="image" class="logbuttonformat" id="logoutbtn"
src="../Images/logout_deselected.png" onclick="changeLogoutImage()"
alt="submit" style="padding: auto">
</form>
</div>
<form id="form_forgotpswd" >
<p class="slectedNameformat"> FORGOT PASSWORD </p>
<input type="text" id="ForgotPassUname" name="user_name" class="changepassformat"placeholder="Enter Username">
<button class="buttonformat" id="btnuserName" name="btnuserName">SEND</button><br>
<input type="text" id="txt_securityQuestion" name="txt_securityQuestion" class="changepassformat">
<br>
<input type="text" id="SecurityAns" name="SecurityAns"class="changepassformat" placeholder="Enter the Answer">
<br><input type="button" class="buttonformat" value="SUBMIT">
</form>
</body>
</html>

Answer

You need id selector instead of class selector here as txt_securityQuestion is id of element and not its class:

 $("#txt_securityQuestion").val(securityQuestion);