HTML Form Linking - html

As a newbie to HTML, I am seeking your help and guidance.
I am trying to create a page which will have only two Buttons like:
Create User and Log In
Depending on which button is clicked a form will be processed.
It's similar to a concept of Register or LogIn.
PS: I am trying to use java for the script part
Please Guide me to achieve the above mentioned scenario

As I understood from your descriptions you have a page with only two buttons in it. So there is no form in this page but then when you click on any of buttons they lead you to another page with a form.
then you can have a tag like this:
<a href="">
<div style="width: 60px; height: 30px; border: solid 1px; text-align: center">Log In</div>
</a>

The below code will send different data to the server, depending on which button was clicked
var formElm = document.forms[0];
formElm.addEventListener('submit', function(){
return false; // disable normal form submit so the page won't refresh
})
// when button number #1 gets clicked, send the form to the server
formElm.querySelector('.do1').addEventListener('click', function(){
fetch('/url',{ method:'POST', body:new FormData(formElm) })
.then(function(response) {
console.log('request succeeded with JSON response', JSON.parse(data))
})
.catch(function(error) {
console.log('request failed', error)
})
});
// when button number #1 gets clicked, do something else..you choose.
formElm.querySelector('.do2').addEventListener('click', function(){
// send something else to the server
// ...
});
<form>
<input name='something' value='foo'>
<button type='button' class='do1'>button 1</button>
<button type='button' class='do2'>button 2</button>
</form>

Related

react js form getting submitted twice

I have below code which calls save form
<div className="col-md-4">
<button onClick={saveCredit} className="btn btn-success">
Submit
</button>
I have onclick handler function as
const saveCredit = () =>{
//validate form
// call api to save form attributes
CreditTransactionDataService.create(data)
.then(response => {
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
after successful save , I will show successful message as below.
{submitted ? (
<div>
<h4>You submitted successfully!</h4>
<button className="btn btn-success mr-2" onClick={newCreditTransaction}>
Add
</button><Link style={{ fontWeight: 'bold' }} className="btn btn-warning" to={"/creditTransactionList"}>
return to List
</Link>
</div>
)
but the problem is, my form is getting submitted twice, and creating duplicate records with same values.... couple of save options, i restricted with unique key column at database level, but few tables still need to handled at code level..
I´m unable to reproduce it in codepen, but one solution a little bit hacky could be check in the method if it is submitted already
const saveCredit = {
//Check if it is submitted
if(!submitted){
//validate form
// call api to save form attributes
CreditTransactionDataService.create(data)
.then(response => {
setSubmitted(true);
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
}
This may not be the best but could do the job
Also a thing I did notice is that your saveCredit function not look like a function.
Why not declare as an arrow function? Like:
const saveCredit = () => { //Your code }
Your button doesn't need onClick event handler if it's responsible for submitting a certain form. You should add type="submit" to button and onSubmit to form tag itself.
You should go for this approach to handle submitting correctly (clicking of the button or hitting enter by the user are covered).

how to tell which button was clicked in post request with node backend

I have a node application, where on the frontend, I have multiple buttons that activate the same post route as specified by the formaction attribute below:
<button type="submit" formaction="/specifiedroute">-</button>
However, I want to be able to tell which button was clicked within the post route. Is there anyway I would be able to access the name or id attributes of the button within the post route (perhaps within the request object)? If not, would the only way to identify the buttons be to add a parameter to the formaction as below:
<button type="submit" formaction="/specifiedroute?redbutton">-</button>
Note all these buttons exist in one form (I can't change this) and I can't just use a hidden input field.
May be you should try this
<button type="submit" formaction="/specifiedroute?button=red">Red</button>
<button type="submit" formaction="/specifiedroute?button=green">Green</button>
<button type="submit" formaction="/specifiedroute?button=blue">Blue</button>
// NodeJS
Controller
app.post('/specifiedroute', (req, res) => {
let buttons = {
"red": "Red Button Clicked",
"green": "Green Button Clicked",
"blue": "Blue Button Clicked"
}
let reqButton = req.query.button;
res.send(buttons[reqButton])
})
The name and value of the submit button used to submit a form will be included in the submitted form data.
<button formaction="/specifiedroute" name="foo" value="minus">-</button>
and on the server
if (req.body.foo === 'minus')

button submits email, onclick call invoke function, redirects to a index page and display message

How can I display a message on the redirected page after submit a form?
I have a form on my page that after submitting the form it redirects to the index.html. After redirecting I have a div with a message that is set to display:none. What I'm trying to do is to set to display:block the div for a couple seconds then set the display back to none. Here is what I have so far:
<input type="hidden" name="_next" value="index.html">
<button onclick="emailSubmit()" class="sub-button" type="submit" value="Send Message" style="margin-bottom: -35px;">Send Message</button>
<script>
function emailSubmit() {
setTimeout(function(){ document.getElementById("confirmation").style.display = "block"; }, 500);
setTimeout(function(){ document.getElementById("confirmation").style.display = "none"; }, 3000);
}
</script>
Cold You please share Your code? How does your html file Look like?
Where Do You keep Your message?
As far You only hidden and show dom element. It is Look like the div is empty.

Click function/wiring up future elements are not working after ajax Call

On submit of search, message with cancel button will display then via ajax data table will display. On click of cancel button loaded ajax result should get clear. But it is not getting cleared.
Kindly find my code
html file
<div class="report_result" >
<p class="report_loader" >Loading please wait...
<button type="button" aria-label="Close">
<span class="stop_load" aria-hidden="true"><u>Cancel</u></span>
</button>
</p>
</div>
js file
//wiring up future elements
$(document).on('click', '.report_result > .stop_load', function() {
$('#result').hide();
});
//using click function
$(".stop_load").click(function(){
$('#result').hide();
});
ajax call
ajaxStop: function() {
$(".report_result").hide();
}
.......
beforeSend:function() {
$('report_result').show();
},
.......
But it's not working after loading ajax . If I call before ajax call both the code works. Kindly help..
Did you try it with the body tag (or just a higher existing parent element) in the selector as well? Like:
$('body').on('click','.report_result > .stop_load',function(){
$('body #result').hide();
});
$('body').on('click','.stop_load',function(){
$('body #result').hide();
});

two submit buttons in one form executing two different servlets

i have a form having two submit buttons.
one for creating a user and other for logging in an existing user.
how can i fire two different servlets from these two buttons keeping them in one single form??
like if create button is clicked then create.java is executed
and if login button is fired then login.java is executed
If you want to go with JavaScript, this is an example using jQuery ajax:
$(document).ready(function() {
$('#id_of_your_button').click(function() {
// do some stuff here, e.g.
var str = $("#your_html_form").serialize();
$.ajax({
type: "POST",
url: "url_to_your_file",
data: str,
success: function(msg) {
//...
}
});
}
// prevent the default action, e.g., following a link
return false;
});
});
EDIT:
if you want to do it without JavaScript, you can do it like <input type="button" value="register">
Otherwise, if you want the form submitted right away, you could only take two forms, or use JavaScript (also in other ways, as you could e.g. change the action-url with JavaScript depending on which button the user clicks, etc)...
... but there is only one "Submit" button allowed per HTML-form.
Check this tutorial about the onclick event for HTML buttons: Here
Example:
<script type="text/javascript">
function copyText()
{
document.getElementById("field2").value=document.getElementById("field1").value;
}
</script>
<button onclick="copyText()">Copy Text</button>
Source