submit button does not post when its attributes were changed - javascript

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()
}

Related

How to confirm a firm but set a function in-between?

I got a script that checks every form in my app and if there is one, that gets submitted, it will prevent the submission, toggles a loading screen and then submits the form.
<script>
document.addEventListener('DOMContentLoaded', () => {
const forms = document.querySelectorAll('form');
forms.forEach((form) => {
form.addEventListener('submit', (e) => {
e.preventDefault();
document.getElementById('loading').classList.toggle('hidden');
form.submit();
})
});
});
</script>
This works perfectly but for some forms (like a deletion button) I want to ask to user if this is really what he wants to do:
<form method="post" action="<?=base_url('clients/' . $meeting->cid);?>" onsubmit="return confirm('Are you sure?');">
<input type="hidden" name="delmeeting" value="<?=$meeting->id;?>">
<input type="submit" value="Delete" class="button">
</form>
This is in conflict with the first script. The alert gets shown correct but when I cancel it, the first script comes into place and submits.
How can I handle this?
What is important to me:
display the loading div every time for each form
having the possibility to have forms with and without a confirm window
keeping the code small
having individual texts for the confirm
Got it:
const forms = document.querySelectorAll('form');
forms.forEach((form) => {
form.addEventListener('submit', (e) => {
if (form.onsubmit === null) {
e.preventDefault();
document.getElementById('loading').classList.toggle('hidden');
form.submit();
}
})
});
``

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.

JavaScript Form Submit Value

I have a legacy HTML form (that i dont control) that looks like this:
<form action="submit_action" method="get">
<textarea rows="4" cols="40" name="textarea1"></textarea>
<input type="submit" value="Submit" name="result" />
<input type="submit" value="Cancel" name="result" />
</form>
I need to read the values out of this form and do a HTTP POST to a REST API service. I wrote a function that would read out the input elements from the form and create a object from them like this:
const form = this._elementRef.nativeElement.querySelector('form');
form.onsubmit = (event) => this.onFormSubmit(event);
function onFormSubmit() {
event.preventDefault();
const action = form.attributes['action'].value;
let result = Object.keys(form.elements).reduce((acc, k) => {
const element = form.elements[k];
acc[element.name] = element.value;
return acc;
}, {});
console.log('Form Result', action, result);
}
In a classical form submit, the button that triggered the submission is passed a parameter. In this example: https://www.w3schools.com/tags/att_button_name.asp you see when you click the FORM it passes the button that was clicked in the post.
Is there a better way to do this so that I can read that out?

form.submit() not working

I need to do something to use the ruby cgi to output something.
As such form must be submitted first followed by the js to alter the element values.
Using the form.submit() does not work in my case.
Using the simple below example below to output the click me values after submitting the form.
When the form.submit() function is run,the js will not work on click me.
Form onsubmit method cannot be used as it calls the javascript function first before submitting the form(Must submit the form first then call the JS function to carry out something)
Any idea to resolve this:
NOTE:MUST SUBMIT FIRST
$(document).on('click','#afterbutton',function() {
var form = document.getElementById("myForm");
//form.submit();
document.getElementById("test").innerHTML = "afterbutton";
});
$(document).on('click','#beforebutton',function() {
var form = document.getElementById("myForm");
//form.submit();
document.getElementById("test").innerHTML = "beforebutton";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="submit" value="formSubmitbutton" id="submit"><br>
<button id="beforebutton">beforebutton</button><br>
</form>
<button id="afterbutton">afterbutton</button><br>
<p id="test">click me</p>
OK easy problem , you make a simple mistake when you give an input the id submit you override the form.submit method if you look at the console in the devtool you'll see something telling you that
form.submit is not a function
so to solve this problem change the id of your first input instead of submit to something else like submit123
<input type="submit" value="formSubmitbutton" id="submit123"><br>
look at the code below and tell me what you think
$(document).on('click','#afterbutton',function(event) {
event.preventDefault();
var form = document.getElementById("myForm");
form.submit();
document.getElementById("test").innerHTML = "afterbutton";
});
$(document).on('click','#beforebutton',function(event) {
event.preventDefault();
var form = document.getElementById("myForm");
form.submit();
document.getElementById("test").innerHTML = "beforebutton";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="submit" value="formSubmitbutton" id="submit123"><br>
<button id="beforebutton">beforebutton</button><br>
</form>
<button id="afterbutton">afterbutton</button><br>
<p id="test">click me</p>

Need to submit a form without the onsubmit and include the action

Here is a form
<cfoutput>
<form name = "xrefform"
id = "xrefform"
action = ""
method = "post"
onsubmit = "return submitx('#coltop#', '#col#')">
</cfoutput>
There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table
For the first case I have
<input type = "Submit"
name = "SubmitXref"
class = "submitbut"
value = "Submit"
onclick = "aasubmit('xref2.cfm')">
with corresponding javascript:
function aasubmit(target) {
document.xrefform.action = target;
}//end function aasubmit
This works fine.
For the delete case I have
<input type = "Submit"
id = "delbut"
class = "onoffbut"
value = "delete"
onclick = "aasubmit('repdel.cfm')">
This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.
I find references that say using the document.form.submit() method will avoid running the onsubmit function. But I can't figure out how to indicate the action.
Can someone show me how to do this?
After fussing around some more I found the answer:
For the delete button --which needs to evade the onsubmit script --here is the HTML:
<input type = "button"
id = "delbut"
value = "Delete this item"
onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">
And here is the javascript.
function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}
This works perfectly. The ordinary submit honors the onsubmit script, the delete button skips it.
Let's outline your requirements:
One form
Two submit buttons
No JavaScript submit.
If you give each of the submit buttons a name, then you can have a single action page and check which button was clicked.
name="doUpdate" or name="doDelete"
The only name key that will exist in the form scope is whichever submit button was clicked. Use structKeyExists() to check and process accordingly.
Of course, you probably want to use onsubmit="return validateForm()" to call a validation function. If you click on "delete", you might want the user to confirm that was what they wanted to do before processing it. The function validateForm() just needs to return true or false, so you'll still avoid the JavaScript submit().
Do something like this in the form:
<input name="action" value="save" id="action" type="hidden">
<button type="submit" class="button button-basic-green" onclick="document.getElementById('action').value='save';"><span class="fa fa-save"></span> Save</button>
<button type="submit" class="button button-basic" onclick="document.getElementById('action').value='reload';"><span class="fa fa-repeat"></span> Save & Reload</button>
<button type="submit" class="button button-basic" onclick="document.location.href='./';return false;"><span class="fa fa-arrow-circle-o-left"></span> Cancel</button>
Note the default action of "save". Gets you something like:
Then in the singular form-action page, check to see what the form.action is and process accordingly.
<cfif form.action eq "reload">
<cfset loc="page.cfm?id=#form.id#">
<cfelse>
<cfset loc="./">
</cfif>

Categories

Resources