jQuery unable to set Input values when <form> tag is used with <input> type submit

jQuery unable to set Input values when <form> tag is used with <input> type submit
0.0 0

#1

I have the solution to my question but I wanted to see if anyone can help me understand why this is happening. When I submit a form with I am unable to set the value of the text field using jQuery in the submit event handler. However when I use I can change text field values using jQuery val() method.

HTML and JS code is below:

<form>
  <span> Enter the decimal digit to convert the value</span>
  <input type="text" id="num"/>
  <input type="submit"  id="subbtn"  value="Submit"/>
</form>
$(document).ready( function () {
    //Search the parent class, id, or tag and then try to find the <a id="addMore"></a>  as a child
    $('#subbtn').on('click',function () {
       $("#num").val('XYZ');
       
    });
});

The code above does not work. It only works when I change the button input type to “button” instead of “submit”. When I use SUBMIT the input value changes for a few seconds and then disappears.

Thank you for your time and help.

Ramya


#2

Your code is missing, it’s difficult to advise without it.


#3

I cleaned up your code.
You need to use triple backticks to post code to the forum, or else it will not show.
See this post for details.

As for your question:
You are misusing the submit input. A submit input takes data from the form, and processes it (usually it sends a post request to a server). I am not sure that inputs with type submit have a “click” event. They do have a submit one it looks like though:

$('#subbtn').on("submit", () => {
  // try this
})

#4

Thanks for the responses. I did try putting the ’ submit ’ event type in the jQuery on() function . That did not work . The value momentarily appears in the input field and then it gets cleared off. It probably is due to the misuse of submit event as pointed out by @IsaacAbrahamson.