Function results only lasting a millisecond - javascript

Im just getting into javascript and Im writing a script thats supposed to hide a submit button and show a similiar button which shows the site is processing the info. The fucntion below gets the result im looking for but only for a millisecond before returning to normal. Im not sure if the fuction is incorrect or if I have to add a sleep command or something.
<form>
<input placeholder="ID"><br>
<button id="submit" onclick="send()" type="">Submit</button>
<button id="loading"><i class="fa fa-circle-o-notch fa-spin"></i> Submiting</button>
</form>
<script type="text/javascript">
function send() {
var submit = document.getElementById('submit');
var loading = document.getElementById('loading');
if (submit.style.display === "none") {
loading.style.display = "block";
} else {
submit.style.display = "none";
loading.style.display = "block";
}
}

Your "Submit" button submits the form, which requests it again and renders the original version. To prevent this first add a parameter to your send() function which holds the data above the event:
function send(event)
Now add the following line at the end of your function:
event.preventDefault()
This prevents the form from being submitted.

Related

Cannot re-enable Submit button in Javascript after it has been clicked. ".querySelector().disabled = false" does not seem to work

I am trying to create a simple google search bar in my website. It works fine. However, I am accounting for user error, and for some reason I cannot re-enable my submit button once it is clicked, under the condition that no input is provided. Please see Javascript code below.
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
setTimeout(() => msg.remove(), 3000);
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
As you can see, if no text is input, it will let the user know they will need to enter an actual search query. However, after that point, the submit button just wont work again.
I tried using .querySelector().disabled = false; , as well as .removeAttribute("disabled"), but nothing is working. What exactly am I missing here, to re-activate the submit button once it was clicked with no input?
Your button works just fine. You just remove the complete element and then the msg = document.querySelector(".msg"); doesn't find anything. In addition i would leave the timeout out and let the message there until the user writes something.
You should do it like that:
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
msg.innerHTML= '';
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
When button type is set on submit value, it will send the information to the server anyway. (not if you use preventDefault() method!)
My suggestion is to change button type to button and then write an onclick event for it and check the validation there , if everything was right then call for form submit event!
This is how you can prevent incorrect information from being sent into the server side and avoid the errors that it can cause.

submit button does not post when its attributes were changed

I am using a form and a submit button in it to call a post request to server in html
In submit button, I use onclick event to change something in UI before posting request. Everything is fine when I do not change anything to the submit button, it posts request successfully.
But if I change anything in submit button such as value, disable attribute,... then it does not post request
Here is my code
<form action="url"method="post">
<input type="submit" onclick="return onClick(event)">
</form>
js code that does not post request
function onClick(e) {
const submit = e.target // or = this
submit.value = "Clicked"
submit.disabled = true
return true
}
js code that posts request successfully
function onClick(e) {
alert("Clicked")
return true
}
Could somebody tell me the reason why it does not post successfully and how to post with UI change like above?
You need to use submit method to achieve the result.
-> Assign id to the button and form element then get the element like,
const btn = document.getElementById('btn');
const form = document.getElementById('form');
It is always recommended to use addEventListener() method in javascript instead of making it in HTML template.
form.addEventListener('submit', onSubmit)
-> Now you can change the value of an attribute in submit method like,
function onSubmit(){
btn.value = "Clicked";
btn.disabled = true;
return true
}
Working snippet as follows,
const btn = document.getElementById('btn');
const form = document.getElementById('form');
function onSubmit(){
btn.value = "Clicked";
btn.disabled = true;
return true
}
form.addEventListener('submit', onSubmit)
<form id="form" action="url" method="post">
<input type="submit" id="btn">
</form>
Whether a form sends a POST or GET request is based on its method attribute. Try changing your form to
<form action="url" method="post">
<input type="submit" onclick="return onClick(event)">
</form>
another solution from me, I found it myself and many thanks to #Maniraj Murugan for your help above: use input type="button" instead, and in onclick event, use form.submit() to submit manually
<form action="url"method="post">
<input type="button" onclick="return onClick(event)">
</form>
and in onClick event
function onSubmit(e){
const btn = e.target
btn.value = "Clicked"
btn.disabled = true
const form = document.getElementById('form')
form.submit()
}

Javascript Popup from Code Behind Without Button Onclick Action

I have read numerous threads and cannot figure this one out as they all relate to calling a javascript with a button click. I have a simple javascript popup that I want to call during my vb code in an asp.net project. Each time I call the javascript, the program continues on, and my variable from the popups do not get calculated.
I need the program to stop, wait for the popup reply, and then based upon the reply, continue on. What am I missing? The first one runs fine as it is conditional based upon a button OnClientClick method, but the next two are in the code behind. I need the program to stop, wait for a response, and continue based upon the response. This doesn't happen and using ScriptManager.RegisterStartupScript or other javascript calls as they aren't stopping the program to wait for the response. The second two do not have a button click event to trigger them, only a programming code call.
HTML Code:
<script type="text/javascript">
function Payment() {
var payment_value = document.createElement("INPUT");
payment_value.type = "hidden";
payment_value.name = "payment_value";
if (confirm("Are you sure you want To Cancel this Payment?")) {
payment_value.value = "Yes";
} else {
payment_value.value = "No";
}
document.forms[0].appendChild(payment_value);
}
</script>
<script type="text/javascript">
function LateFee() {
var latefee_value = document.createElement("INPUT");
latefee_value.type = "hidden";
latefee_value.name = "latefee_value";
if (confirm("This payment is over 30 days, do you want to add a Late Fee ($99.00) to this incident?")) {
latefee_value.value = "Yes";
} else {
latefee_value.value = "No";
}
document.forms[0].appendChild(latefee_value);
console.log(latefee_value)
}
</script>
<script type="text/javascript">
function LateFeePrint() {
var latefeeprint_value = document.createElement("INPUT");
latefeeprint_value.type = "hidden";
latefeeprint_value.name = "latefeeprint_value";
if (confirm("Late Fee Updated Successfully, do you want to print a Late Fee Notice?")) {
latefeeprint_value.value = "Yes";
} else {
latefeeprint_value.value = "No";
}
document.forms[0].appendChild(latefeeprint_value);
}
</script>
<h2><%: Title %></h2>
<p class="text-danger">
<asp:Literal runat="server" ID="Literal1" />
</p>
VB,net Code:
If NumDays > 30 And TempLateFee <> "$99.00" Then
Dim LateFeeValue As String = Request.Form("latefee_value")
'Call Javascript and popup the modal
ScriptManager.RegisterStartupScript(Me, Page.GetType, "LateFeeCall", "LateFee()", True)
'use the result to calculate the late fee
If LateFeeValue = "No" Then
ElseIf LateFeeValue = "Yes" Then
AccountBalance = 0
Call UpdateLateFee()
Call GetAlarmInfo()
Call LoadAlarmInfo()
Call LoadBalanceInfo()
End If
End If

jQuery submit() with spin.js is preventing form from submitting?

I have a form that submits just fine, but when I add jQuery code to show a loading div using spin.js everything stops working.
<form id="search_form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<!-- Form inputs here -->
...
<input id="exam_search" type="submit" name="submit" value="Search" />
Once I add the following code the form stops submitting and nothing happens. The loading div shows for a brief moment and then goes away like expected, but it seems like the form isn't actually submitting anymore.
var opts = // Array of options
var spinner = null;
$("#search_form").submit(function() {
spinner_div = document.getElementById('spinner');
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
} else {
spinner.spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
}
});
If I change all of that code in the submit event to this:
$("#search_form").submit(function() {
alert ("form submitted");
});
It shows the alert and then returns the results of the form submission just fine.
What am I doing wrong here?
EDIT
I saw in the jQuery docs for submit() that I shouldn't use the name "submit" on the input field. I tried changing that as well with no luck.
Well I'm not sure why but simply doing this worked:
$("#search_form").submit(function() {
var spinner_div = document.getElementById('spinner');
var spinner = new Spinner(opts);
spinner.spin(spinner_div);
});

Javascript OnClick before submit button

Im having an issue getting some bit of code to run before the page submits.
When i change the return value to true to submit the form, the code above doesn't run. The way it is now, the code runs and the page is refreshed. I want to pass a true variable to submit the form Any ideas?
function buildMessageC() {
//Create an ePOS-Print Builder object
var builder = new epson.ePOSBuilder();
//Create a print document
builder.addTextLang('en')
builder.addTextSmooth(true);
builder.addTextFont(builder.FONT_A);
builder.addTextSize(1, 1);
builder.addText(document.getElementById('receipt').textContent);
builder.addFeedLine(1);
builder.addCut(builder.CUT_FEED);
//Acquire the print document
var request = builder.toString();
//Set the end point address
var address = 'http://192.168.1.69/cgi-bin/epos/service.cgi?devid=counter_printer&timeout=10000';
//Create an ePOS-Print object
var epos = new epson.ePOSPrint(address);
//Send the print document
epos.send(request);
return false;
The form button
<sf:form onsubmit="return buildMessageC()">
<input class="addToOrderButton button blue large expand" value="Place Order" name="_eventId_placeOrder" type="submit"/>
</sf:form>
Clarification
function doSubmit(){
buildMessageC();
return false;
} gives me print out and reloads the same page not submiting the form
function doSubmit(){
buildMessageC();
return true;
} doesn't print yet submits the form

Categories

Resources