How to check if my button was clicked in JavaScript? - 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>

Related

Calls function either press enter or hit button

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>

Javascript: How to disable submit button until all fields are validated?

I have several validation functions that work fine and I want to write an additional validation in simple javascript (no jQuery, etc) for the entire form that disables/enables the Submit button depending on whether the other validation functions return true or false. How do I go about that?
For example, for my main HTML I have:
<form id="form" method="POST">
<label class="form">Field 1</label><input type="text" name="input1" onkeyup="validateInput1(); return false">
<label class="form">Field 2</label><input type="text" name="input2" onkeyup="validateInput2(); return false">
...
<button id="submit" type="submit" value="submit">Submit</button>
</form>
For my script I have:
function validateInput1(){
...
}
function validateInput2(){
...
}
Now I want to write a function with something like:
function validateForm(){
var submitButton = document.getElementById('submit');
submitButton.disabled = true;
/*If all other validation functions like validateInput1() returns true then submitButton.disabled = false*/
}
How do I do this?
Start the button off as disabled. Hook to the onchange event for each of the form inputs, and then have it check the validateForm() function to see if all the forms are valid. After that, if they're all valid, set the submit button to enabled, otherwise set it to disabled.
var inputs = document.querySelectorAll('#form input');
var validateInput1 = function()
{
return document.getElementById('input1').value != '';
}
var validateInput2 = function()
{
return document.getElementById('input2').value != '';
}
var validateForm = function() {
if ( !validateInput1() ) {
return false;
}
if ( !validateInput2() ) {
return false;
}
return true;
}
for ( var i = 0, len = inputs.length; i < len; i++ )
{
var checkValid = function() {
document.getElementById('submit').disabled = !validateForm();
//Is the same as:
/*if ( !validateForm() )
{
document.getElementById('submitButton').disabled = true;
}
else
{
document.getElementById('submitButton').disabled = false;
}*/
}
inputs[i].addEventListener('change', checkValid);
inputs[i].addEventListener('keyup', checkValid);
}
<form id="form" method="POST" onsubmit="alert('Submitted!'); return false">
<label class="form">Field 1</label><input type="text" name="input1" id="input1">
<label class="form">Field 2</label><input type="text" name="input2" id="input2">
<button id="submit" type="submit" value="submit" disabled="disabled">Submit</button>
</form>

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" />

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

Validate a form depending on which submit button is used

So, I have this code
<script>
function validate(f) {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2(f) {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID"/>
<input type="submit" name="send_name" value="Send Name"/>
</form>
How can I do it to validate the form depending on which submit is used?
I want to execute validate(); if the Send Id button is clicked and validate2() if we use the other one.
You can do this:
<form id="myForm" action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return validate();" />
<input type="submit" name="send_name" value="Send Name" onclick="return validate2();" />
</form>
This way when your functions return false (meaning the form is not valid) the submit is interrupted.
And get your f parameter manually.
function getForm() {
return document.getElementById("myForm");
}
function validate() {
var f = getForm();
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var f = getForm();
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
You have to give an id to your form as show above.
Have another function as checkValidate() or something as you like and check it on click of both the buttons
<script>
function checkValidate(buttonName) {
if(buttonName == 'send_id'){
return validate();
}else{
return validate2();
}
}
function validate() {
var ok = true;
if (f.id.value === '' || f.id.value === null) {
ok = false;
}
return ok;
}
function validate2() {
var ok = true;
if (f.name.value === '' || f.name.value === null) {
ok = false;
}
return ok;
}
</script>
<form action="#" method="post">
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="submit" name="send_id" value="Send ID" onclick="return checkValidate(this.name)"/>
<input type="submit" name="send_name" value="Send Name" onclick="return checkValidate(this.name)"/>
</form>
I hope it helps...
Not tested.. but something like that...
$( "input[name='send_id']" ).click(function(event) {
event.preventDefault()
validate();
$("form").submit();
});
$( "input[name='send_name']" ).click(function(event) {
event.preventDefault()
validate2();
$("form").submit();
});

Categories

Resources