Search code examples
javascriptpaypaldjango-formsgetelementbyidonload

Using onload with document.getElementById to fill HTML form


I have the following code for a paypal payment in Javascript -

onApprove: function(data, actions) {
    return actions.order.capture().then(function(details) {
    window.location.replace("www.mysite.com/success");
    document.getElementById("payment_no").value='1234';
  });
},

This redirects the user once a payment has been made. The next page has a form with a "payment_no" field which I wanted to fill once redirected with the value in the script.

At the moment this is not working and I think it is because the page hasn't loaded before it is trying to post the value. I've looked into using onload but just don't understand how to use it inside this script. Is anyone able to help?

Here is my form.py just in case that helps -

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField(widget= forms.EmailInput(attrs={'id':'email'}))
    payment_no = forms.CharField(max_length=50, widget= forms.TextInput(attrs={'id':'payment_no'}))

    class Meta:
        model = User
        fields = ['email', 'payment_no', 'password1', 'password2']

Solution

  • Using onload is just like using any other DOM event. Here is an example I made

    <script>
      const OnLoadFunction = () =>{
        document.getElementById('form-input').value = "1234";
      }
    </script>
    <body onload="OnLoadFunction();">
      <form>
        <input type="text" id="form-input"/>
      </form>
    </body>
    

    This should change the value of an input field on the load of the document. From the looks of your code, it seems you are using one function to do two jobs. I would use two functions so that you can call one when www.mysite.com/success loads

    1: To change the location of the page

    2: Manipulate the Input Field