-2
<form action="">
    <input type="text" id="id" name="id" value="">
    <input type="password" id="pw" name="pw" value="">
</form>

<script>
    $('#id').val('darth-vader');
    $('#pw').val('i-am-your-father');
    $('form').submit();
</script>

I know it would be very ridiculous question, anyway, what I am trying to do is save id and password to local storage or javaScript values, and then automatically log on. (without Server languages, I'm just making prototype on client side)

Of course, the avobe page reload infinitely, How can I do this correctly?

JuntaeKim
  • 5,364
  • 15
  • 54
  • 97

3 Answers3

0

Add event.preventDefault(); to the submit function. Check details here: https://api.jquery.com/submit/

It stops the default event from triggering, which in case of a submit is reloading the page.

Paul van den Dool
  • 2,498
  • 2
  • 16
  • 35
  • But that is only to used in callback function I think, How can I use that above code? The submit would be fire automatically, – JuntaeKim Jan 15 '17 at 07:48
0

You can: A) handle the submit event and make sure to return false B) use an ID'd button and bind a 'pseudo-submission' function to the button's click event.

My personal preference is B for simple cases, but using the native submit event allows the browser to handle native validation (such as required, max/mid-length, etc). If you're going to use A, you may return false or use event.preventDefault() to stop the page from reloading. Nothing further is required if you use B.

0

Self answer

problem :

<form action="">
    <input type="text" id="id" name="id" value="">
    <input type="password" id="pw" name="pw" value="">
</form>

<script>
    $('#id').val('darth-vader');
    $('#pw').val('i-am-your-father');
    $('form').submit();

    $('form').submit(function(e){
        e.prenventDefault();
    });
</script>

solved :

<form action="">
    <input type="text" id="id" name="id" value="">
    <input type="password" id="pw" name="pw" value="">
</form>

<script>
    $('#id').val('darth-vader');
    $('#pw').val('i-am-your-father');

    $('form').submit(function(e){
        e.prenventDefault();
    });

    $('form').submit();


</script>
JuntaeKim
  • 5,364
  • 15
  • 54
  • 97