Calls function either press enter or hit button - javascript

I would like to call the JavaScript function when I either hit enter or press the button. Also, I want the function to retrieve the value.
Here is my form:
<form>
Farm Number:<br>
<input id="fnumber" type="text" value="" onKeyDown="findfarm2(event)">
<input type="button" value="Find Farm" onclick="findfarm();">
</form>
And here is my JavaScript function:
function findfarm2(event) {
if (event.keyCode == 13){
cqlfilter = 'Farm =' + document.getElementById('fnumber').value;
unregistered.getSource().updateParams({'LAYERS': 'NCSPCTest:Unreported_Names','CQL_FILTER': cqlfilter});
alert(cqlfilter)
}
}
function findfarm() {
cqlfilter = 'Farm =' + document.getElementById('fnumber').value;
unregistered.getSource().updateParams({'LAYERS': 'NCSPCTest:Unreported_Names','CQL_FILTER': cqlfilter});
alert(cqlfilter)
}
The button is working but the enter function is not. The 'findfarm2' function can pop out an alert but it isn't passing the value to 'updateParams'.

Your function (findfarm2) do not work, because your form is submitting when you press ENTER button (keyCode = 13).
<form id="form" active="#">
<!-- get value (using parameters) -->
<input id="first" type="text" value="" onkeydown="find(event, this.value)">
<input id="last" type="button" value="Find Farm" onclick="findfarm();">
</form>
<script type="text/javascript">
document.querySelector('#form').addEventListener('submit', function(e) {
e.preventDefault(); // stop form from submitting
console.log('You need stop form from submitting!')
});
function find(e, val) {
if (e.keyCode == 13) {
console.log('enter')
}
var value = document.getElementById('first').value;
console.log('My value (using getElementById)' , value)
console.log('My value (using parameters)' , val)
// resume your code here...
}
function findfarm() {
console.log('Find Farm clicked!');
}
</script>

Related

Using ENTER key to replace button click?

<body>
<form>
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
I have a very simple HTML file with minimal javascript included. When I click the button, it works perfectly. But when I hit the ENTER on the keyboard to simulate the button click, it will also run through the code, but then an error happens at the end.
On Firefox and Chrome, it'll return an error "Not Found". On w3schools, it'll return "The file you asked for does not exist". And on stackoverflow, it'll just disappear.
What am I missing? Where is the error? What's the trick to making the ENTER key act just like the mouse click?
HTML form has onsubmit attribute on them. onsubmit handles the enter functionality. You have to set the type="submit" on the button, also you need to set the onsubmit on form passing the event to your function so that you can prevent the default action of the form ( that is to send the request to backend ) by doing e.preventDefault.
<body>
<form onsubmit="calc(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="submit">read</button>
</form>
<br>
<label id = "calculated"></label>
<script>
function calc(e) {
// Will stop the form from sending the request to backend
e.preventDefault()
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
</body>
If you want to just prevent ENTER from doing anything including running the code....
The following code (yours with a couple more lines... will prevent Enter from doing anything:
<body>
<form onsubmit="return mySubmitFunction(event)">
<label>enter number here: </label>
<input type="number" id="text"/>
<button type="button" id="btn" onclick="calc()">read</button>
</form>
<script>
document.getElementById("text").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
return false;
//document.getElementById("btn").click();
}
});
</script>
<br>
<label id = "calculated"></label>
<script>
function mySubmitFunction(e) {
e.preventDefault();
return false;
}
function calc() {
let inputValue = document.getElementById("text").value;
document.getElementById('calculated').innerHTML = 'your number: ' + inputValue;
}
</script>
Why was this happening? since the form element itself has a submit and the enter key is a key pressed which also does a form submit.... so you need to prevent the form from submitting... mySubmitFunction() <- this prevents the form from submitting ... and a change to your keyup event listener - if you do not want enter to even create the click you change this:
event.preventDefault();
document.getElementById("btn").click();
to this :
event.preventDefault();
return false;
//document.getElementById("btn").click();
As I have already did in the code example. or leave it like you had(the event listener keyup) and the Enter key will only act as a click.

How to check if my button was clicked in JavaScript?

I want to call a JavaScript function test() when I press enter or I click a button but I don't know how to check if the button was clicked in test().
HTML Code :
<input id="data" type="text" name="data" value="" onkeypress="test()" />
<button id="button" type="submit" onclick="test()">button</button>
JavaScript :
function test() {
let data = document.getElementById("data") ;
let button = document.getElementById("button") ;
if(data.onkeypressed = this.event.which === 13 || /*need to check if button was clicked*/) {
...
...
...
}
How do I do this in JavaScript ?
You can pass this to function and check the tagName
function test(e) {
let data = document.getElementById("data") ;
let button = document.getElementById("button") ;
if(data.onkeypressed = this.event.which === 13 || e.tagName === "BUTTON") {
console.log("button")
}
}
<input id="data" type="text" name="data" value="" onkeypress="test(this)" />
<button id="button" type="submit" onclick="test(this)" >button</button>
You can pass this into test() and use it there:
function test(el) {
let enter = el.id === 'data' && this.event.which === 13;
console.log(`Called by ${el.id}${enter ? ' and Enter was pressed' : ''}.`);
}
<input id="data" type="text" name="data" value="" onkeypress="test(this)" />
<button id="button" type="submit" onclick="test(this)">Button</button>
Use the button's onclick event handler for that. It will be called every time the button is clicked:
Edit: You can also use the input's onkeydown event to see if the user pressed enter while the input box was selected.
var data = document.getElementById("data") ;
var button = document.getElementById("button");
button.onclick = function() {
console.log("clicked!");
test();
//do something
}
data.onkeydown = function(e) {
if(e.keyCode == 13) {
console.log("ENTER IS PRESSED!");
this.blur(); //de-selects the textbox
}
}
function test() {
//do something
}
<input id="data" type="text" name="data" value="" />
<button id="button" type="submit" >button</button>

Why isn't the form submitting after validation

HTML:
<form method="post" name="contact" id="frmContact" action="smail.php">
...
<label for="security" class="smallPercPadTop">Please enter the result:</label> <br /><h3 id="fNum" class="spnSecurity"></h3><h3 id="nCalcType" class="spnSecurity"></h3><h3 id="sNum" class="spnSecurity"></h3> = <input type="text" placeholder="Enter the result" name="security" id="security" class="required input_field_custom" />
<br /><br />
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
<input type="reset" value="Reset" id="reset" name="reset" class="submit_btn" />
</form>
Script:
$('form').on('submit', function(e) {
e.preventDefault();
var vGetResult = $("#security").val();
if (vGetResult == vResult) { //""vResult"" is a value that I set when the page loads...
alert("good");
$("#frmContact").submit();
}
});
What I am trying to do is, once I validate what the user entered is the same as another number then I would like to submit the form. Instead of submitting the form, I keep getting the alert statement infinitely.
How can I fix it?
Move e.preventDefault() to else block when the validation condition fails. Also you don't need to resubmit the form using $("#frmContact").submit()
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult == vResult) { //""vResult"" is a value that I set when the page loads...
alert("good");
//$("#frmContact").submit();
}else{
e.preventDefault();
}
});
Or, you just modify statement as
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult !== vResult) { //""vResult"" is a value that I set when the page loads...
e.preventDefault();
}
alert("good");
});
Your form goes in infinite loop. try this simple code.
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult != vResult)
{
e.preventDefault();
}
});
Return true to allow the form to submit or false to suppress :
$('#frmContact').on('submit', function(e) {
if ($("#security").val() == vResult) {
alert("good");
return true;
} else {
return false;
}
});
Or, if the alert is not needed :
$('#frmContact').on('submit', function(e) {
return $("#security").val() == vResult;
});
You can let the jQuery event get prevented ...and trigger the native event
Just change
$("#frmContact").submit();
To
$("#frmContact")[0].submit();

Check if checkbox is checked using javascript wont work

I have a html form, which has a bunch of inputs inside. In this html form I also have a checkbox, which I then check if the user has checked using javascript, only problem is that it doesn't work. Whenever I click the button to submit, which is then supposed to run through the code and check if the checkbox is checked, it just gives me a couple of errors because the other input values are not set which it is supposed to do, but I want it to just check if the checkbox is checked and if it is do the function inside the if statement, or if the checkbox isn't checked run the alert message.
This is my script which does not work:
<script type="text/javascript">
$(document).ready(function() {
function checkBoxCheck() {
if (document.getElementById('AcceptRules').checked) { //this is where I check if the checkbox is checked
var handler = StripeCheckout.configure({
key: 'removed for security',
image: 'TestGPCheckoutImg.png',
token: function(token) {
var $form = $('#payment-form');
$form.append($('<input type="hidden" name="stripeToken" />').val(token.id));
$form.get(0).submit();
}
});
$('#customButton').on('click', function(e) {
var amount = Math.round($("#amount").val()*100);
handler.open({
name: 'Payment',
description: 'desciption for produ',
amount: amount
});
e.preventDefault();
});
$(window).on('popstate', function() {
handler.close();
});
} else {
alert("Remember to check the checkbox for terms of use"); //this is where I try to alert the user with a message
}
}
});
</script>
<form id="payment-form" action="chargeCard.php" method="POST" name="payment-form">
<input onkeypress="return isNumberKey(event)" type="text" name="amount" id="amount" value="" readonly/>
<input type="text" name="emailForPayment" id="emailForPayment" placeholder="Enter Email"/>
<input type="text" name="displayNameForPayment" id="displayNameForPayment" placeholder="Enter Display Name" maxlength="12"/>
<input type="checkbox" id="AcceptRules" name="AcceptRuels" value="AcceptRules"/> <!-- this is the checkbox -->
<input type="image" src="image123.png" id="customButton" value="button" alt="button" onClick="checkBoxCheck()"/> <!--this is the button with the function in -->
</form>
<script type="text/javascript">
function toDec(code) {
return code - 48;
}
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || toDec(charCode) != currentBid + 1))
return false;
return true;
}
</script>
You're scope is wrong.
$(document).ready(function () {
// I don't work.
function checkBoxCheck() {
alert("I have local scope");
}
});
function checkBoxCheck() {
alert("I have global scopeage");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="checkBoxCheck();">Click</button>
See this answer for a better explanation.

Javascript/jQuery : Detect both return key press and submit button press simultaneously

I have an input field and an "add" button below it. What the add button basically does is, it appends a new input field to the document. What I am trying to do here is, while typing in an input field if return key press is detected the function that calls the addition of new input field is fired the same function that is fired when the add button is clicked.
Can I incorporate the detection of return key press in the following somehow?
$('.addNewSite').on('click', function(){
var idNewInput = "site" + numInputFields;
$('.inputFieldsSettingsPanel').append('<input type="text" class="tracksiteInput" id = "' + idNewInput + '"></input>');
$("#" + idNewInput).focus();
});
I think you want this http://jsfiddle.net/naeemshaikh27/cy84t4pz/
function fun(){
$('body').append('<input type="text"/>');
}
$('.addButton').on('click', fun);
$('body').on('keypress','input', function(e){
if (e.keyCode == 13) {
fun();
}
});
something like this? e.which in the keypress() is what you're looking for to see what button is pressed. in this case, 13 is equivalent to the enter key
$(document).ready(function() {
$('.add').on('click', function() {
var html = '<input type="text" class="field" /><br/><br/>';
$('.form').append(html);
});
$(document).on("keypress", ".field", function(e) {
if(e.which == 13) {
$('.add').trigger('click');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="add" href="#">add</a><br/><br/>
<div class="form">
<input type="text" class="field" /><br/><br/>
<input type="text" class="field" /><br/><br/>
</div>
You cant detect enter keypress on the input and trigger the button's click event.
$("button").on("click", function(e){
$("body").append($("<input>").attr("type", "text"));
});
$(document).on("keypress", "input", function(e){
if(e.which == 13) $("button").trigger("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Input</button>
var i;
var inputs=document.getElementsByClassName('add');
for(i=0;i<inputs.length;i++){
inputs[i].addEventListener('keyup',function(event){
if(event.keyCode){if (event.keyCode=="13" ){createNewElem();
}}
//if(event.which){if(event.which =="13"){alert('return pressed');}}
});
}
function createNewElem(){
var newinput=document.createElement('input');
var inptype=document.createAttribute('type');
inptype.value="text";
newinput.setAttributeNode(inptype);
var inpclass=document.createAttribute('class');
inpclass.value="add";
newinput.setAttributeNode(inpclass);
document.body.appendChild(newinput);
}
<input type="text" class="add" />

Categories

Resources