简体   繁体   中英

Post Request when Number is entered into input tag

I am trying to do something fairly simple in javascript using ajax. However, I am new to javascript and could use a hand. I have an input where I need to send a post request whenever someone enters a number into the input section. I am using ajax to do this so I dont have to reload the page every time. This code works individually. But when I put it together with the document.ready(function()) in the head tag, it does not respond when I input numbers into the input field. How could I send a post request whenever someone enters a number ?

$(document).ready(function() {
 var myInput = document.getElementById("pump1_timer");
if (myInput && myInput.value) {
    $.post('/pump1_timer',myInput.value,function(data,status){console.log('${data} and status is ${status}')});
}

    });

The user will need a way to know that they need to submit a number. You could have a variable number of digits for the number, so your code won't know when to submit unless there is a trigger, such as a special character, or button, or pressing the return key. Here is a basic example:

<input type="number" class="form-control" id="number">
<small>Enter a number and then press the return key</span>

We have an input. You need a way for the program to know when the user has entered their final number. You could specify this by prompting the user to press enter once they have entered their number. You can then send a post request:

$('#number').on('change', function() {
        $.post('/someUrl.html', $('#number').val().toString()
        ).done(function(data) {
            alert("Hey we got data");
         }).fail(function(err) {
            alert(err.message);
        }).always(function () {
            alert("Complete");
        });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM