Submit form on enter press - javascript

Rookie question. I have a simple form with an input box and a submit button. When the button is clicked it triggers some php to search for the input term & output any results. I want to be able to press enter after typing my search term, rather than having to click the button.
I'm aware this is a basic thing and I've found solutions on here but when I've tried to add a keyup event listener to my code it doesn't seem to change anything and I'm not clear why - with or without the js pressing enter seems to refresh the page? I'm guessing that the problem is I don't want to "submit" the form, I want to do something else?
Here is the code:
<?php
if (isset($_POST['submit'])) {
*Removed the search php because I assume it is not relevant to the question*
?>
<div class="site-section bg-dark" id="start">
<div style="padding-left: 20px">
<h3 class="text-white">Find book based on title</h3>
<div class="col-md-6">
<div class=" mb-4">
<div class="form-group">
<form method="post">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control" placeholder="Title">
<p></p>
<button class="btn m-1 btn-secondary">
<input type="submit" id="submit" name="submit" value="View Results">
</button>
</form>
</div>
</div>
</div>
</div>
<script>
var input = document.getElementById("title");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
</script>
*Results output here*
</div>
Many thanks.
Edit:
Resolved, thanks for the suggestions. It turned out that this was only a problem in Firefox, not Chrome, and the reason was this:
<button class="btn m-1 btn-secondary">
<input type="submit" id="submit" name="submit" value="View Results">
</button>
input type="submit" is already a button, and wrapping it around another button apparently caused the browser some confusion.

Related

Disappearing a submit button after being clicked in html form

I have made a html form to take inputs from user. My sample code is given below:
<form class="form-main" action="../php/additem.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="what" value="faculty" />
<div class="form-item">
<div class="form-left">
<label><big>Name:</big></label>
</div>
<div class="form-right">
<input class="txtbox" type="text" name="facname" id="fac_name" size="20" required >
</div>
</div>
<div class="form-item">
<div class="form-left">
<label><big>Education:</big></label>
</div>
<div class="form-right">
<input class="txtbox" type="text" name="educn" id="fac_edu" size="20" required >
</div>
</div>
<div id="buttons">
<button class="greenbtn" type="submit" name="btn-upload" value="Add Now" id="add_fac" >Submit</button>
<input class="orangebtn" type="reset" value="Clear" id="clear_fac" />
</div>
</form>
I want to add a feature that, after the submit button being clicked it will be disappeared so that user can't double click on that. Is it possible? How will I do this?
Two easiest ways would either be with javascript and have
<form class="form-main" action="../php/additem.php" method="post" enctype="multipart/form-data" onsubmit="hideSubmit()">
<script>
function hideSubmit(){
document.getElementById("buttons").style.display = "none";
}
</script>
or jquery
<script>
$(function(){
$('.form-main').on('submit', function(){
$('#buttons').hide();
});
});
</script>
after the submit button being clicked it will be disappeared so that user can't double click on that.
You've literally described how to do it.
document.getElementById('test-button').addEventListener('click', function () {
this.remove()
})
<button id="test-button">Click me!</button>
I suggest reading about setting up events.

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.

Jquery does not select the form element given an ID

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

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.

jQuery post function with radio buttons

In my Django app, I would like to use Twitter bootstrap radio buttons. Then I would like to post the value of those buttons in order to create an object.
Here is my buttons:
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" class="btn" name="supporting">Team1</button>
<button type="button" class="btn" name="supporting">Team2</button>
</div>
<div class="span6 btn-group ib" data-toggle="buttons-radio">
<button type="button" class="btn btn-primary active" name="style">relaxed</button>
<button type="button" class="btn btn-primary active" name="style">strict</button>
</div>
<input type="submit" value="create your match">
I would like to get the information from those radio button and create an object match with it in a view:
def test(request):
user=request.user
if request.method == 'POST':
style = request.POST['style']
supporting = request.POST['supporting']
match = Match.objects.create(user=user, style=style, supporting=supporting)
return HttpResponse(test)
The thing is that I don't know JavaScript well, so I didn't find how to get the value from the button.
Then, I think I have to use:
$.post('/sportdub/points_dub/', {'style': style , 'supporting': supporting});
But how can I do so that style and supporting correspond to the value of the buttons, and then to post it only when the user clicks on the button?
Thank you very much for your help.
taking my last answer, let's use your own code... in your HTML you have something like:
<form action="/sportdub/points_dub/" method="post" class="form-horizontal">
<div class="btn-group" data-toggle="buttons-checkbox">
<button type="button" class="btn" name="supporting">Team1</button>
<button type="button" class="btn" name="supporting">Team2</button>
</div>
<div class="span6 btn-group ib" data-toggle="buttons-radio">
<button type="button" class="btn btn-primary active" name="style">relaxed</button>
<button type="button" class="btn btn-primary active" name="style">strict</button>
</div>
<input type="submit" value="create your match" />
</form>
and you just have to add one hidden field per block, in your case, add 2. Your form would then match:
<form action="/page" method="post" class="form-horizontal">
<input type="hidden" id="supporting_team" value="" />
<input type="hidden" id="supporting_type" value="" />
<div class="btn-group supporting_team" data-toggle="buttons-checkbox">
<button type="button" class="btn" name="supporting">Team1</button>
<button type="button" class="btn" name="supporting">Team2</button>
</div>
<div class="span6 btn-group ib supporting_type" data-toggle="buttons-radio">
<button type="button" class="btn btn-primary active" name="style">relaxed</button>
<button type="button" class="btn btn-primary active" name="style">strict</button>
</div>
<input type="submit" value="create your match" />
</form>
add a jQuery helper that will set the values of those hidden fields upon buttons click:
// whenever a button is clicked, set the hidden helper
$(".supporting_team .btn").click(function() {
$("#supporting_type").val($(this).text());
});
$(".supporting_type .btn").click(function() {
$("#supporting_team").val($(this).text());
});
when you click the create your match the entire form will be posted to the page set as the action attribute of the form, you have to do nothing more...
If you want to submit it manually by invoking post in javascript you need to remember to prevent the form to be submitted again as that's the input type="submit" element task, you can invoke your post and serializing the entire form data, instead one by one as in your example...
like:
// when the form is submited...
$("form").submit(function() {
// submit it using `post`
$.post('/sportdub/points_dub/', $("form").serialize());
// prevent the form to actually follow it's own action
return false;
});
in your dynamic code, you will have those variables as:
supportingTeam = request.POST['supporting_team']
supportingType = request.POST['supporting_type']
and this, will be valid, no matter if you have the manually form submit script or not...
After your most recent comment, I think you should try using the input radio buttons provided in HTML. It is very easy to do button groupings, make labels for the inputs, and retrieve which one has been clicked.
Altering your HTML slightly to look like this (the for attribute of the label allows the user to be able to click the label and select the radio button instead of clicking on the button directly):
<div>
<input id="team1" type="radio" name="supporting" value="Team1" /><label for="team1">Team 1</label>
<input id="team2" type="radio" name="supporting" value="Team2" /><label for="team2">Team 2</label>
</div>
<div>
<input id="relaxed" type="radio" name="style" value="relaxed" /><label for="relaxed">Relaxed</label>
<input id="strict" type="radio" name="style" value="strict" /><label for="strict">Strict</label>
</div>
I can get which selections have been made using this:
$('input[name="supporting"]').filter(':checked').val();
$('input[name="style"]').filter(':checked').val();
If you still wish to use buttons, class active is added to a radio button when clicked. To get the button text, try:
$('button[name="supporing"]').filter('.active').text();
$('button[name="style"]').filter('.active').text();
To put this value into a hidden input, do the following:
$('#hiddenInput1').val($('button[name="supporting"]').filter('.active').text());
$('#hiddenInput2').val($('button[name="style"]').filter('.active').text());

Categories

Resources