This question already has answers here:
What is the default button type?
(3 answers)
What's the point of <button type="button">?
(6 answers)
Closed 3 years ago.
I have a button inside a form in asp.net core. The form has it's own submit button which is supposed to trigger the create action when it is clicked. I have another button insde the form which is just calling a piece of javascript code. I don't understand why when I click on the button to call the javascript, the post action "Create" is called also afterwards. That is I see the alert box and then I get redirected by the action. I just want to display the alert without this triggering the action method.
function ValidateName() {
var name = document.getElementById('btnName').value;
alert(name);
}
<form asp-action="Create">
<div class="form-group">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="row">
<div class="col-md-6 text-center">
<button id="btnName" class="btn btn-primary btn-md center-block" Style="width: 150px;" OnClick="ValidateName()">Validate</button>
</div>
</div>
</div>
<div class="form-group">
<input type="submit" value="Créer" class="btn btn-default" />
</div>
</form>
you need to prevent the default behavior
function ValidateName(e) {
e.preventDefault();
var name= document.getElementById('btnName').value;
alert(name);
}
Related
This question already has answers here:
How to delegate focus event? [duplicate]
(1 answer)
Focus and blur jQuery events not bubbling
(3 answers)
Closed 17 days ago.
I was trying to initialize datePicker on dynamically added content. When i focus on datepicker, datepickerloaded but when i add a dynamic content, datePicker doesn't load for that content.
Here is the code for jquery datePicker on focus code.
$('document').on('focus',".datepicker", function(){
$(this).datepicker({ dateFormat: 'yy-mm-dd' });
});
HTML Part:
<div class="row" style="align-items: center;">
<div class="col-md-10 dynamic-field" id="dynamic-field-1">
<div class="row" >
<div class="col-md-3">
<div class="form-group">
<label for="field" class="hidden-md">Type Of Cultivation*</label>
<input type="text" id="field" class="form-control" name="type_of_cultivation[]" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="field" class="hidden-md">Cultivation Date</label>
<input type="text" class="form-control datepicker" placeholder="2023-02-28" name="cultivation_date[]" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Harvest Date</label>
<input type="text" class="form-control datepicker" placeholder="2023-03-28" name="harvest_date[]">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Quantity</label>
<input type="text" class="form-control" name="quantity[]">
</div>
</div>
</div>
</div>
<div class="col-md-2 mt-30 append-buttons">
<div class="clearfix">
<button type="button" id="add-button" class="btn btn-secondary float-left text-uppercase shadow-sm"><i class="fa fa-plus fa-fw"></i>
</button>
<button type="button" id="remove-button" class="btn btn-secondary float-left text-uppercase ml-1" disabled="disabled"><i class="fa fa-minus fa-fw"></i>
</button>
</div>
</div>
</div>
It appears that there is an issue with initializing the datepicker on dynamically added content. The current implementation binds the datepicker to the focus event of elements with the class .datepicker. However, this approach is not effective when new content is added dynamically, as these elements are not present in the DOM at the time the binding occurs.
To address this issue, a solution would be to manually trigger the focus event on the newly added elements after they have been added to the DOM. This can be accomplished through the use of a click handler on the #add-button element, as follows:
$('#add-button').click(function() {
// Add dynamic content here
// Manually trigger the focus event on newly added elements with class
//.datepicker
$('.datepicker').trigger('focus');
});
I'm trying to create a confirmation dialog using something like this: confirm('Are you sure?') inside of my EJS form but I don't know where and how to get it to work correctly.
Here is the code I have so far for my EJS template:
<div id="popupAddUser" class="addUser">
<div class="card h-100">
<div class="row">
<div class="col-7"><h2>Create New User</h2></div>
</div>
<div class="card-body">
<form method="POST" id="formAddUser" action="/add-user" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-xl-5 float-right">
<div class="form-group">
<input class="form-control" type="text" placeholder="Type a User name"
name="create_user">
</div>
<div>
<button type="submit" class="btn btn-primary float-right" form="formAddUser" onclick="checker()">Create
User
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
function checker(){
if( confirm("Are you sure you want to create a new User in the database?")){
continue;
}else{
break;
}
}
</script>
I'm aware that the checker() function isn't correctly placed or even necessary but I'm not sure if there's another way to do this. When I click the create user button, the Confirm dialog box should render and ask me if I'm sure I want to create a user. If I select yes, it should submit the form but if I click cancel, it shouldn't do the form post request
You can use the JavaScript submit() function to remotely submit your form depending on the response. This would mean that instead of using a submit button, you'd have to use a normal button.
function checker(){
if(window.confirm("Are you sure")){
document.getElementById("formAddUser").submit();
} else {
return;
}
}
<div id="popupAddUser" class="addUser">
<div class="card h-100">
<div class="row">
<div class="col-7"><h2>Create New User</h2></div>
</div>
<div class="card-body">
<form method="POST" id="formAddUser" action="/add-user" enctype="multipart/form-data">
<div class="container">
<div class="row">
<div class="col-xl-5 float-right">
<div class="form-group">
<input class="form-control" type="text" placeholder="Type a User name"
name="create_user">
</div>
<div>
<button type="button" class="btn btn-primary float-right" form="formAddUser" onclick="checker()">Create
User
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Note that the button type is set to button rather than submit to prevent the page from refreshing after the function runs.
I am surprised your text editor did not complain about the continue and break statement in your if-else statement!!
I would:
Remove the inline onclick event handler
Use instead the addEventListener() method or the onsubmit call on the form element.
Use event.preventDefault() method to stop the form from submitting when the cancel button is clicked.
document.getElementById('form').addEventListener(
'submit',
(e) => checker(e)
)
function checker(e) {
if(!confirm('Are you sure?')) {
e.preventDefault()
alert('Form was not submitted')
}else {
alert('New user created')
}
}
I have two forms in one form.hbs page but with the same process.js file to process these two forms on different occasions with two different submit buttons.
When I hit the first submit button, it should be processed inside the process.js file and sent to the database, and when I hit the submit button of the second form in the same page, it should be processed still inside the process.js file and sent to the database. The first one works, but the second one doesn't, it keeps trying to submit the content of the first form. Please how do I solve this problem?
Thanks in advance.
forms.handlebar
{{!-- FIRST FORM - MATERIAL FORM --}}
<div id="materials">
<form action="/forms" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{materials._id}}">
<div class="form-group">
<label>Category of Material</label>
<input type="text" class="form-control" name="matName" value="
{{materials.matName}}"
placeholder="Material Title">
<div class="text-danger">
{{materials.matNameError}}
</div>
</div>
<div class="form-group">
<label>Description</label>
<input type="text" class="form-control" name="desc" value="{{materials.desc}}"
placeholder="Material Description">
<div class="text-danger">
{{materials.descError}}
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">
<i class="fa fa-database"></i>Submit</button>
<a href="/material-list" class="btn btn-danger">
<i class="fa fa-list-alt"></i>All Material records
</a>
</div>
</form>
</div>
{{!-- SECOND FORM - EQUIPMENT FORM --}}
<div id="equipments" style="display:none">
<form action="/forms" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{equipments._id}}">
<div class="form-group">
<label>Title of Equipment</label>
<input type="text" class="form-control" name="eqName" value="
{{equipments.eqName}}"
placeholder="Equipment Title">
<div class="text-danger">
{{equipments.eqNameError}}
</div>
</div>
<div class="form-group">
<label>Quantity</label>
<input type="desc" class="form-control" name="quantity" value="
{{equipments.quantity}}"
placeholder="Quantity of Equipment">
<div class="text-danger">
{{equipments.quantityError}}
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">
<i class="fa fa-database"></i>Submit</button>
<a href="/equipment-list" class="btn btn-danger">
<i class="fa fa-list-alt"></i>All Equipment records
</a>
</div>
</form>
</div>
router.js
//launching all forms
router.get('/forms', MaterialController.launchForm);
//posting & updating data to db
router.post('/forms', MaterialController.createElement)
router.post('/forms', EquipmentController.createElement);
//getting list of existing items
router.get('/material-list', MaterialController.Lists)
router.get('/equipment-list', EquipmentController.Lists)
//getting list by ids
router.get('/:id', MaterialController.ids)
router.get('/:id', EquipmentController.ids);
//deleting items from db
router.get('/delete/:id', MaterialController.delete);
router.get('/delete/:id', EquipmentController.delete)
I know there's a way to use javascript to choose which button is being clicked for submission, but I really don't know how to implement this.
Please any assistance offered will be highly appreciated
Thank you.
May it will be better to set "submit" action on form (as result remove tags)
const elemetns = {
equipmentsForm: document.getElementById('equipments') <== set this id to form,
materialsForm: document.getElementById('materials') <== set this id to form
}
after add submit to each form
elemetnts.equipmentsForm.submit(e => processForm(e, elemetnts.equipmentsForm, someRoute))
elemetnts.materialsForm.submit(e => processForm(e, elemetnts.materialsForm, someRoute))
after it create "processForm" func
fucntion processForm (e, form, route) {
e.preventDefault();
const data = new FormData(form);
$.ajax({
type: "POST",
url: route,
data
}).done(() => console.log('success'));
}
here i use $.ajax. But you can use new XMLHttpRequest() constructor. Find out how create XMLHttpRequest.
so, i think, it is enought to solve your case.
Best regards!
In my site, everything is working well on the desktop version but when I switch to the mobile version a button only works once. It doesn't do anything after 1 click.
If I press enter it works fine, but pressing on the button won't trigger the button again. I specifically don't want my page to reload.
onClick not working on mobile (touch)
This answer involves reloading the page.
$("#quiz").on('touchstart click', 'button', function(e){
e.preventDefault();
});
<h1 class="title">Quote Game!</h1>
<div class="container">
<form id="quiz" name="quiz" autocomplete="off"><br>
<container class="cont1">
<p class="questionp">Which hero does this quote belong to? </p>
<div class="row">
<!--<div class="form-group float-label-control">-->
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<p class="question" id="questionquote"></p>
</div>
<div class="col-6 col-lg-2 col-md-2 col-sm-2 col-xs-2 ">
<p id = "number_correct" class="green"></p>
</div>
<script class="score">document.getElementById("number_correct").innerHTML = "Your Score: " + correct;</script>
<div class="col-6 col-lg-2 col-md-2 col-sm-2 col-xs-2">
<!-- <img src="transparent.gif" height="90" width="90" class="pull-right"> penguin picture-->
</div>
<input class="form-control" id="question1" name="question1" placeholder="Hero Name" onclick="IsEmpty();" >
<br> </br>
<!--<input class="answer" id="question1" name="question1"></input><br> </br>-->
<div class="col-6 col-lg-2 col-md-2 col-sm-2 col-xs-2">
<!--<input id="button" class="btn btn-primary" type="submit" value="Check" onclick = "check(); ">-->
<button id ="button" value="Check" class="btn btn-primary " onclick = "check(); ">Check</button>
</div>
</div>
</container>
</form>
<div class="text-center">
<img id="result" class="correct_answer" src="" height="350" width="90%">
</div>
</div>
Tried your code under Chrome 68 for Android and the button is working everytime. However, a few hints:
Use addEventListener (or jQuery.on()) rather than using inline javascript in HTML.
If what you want is to not submit the form after running your code, you can use return false instead of e.preventDefault().
I don't get the point on attaching an event handler to the form only to filter it to the button and adding another inline javascript function to the button itself. If what you want is to call two different functions at once, use one function to call both.
try setting button type to button (instead of submit)
that way the button won't be disabled by browser after a click
<button type="button" id ="button" value="Check" class="btn btn-primary " >Check</button>
also, e.preventDefault is not needed anymore and you'll have to submit this form with js if you wan't to
This question already has answers here:
Submit multiple forms with one submit button
(3 answers)
Closed 6 years ago.
This is my HTML code - the forms in this are not working. Please help to work out the JavaScript and the HTML to submit these forms with a single click to same database.
JavaScript for the buttons:
<script>
submitBothForms = function () {
document.forms["userinfo"].submit();
document.forms["userinfo1"].submit();
}
</script>
<script>
clearForms = function(){
document.forms["userinfo"].reset();
document.forms["userinfo1"].reset();
}
</script>
HTML code where the both the forms and the buttons exists both the buttons are clear and save the code must be submitted to a single PHP file to a single database and single table.
<div class="row">
<div class="col-sm-12">
<div class="bill-to">
<div class="step-one">
<h2 class="heading">Add new Shipping address</h2>
</div>
<div class="form-one">
<form action="userinfo.php" name="userinfo" method="POST">
<input type="text" name="name" required placeholder="Name">
<input type="email" name="email" required placeholder="Email">
<input type="text" name="address1" required placeholder="Address 1">
<input type="text" name="address2" placeholder="Address 2">
</form>
</div>
</div>
<div class="form-two">
<form action="userinfo.php" name="userinfo1" method="POST">
<input type="text" name="zip" required placeholder="Zip / Postal Code">
<select>
<option>-- Country --</option>
<option>United States</option>
<option>Bangladesh</option>
<option>UK</option>
<option>India</option>
<option>Pakistan</option>
<option>Ucrane</option>
<option>Canada</option>
<option>Dubai</option>
</select>
<input type="tel" name="contact" required placeholder="Mobile Phone *">
<button type="submit" class="btn btn-primary" style="margin-right: 15px;" onClick="submitBothForms()">Save</button>
<button class="btn btn-primary" onclick="clearForm()">Clear</button>
</form>
</div>
</div>
</div>
You cannot submit two forms using submit button. Only one form can be submitted by the button. Use ajax call to submit the form i.e give two ajax call for the form submit.
jQuery AJAX submit form
this is simply not possible, as each of your fomrs will trigger a rountrip/reload.