Jquery does not select the form element given an ID - javascript

I'm trying to submit a form with jquery, but it does not acknowledge that I submitted it when I click the "submit" button.
My html is as follows:
<form id="singleParam" role="form">
<div class="form-group">
<label for="sample_size">Number of samples needed</label>
<input name="choices[sample_size]" type="number" class="form-control" id="sample_size" placeholder="Enter desired number of samples">
</div>
<div class="form-group">
<label for="mode">Mode of the distribution (value most likely to be sampled)</label>
<input name="choices[mode]" type="number" class="form-control" id="mode" placeholder="Enter the likeliest value for your parameter">
</div>
<div class="form-group">
<label for="confidence">Confidence interval factor</label>
<input name="choices[confidence]" type="number" class="form-control" id="confidence" placeholder="Enter desired confidence interval factor">
</div>
<div class="form-group">
<input type="button" class="btn btn-primary btn-lg" id="submit" name="submit">
</div>
</form>
and JS is:
$('#singleParam').on('submit', function () {
alert('Form submitted!');
console.log('Form submitted!');
return false;
});
The alert() or console.log() in the loop do not work, meaning that jquery did not run the code on submit. What am I doing wrong? It might be worth mentioning that I am using bootstrap.

Change the button type from type="button" to type="submit"
EDIT:-
Make sure you are calling all your event handlers once the DOM is fully loaded by adding all the code inside dom ready event like:-
$(document).ready(function() {
// code here
});

Related

Ajax: Why is the post request fired twice?

I have noticed my request is fired twice, but I dont understand why.
I have a simple form:
<form method="POST" class="mb-4" autocomplete="off" action="/recipe/add" novalidate id="form">
<div class="form-group">
<label for="title">Rezeptname</label>
<input required type="text" name="title" id="title" class="form-control form-control-sm needs-validation" value="">
<div class="invalid-feedback">Ein Name wird für das Rezept benötigt!</div>
</div>
<div class="form-group">
<label for="cookingTime">Zubereitungsdauer in Minuten</label>
<input type="number" name="cookingTime" id="cookingTime" class="form-control form-control-sm" value="">
</div>
<div class="form-group">
<label for="servings">Portionen</label>
<input type="number" name="servings" id="servings" class="form-control form-control-sm" value="">
</div>
<label for="ingredients">Zutaten</label>
<button class="btn btn-outline-secondary btn-sm ml-2" onclick="createInputRow()"><i class="fas fa-plus"></i></button>
<div class="mb-4" name="ingredients">
<table class="table">
<tbody id="tbody">
</tbody>
</table>
</div>
<button type="submit" class="btn btn-primary btn-sm" id="submit">Speichern</button>
Zurück
</form>
on document load, I add the event listener for the button
$(document).ready(() => {
$("#submit").unbind("click").bind("click", event => {
onSubmit(event)
})
})
in the onSubmit method, the request is sent out:
$.ajax({
type: "POST",
url: "/recipe/add",
data: {recipe: recipeData},
success: (res) => {
console.log(JSON.parse(res))
}
});
In the network scan I could see that the request is fired twice.
This leads to getting an error on my server.
When setting a breakpoint in the front end, it is only triggered once, though. The backend recieves two requests like in the network scan.
I already tried the $("#submit").unbind().bind() as mentioned in other sources but that doesnt fix the problem.
In the case that you want to use your <form> tag for other purposes (including redirect) -- You should remove the type=submit off the submit button, OR use preventDefault() to prevent the default form action. Also note that hitting the "Enter" key may also submit the form if in an text field. You can also use preventDefault() to prevent the form from being submitted during this action as well.

PHP :unable to check if a form is submitted

I am using a form in php file inside a modal window like this
<div class="modal-body">
<form method="post" action="m.php">
<div class="form-group">
<lable>Name</lable>
<input type="text" class="form-control" required="required">
</div>
<div class="form-group">
<lable>Email</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Details</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Message</lable>
<textarea name="" id="" class="form-control"></textarea>
</div>
<div class="form-group">
Submit
</div>
</form>
</div>
file name is m.php now when i press the submit button it doesn't detect form submission
<?php
if( ($_SERVER['REQUEST_METHOD'] == 'POST')){
die("form submitted");
}
?>
i tried $_POST['submit'] as well kindly help me whats wrong with it
This is because you dont press a submit button, you press a link called submit. Try replacing it with <input type="submit" value="Submit" />.
Also, your check wether your form has been submitted uses a dangerous method. If you have multiple forms to be handled in your code, it will catch them all. A better approach would be:
if( isset($_POST['nameOfSubmitbutton']) ){}
// because you can now easily do:
if( isset($_POST['completelyDifferentButton']) ){}
If you want to keep the anchor (I advice against it), you can use javascript to fake the submit for you:
document.getElementById('yourAnchor').onclick = function(){
document.getElementById('yourForm').submit();
}
// Or if you have jQuery:
$('#yourAnchor').on('click', function(e){
e.preventDefault();
$(this).closest('form').submit();
});
The submit button you are using is pointing towards the same url, can you try something like?
<input class="btn btn-default" type="submit" value="Submit">
and then try to see if the form is submitted from PHP.
And i also would recommend that you use some framework for this to handle sql injections and/or other exploits.
Wrong use of form submit.
<div class="form-group">
Submit
</div>
You should use it like:-
<div class="form-group">
<input type="submit" class="btn btn-default" name="submit" style="background: #eee; width:100px;display: block;margin-left:auto;" value="Submit"/>
</div>
Hopefully this will solve the issue.

Multiple buttons in Bootstrap validator form

I have a simple form with multiple submit buttons. How do I change the java script to see, which button is clicked. Thanks
<form class="contact" role="form" data-toggle="validator" id="testform">
<div class="form-group">
<label for="inputName" class="control-label">Name</label>
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="Cina Saffary" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button class="btn btn-success" type="submit" id="save1" value="save1">save1</button>
<button class="btn btn-success" type="submit" id="save2" value="save2">save2</button>
</div>
</form>
$('#testform').validator().on('submit', function (e) { (e.isDefaultPrevented()) {
alert("failure!");
} else {
// if save1 clicked, alert("save1 was clicked");
// if save2 clicked, alert("save2 was clicked");
}
});
You can get button value like this:
var val = $("button[type=submit][clicked=true]").val();
And you need to add one more event for button also
$("form button[type=submit]").click(function() {
$("button[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
DEMO
Reference: How can I get the button that caused the submit from the form submit event?

Why element.classList.add('class-name'); is not working?

Have HTML (part):
<div class="modal-write-us">
<form class="modal-write-us-form" action="" method="post">
<label>
<input type="text" name="user-name" required>
</label>
<label>
<input type="text" name="e-mail" required>
</label>
<label for="text-field"></label>
<textarea name="text" rows="5" id="text-field" required></textarea>
</form>
<div class="modal-write-us-button">
<button class="btn btn-red" type="submit">Submit</button>
</div>
</div>
I need to add class "modal-error" for div.modal-write-us if submitted form have empty field/fields.
JS:
var modalWriteUs = document.querySelector('.modal-write-us');
var form = modalWriteUs.querySelector('form');
var userName = modalWriteUs.querySelector('[name=user-name]');
var eMail = modalWriteUs.querySelector('[name=e-mail]');
var textArea = modalWriteUs.querySelector('[name=text]');
form.addEventListener('submit', function(event) {
if (!userName.value || !eMail.value || !textArea.value) {
event.preventDefault();
modalWriteUs.classList.add('modal-error');
}
});
But class is not added. Where is my mistake?
First of all, you need to place your submit button into the form.
Then, change submit button to input:
<input class="btn btn-red" type="submit">Submit</input>
Now you need to make some fixes in your JS.Use double quotes in atttribute selectors:
querySelector('[name="user-name"]')
Attribute required doesn't allow to submit empty form, so your submit callback never runs.If you remove required attribute your code will work.
If you put <button class="btn btn-red" type="submit">Submit</button> inside the <form> it should work.
See working Plunker.
<div class="modal-write-us">
<form class="modal-write-us-form" action="" method="post">
<label>
<input type="text" name="user-name" required>
</label>
<label>
<input type="text" name="e-mail" required>
</label>
<label for="text-field"></label>
<textarea name="text" rows="5" id="text-field" required></textarea>
<div class="modal-write-us-button">
<button class="btn btn-red" type="submit">Submit</button>
</div>
</form>
</div>
EDIT: More explanation here:
The elements used to create controls generally appear inside a FORM element, but may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed in the section on intrinsic events. Note that controls outside a form cannot be successful controls.

Bootstrap reset button onclick keep textbox as valid

I have used below code for bootstrap textbox and textarea and also in the last div I have used button type="reset" .But when I entered invalid shop name and valid Address and click on Reset button it reset it and after only entering invalid shop name and click on Add shop then it is successfully adding new shop.Both the textbox show green background-color and correct sign even after it is empty.
Please help me.
Please see below image after onclick of reset button:
<form id="defaultForm" method="post" class="form-horizontal"
data-bv-message="This value is not valid"
data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
<div class="form-group">
<label class="col-xs-3 control-label">Shop Name</label>
<div class="col-xs-4">
<input type="text" class="form-control" pattern="^[a-zA-Z\s]+$"
data-bv-regexp-message="The shop name can consist of alphabetical characters only" name="shopName" placeholder="Shop Name" data-bv-trigger="blur" data-bv-notempty="true" data-bv-notempty-message="Shop name is required and cannot be empty" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Shop Address</label>
<div class="col-xs-4">
<textarea id="id_txt_addr" type="text" class="form-control" name="shop_address" placeholder="Shop Address" style="height:100px" maxlength="200" data-bv-trigger="blur" data-bv-notempty="true" data-bv-notempty-message="Shop address is required and cannot be empty"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-9 col-xs-offset-3">
<input type="submit" name="add" class="btn btn-primary" value="Add Shop">
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
On reset button click, remove all relevant validation classes and elements handling error message inside closest form. Here an example:
$(':reset').on('click', function(){
var $form = $(this).closest("form");
$form.find('*').removeClass('has-success has-error glyphicon-ok glyphicon-remove');
$form.find('.help-block').remove();
});
-DEMO-
Now maybe there is a bootstrap method to reset validation, you should check bootstrap DOC maybe.
$(document).ready(function () {
$("#ibtReset").on("click", function () {
$('#ShopName').val("");
$('#id_txt_addr').val("");
$('.glyphicon ').remove();
});
});
On reset button click both the values become empty.
It may help You.

Categories

Resources