Button Enable After reCaptcha and Input Filled JS - javascript

I have a disabled submit button that I can't seem to enable after BOTH a successful Google reCaptcha and checking there is text in an input box.
I'm using the HTML and 2 separate JS files below but the JS files only seem to work individually and not together. Is there a way to verify the reCaptcha and check the text box is filled together? I can't find any similar answer.
HTML:
<input type="text" name="em" ID="em" class="form-item input-address" placeholder="Email"></input>
<button type="submit" class="submit start" id="button1" alt="Submit" disabled="disabled"></button>
</br>
<?php foreach ($_POST as $key=> $value) { echo '
<p><strong>' . $key.':</strong> '.$value.'</p>'; } ?>
<div class="g-recaptcha" data-sitekey="{key}" data-callback="enableBtn"></div
recaptcha.js (this works on its own):
//Disable Button if No reCaptcha
$("#button1").prop("disabled", true);
function enableBtn() {
$("#button1").removeAttr('disabled');
}
What I'd like to do is also have the button disabled if there is no text in the input area. I have tried this and it works:
input.js (this also works on its own but not with recaptcha.js):
//Disable Button if Input Empty
$(document).ready(function() {
$('.input-address').keyup(function() {
var empty = false;
$('.input-address').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$("#button1").prop("disabled", true);
} else {
$("#button1").removeAttr('disabled');
}
});
});

I'm assuming that you're using the programmatic version of Recaptcha. You first need to include a callback in your recaptcha call. Something like this
recaptchaWidget1 = grecaptcha.render('recaptchaDiv1', {
'sitekey' : 'site-key-goes-here',
'theme' : 'light',
'callback' : 'enableBtn'
});
Alternatively you can set up a callback using the data attributes
<div class="g-recaptcha" data-sitekey="your_site_key" data-callback="enableBtn"></div>
Next do the callback:
var enableBtn = function () {
$("#button1").removeAttr('disabled');
}
That's about it. As long as the callback is there it should work.

Related

How to submit form when any value selected from populated textbox using javascript or jQuery without clicking submit button

search.php
In this form, when we type something in textbox, matching words are fetched from api_search.php page and displayed as seen in attached screenshot.
<form role="form" id="frm_search" name="frm_search" method="POST" action="./api_search_p.php" enctype="multipart/form-data" >
<script type="text/javascript">
$(function()
{
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php'
});
});
</script>
<input type="text" id="txt_itemname" name="txt_itemname" class="form-control" required data-validation-required-message="Please enter something here">
<button type="submit" class="btn btn-warning"><i class='fas fa-search'></i> </button></span>
</form>
api_search.php
Textbox on search.php is populated from API result data from this page.
-- API data are coming using curl in $result array --
$json = json_decode($result, true);
$arr_searchTerm = array();
if (is_array($json) && !empty($json))
{
foreach ($json as $key1 => $level1)
{
if (is_array($level1) && !empty($level1))
{
foreach ($level1 as $key2 => $level2)
{
array_push($arr_searchTerm, $level2['TITLE']);
}
}
}
}
echo json_encode($arr_searchTerm);
Currently need to click submit button to submit the form. But I want to do so when any word from fetched result is selected / clicked then form should be submitted immediately without clicking submit button.
I tried onselect="this.form.submit()" & onchange="this.form.submit()" with textbox but form is not submitted on any of javascript events.
Please let me know how can I make this working as expected.
Screenshot
You can use select function in your code
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php',
select: function(e, ui){
this.value = ui.item.value;
this.form.submit();
}
});
You can try this way. in this case, you can make your API call every time someone inserts something. This means every single letter will make a call
document.querySelector("#txt_itemname").addEventListener('input',(e)=>{
...
})
and additionally, if you do it as an API try to look at this too http_responses with PHP

Cannot re-enable Submit button in Javascript after it has been clicked. ".querySelector().disabled = false" does not seem to work

I am trying to create a simple google search bar in my website. It works fine. However, I am accounting for user error, and for some reason I cannot re-enable my submit button once it is clicked, under the condition that no input is provided. Please see Javascript code below.
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
setTimeout(() => msg.remove(), 3000);
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
As you can see, if no text is input, it will let the user know they will need to enter an actual search query. However, after that point, the submit button just wont work again.
I tried using .querySelector().disabled = false; , as well as .removeAttribute("disabled"), but nothing is working. What exactly am I missing here, to re-activate the submit button once it was clicked with no input?
Your button works just fine. You just remove the complete element and then the msg = document.querySelector(".msg"); doesn't find anything. In addition i would leave the timeout out and let the message there until the user writes something.
You should do it like that:
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
msg.innerHTML= '';
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
When button type is set on submit value, it will send the information to the server anyway. (not if you use preventDefault() method!)
My suggestion is to change button type to button and then write an onclick event for it and check the validation there , if everything was right then call for form submit event!
This is how you can prevent incorrect information from being sent into the server side and avoid the errors that it can cause.

jQuery submit() with spin.js is preventing form from submitting?

I have a form that submits just fine, but when I add jQuery code to show a loading div using spin.js everything stops working.
<form id="search_form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<!-- Form inputs here -->
...
<input id="exam_search" type="submit" name="submit" value="Search" />
Once I add the following code the form stops submitting and nothing happens. The loading div shows for a brief moment and then goes away like expected, but it seems like the form isn't actually submitting anymore.
var opts = // Array of options
var spinner = null;
$("#search_form").submit(function() {
spinner_div = document.getElementById('spinner');
if(spinner == null) {
spinner = new Spinner(opts).spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
} else {
spinner.spin(spinner_div);
$("#search_results, #query").css({"opacity": "0.75"});
$("#search_form :input").attr("disabled", true);
}
});
If I change all of that code in the submit event to this:
$("#search_form").submit(function() {
alert ("form submitted");
});
It shows the alert and then returns the results of the form submission just fine.
What am I doing wrong here?
EDIT
I saw in the jQuery docs for submit() that I shouldn't use the name "submit" on the input field. I tried changing that as well with no luck.
Well I'm not sure why but simply doing this worked:
$("#search_form").submit(function() {
var spinner_div = document.getElementById('spinner');
var spinner = new Spinner(opts);
spinner.spin(spinner_div);
});

Javascript have to click button twice which is outside the form

Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.

Check a user input value against values in array

I have text file. there around 1000 lines in it, each line contains a 8 letter alpha numeric word for example my text file looks like this
TEST1234
T1E2A334
12RR8912
and so on. this file is located on the server in a folder called TestCodes
Now I have an html file called test.html where in this file I have input textbox where the user enters the testcode he/she has with them
I have button called Verify. when this input button is clicked I want to check the user inputed value against the contents in the text file.
If the testcode exists in the text file then display a button called Procced if not display an error message called invalid.
I know how to write the if condition but I have no idea how to check it against the text file
HTML
<div class="user-input">
<input type="text" name="test-code" id="test-code" value="" />
<input type="submit" value="Verify Code" name="verify-code" id="verify-code" />
</div>
<div id="TestRegister">
<form id="club" action="/Proceed.html" method="post" autocomplete="off">
<input type="submit" value="Proceed Registration" name="proceed-register" />
</form>
</div>
<div id="TestError">
<span>Please check the code again, its not valid</span>
</div>
JavaScript
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#TestRegister").hide();
$("#TestError").hide();
$.get("testcodes.txt", function (data) {
var lines = data.split("\n");
// this is where I am stuck. how to pass the above to ARRAY
$("#verify-code").click(function (e) {
e.preventDefault();
if ( /* here I need to check against the user input value, if they are equal */ ) {
$("#TestRegister").show();
$("TestError").hide();
} else {
$("#TestRegister").hide();
$("TestError").show();
}
}
});
</script>
How can I pass text from testcodes to an Array and then check the user input value against this array? If the user input value is present in the array then I want to show #TestRegister, and if not, or if the input value is blank or null, show #TestError.
Thanks and appreciate any tips.
var lines;
$(document).ready(function () {
$("#TestRegister").hide();
$("#TestError").hide();
$.get("testcodes.txt", function (data) {
lines = data.split("\n");
});
$("#verify-code").click(function (e) {
e.preventDefault();
if (lines.indexOf($("#test-code").val()) !== -1 && $("#test-code").val().length == 8) {
$("#TestRegister").show();
$("TestError").hide();
} else {
$("#TestRegister").hide();
$("TestError").show();
}
});
});
You can avoid an array loop altogether by creating a regular expression that ensures the test code is found between word boundaries:
var codeRegEx = new RegExp('\\b'+$('#test-code').val()+'\\b');
if(codeRegEx.test(lines)) {
// the testcode is found on a single line, avoiding partial matches
}
Here's a demo:
jsFiddle DEMO

Categories

Resources