I have a search form where I'm trying to have it output the results at the bottom of the page without reloading.
<form action='' method='post'>
<div id="search-form">
<input type="text" name="search" class="search-field" id="search" value="" />
<div class="submit-container">
<button type="button" value="" class="submit" id="searchbutton" onclick="searchoutput()" /></button>
</div>
</form>
<br><br>
<p>Type First Name</p>
I want the search results to show below when the button is clicked, using Ajax call to another script. I keep getting an error: "Uncaught ReferenceError: searchoutput is not defined at HTMLButtonElement.onclick
Here is my javascript (using jquery):
$( document ).ready(function() {
function searchoutput() {
if($(".search-field").val().length > 5) { //only shows results when more than 5 characters have been entered
var search = $(".search-field").val();
var update = $(".result");
var goal = 0;
$.get("query-include.php" , {search: search, goal: goal})
.done(function( data ) {
update.empty();
update.append(data);
$(this).remove();
});
};
}
$( ".search-field" ).keydown(function() {
var update =$(".results");
update.empty();
});
});
I have checked other posts and spent a long time trying to get the solution on my own. The odd thing is if I add an event listener for "keyup" in order to run the same function searchoutput as the user types:
var searchfield = document.getElementById("search");
searchfield.addEventListener("keyup", searchoutput);
Then I don't get the ReferenceError and the script runs fine.. I only get the function issue on button click.
It's a scoping issue - searchOutput is defined within the scope of the $(document).ready() function. What you could try is to declare a var for searchOutput before that code, then assign it to the function like this:
var searchOutput;
$( document ).ready(function() {
searchOutput = function () {
if($(".search-field").val().length > 5) {
//etc.
I add an eventListener in the place of searchoutput();
$( document ).ready(function() {
$('.submit').addEventListener('click', function(){
if($(".search-field").val().length > 5) { //only shows results when more than 5 characters have been entered
var search = $(".search-field").val();
var update = $(".result");
var goal = 0;
$.get("query-include.php" , {search: search, goal: goal})
.done(function( data ) {
update.empty();
update.append(data);
$(this).remove();
});
}
});
$( ".search-field" ).keydown(function() {
var update =$(".results");
update.empty();
});
});
In my case,
I was using modular code in my JS (i.e. import and export statements) so when I tried to use onclick, it wasn't calling my submit function. When I simply removed the import statement from my JS code and replaced dependent code with some default values, onclick called my function. Then I tried the addEventListener with import/export and finally it worked for me.
Related
I've written some code that should check a textbox (ID tfa_1) to see if its empty or contains text, this should trigger on a next page button (wfpagenextID6) being clicked.
I've tried replacing my script with an alert("test.") and it dosent appear, so im assuming I have my trigger wrong but I cannot work out what I have done wrong!
My HTML that defines the textbox is below:
<input type="text" id="tfa_2685" name="tfa_2685" value="" placeholder="" title="Previous Surname (if applicable) " class="">
and the button is
<input value="Next Page" type="button" class="wfPageNextButton" wfpageindex_activate="7" id="wfPageNextId6" style="visibility: visible;">
Both of these are generated and I cannot change them!
My Script is:
<script>
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inp.Val= $("#tfa_2685").val();
if (inp.val().length > 0) {
alert("Test.");
}
});
})
</script>
An identifier ( variable ) must not contains dots. ( see more details ECMAScript specification in section 7.6 Identifier Names and Identifiers)
the next variable declaration is wrong
var inp.Val= $("#tfa_2685").val();
to fix this
var inp = $("#tfa_2685");
if you want to assign value to inp variable, you should just do: var inp = $("#tfa_2685").val();
And then call to inp.val() just replace with inp, for inp is not jQuery object so it doesn't have val() method
You have syntax, try this:
$(document).ready(function(){
$('#wfPageNextId6').click(function(){
var inpVal= $("#tfa_2685").val();
if (inpVal.length > 0) {
alert("Test.");
}
});
});
https://jsfiddle.net/cua40s80/
I'm adding a button dynamically by doing:
<input id="{Id}" type="submit" value="View">
{Id} is replaced at runtime with the record id.
I would like to have a function like:
function viewRecord(button) {
//Do something here...
}
How can I add a click listener to the button that corresponds to the correct button being clicked?
I've started learning jquery today and would like an answer that shows how it's implemented.
EDIT
Based on the answer below, I'm trying the following:
<td><input class="viewRecord" type="submit" value="View"></td>
$(".viewRecord").click(function () {
var $table = $('#table'),
var $tableBody = $table.find('tbody'),
var $text = $tableBody.closest('tr').attr('id');
alert($text);
});
However, no alert is being displayed.
Am I missing something?
use following code:
<div id="container">
<input id="{Id}" type="submit" value="View" class="dynamic-btn" />
</div>
(function($) {
var btnClick = function(){
var id = $(this).attr('id');
alert(id);
/*Do smth that you needed*/
};
$(function() {
$("#container").on("click", ".dynamic-btn", btnClick)
});
}(jQuery));
Two steps:
1) Find the input with:
var dynamicButton = document.getElementById('{Id}');
2) Add the click Event Listener with:
dynamicButton.addEventListener('click',function(){viewRecord(dynamicButton.id);},false);
I want to reset Google reCaptcha widget when I submit my form via AJAX and have some input errors or form is sent. I'm using multiple widgets on the same page so I render these widgets explicitly.
My HTML code:
<div class="g-recaptcha" id="recaptcha-1"></div>
<div class="g-recaptcha" id="recaptcha-2"></div>
...
<div class="g-recaptcha" id="recaptcha-20"></div>
Loading widget
<script src="https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit&hl=en" async defer></script>
<script>
var reCaptchaCallback = function() {
var elements = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < elements.length; i++) {
var id = elements[i].getAttribute('id');
grecaptcha.render(id, {
'sitekey' : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
});
}
};
</script>
After submit form:
var id = $('.g-recaptcha', form).attr('id');
grecaptcha.reset(id);
Form is the instance of the submitted form.
Everything works fine when form is fill correctly. But reCaptcha doesn't reset or reload.
It try this grecaptcha.reset() but no results.
Any idea?
The grecaptcha.reset() method accepts an optional widget_id parameter, and defaults to the first widget created if unspecified. A widget_id is returned from the grecaptcha.render() method for each widget created. So you need to store this id, and use it to reset that specific widget:
var widgetId = grecaptcha.render(container);
grecaptcha.reset(widgetId);
See here.
You are passing the wrong id.
$('.g-recaptcha', form).attr('id');
Your selector will capture all 20 reCaptcha widget, but only return a single DOM id (the first reCaptcha). So your code is actually resetting the first recaptcha.
Just edited your code to create a dynamic widget.
<script>
var reCaptchaCallback = function() {
var elements = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < elements.length; i++) {
widgetId+i = grecaptcha.render('recaptcha-'+i, {
'sitekey' : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
});
}
};
</script>
And after you have successfully completed the above task, change in the AJAX success: response
grecaptcha.reset(widgetId+id);
Here the id would be the same that is generated from the below for Loop.
I have two google captcha in same page, two different form
<form id="form1">
<input type="text" name="form1-input">
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXX"></div>
</form>
and
<form id="form2">
<input type="text" name="form2-input">
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXX"></div>
</form>
You can reset first captcha by
grecaptcha.reset(); or grecaptcha.reset(0);
And Second Captcha by index (1)
grecaptcha.reset(1);
I had an issue where there were multiple recaptchas on the page, some were hidden. In this case I had to loop through all of them and reset them like this:
var count = 0;
$(".g-recaptcha").each(function () {
grecaptcha.reset(count);
count++;
});
I'm trying to validate a form written in Javascript/Dojo before posting it using Ajax. Here's the code:
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConfig="parseOnLoad: true"></script>
<script type="text/javascript">
dojo.require("dijit.form.Form");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ValidationTextBox");
</script>
<script>
function send()
{
var mainForm = dojo.byId( "mainform" );
dojo.connect( mainForm , "onsubmit", function( event )
{
dojo.stopEvent(event);
if ( mainForm.validate() )
{
alert( "valid" );
var xhrArgs = {
form: dojo.byId( "mainform" ),
load: function( data )
{
// Success
alert( "Success" );
},
error: function( error )
{
// Error
alert( "Error" );
}
}
var deferred = dojo.xhrPost( xhrArgs );
}
else
{
alert( "not valid" );
}
});
}
dojo.addOnLoad( send );
</script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css"/>
</head>
<body class="claro">
<h2>Invitation:</h2>
<div dojoType="dijit.form.Form" id="mainform" jsId="mainform" encType="multipart/form-data" action="whatever.php" method="post">
<label for="name">Name: </label><input type="text" id="name" name="name" size="50"
dojoType="dijit.form.ValidationTextBox"
required="true"
propercase="true"/>
<br><br>
<button type="submit" dojoType="dijit.form.Button">Send Message</button>
</div>
</body>
Obviously I'm not using "alert"s in the production code; they help show me what's working and what's not working. The problem here is that the call to mainForm.validate() never returns. Commenting out the call to validate() "fixes" the problem (the form data is POSTed to the .php file), but now there's no validation at all.
Hello and welcome to StackOverflow.
Make sure that you are using dijit.byId to find dijits (as opposed to just their DOM nodes with dojo.byId), and that you are using properly cased event names. Try changing your send function like so:
function send()
{
var mainForm = dijit.byId( "mainform" );
dojo.connect( mainForm , "onSubmit", function( event )
....
When you use dojo.byId you get a regular DOM node (the regular HTML <form> tag), and not the actual dijit object (which has the validate function). This is also why improperly case on "onsubmit" works: a regular HTML form has an event called "onsubmit", but the dijit only has a method "onSubmit" (I agree this is a bit confusing).
Its a pie cake. do like this.
dijit.form.Form has a attr called state. if this state is empty string then the form widgets like dojo textbox are valid.
You can do like this.
1) Don't attach onsubmit for the form. Instead just attach click for the button and do the following code inside the button click handler.
var validForm = "";
dojo.connect( submitBtnDojoWidget, "onclick", function( event ){
if(mainform.state === validForm){
mainform.submit();
}
else {
// here mainform.state may be 'invalid' or 'incomplete'
console.log(mainform.state);
}
})
I have a form thats displayed in a modal box now I want to be able to use the same modal box for 2 different pages where they do slightly different things. Is there a way I can set an event or something for the forms submit button to set which javascript function it calls.
I want to do this from within javascript without changing my form code.
Whats the best way to do this?
Can I set a function to a variable and have it called by my button code?
ie:
var buttonFunction;
//Set the button function on load
function MyButtonFuntion() {
buttonFunction();
}
you could do it like this:
var buttonFunction;
if(someCondition){
buttonFunction = function(){
alert("some action");
};
}else{
buttonFunction = function(){
alert("other action");
};
}
function MyButtonFuntion() {
buttonFunction();
}
You may declare a variable with the function name to be called on submit. The following code is an example. Declaring the function to call in a variable functionToCall inside the form will always work here.
<script type="text/javascript">
function callMyFunction(formName) {
var formObj = eval("document." + formName);
if(formObj != null) {
var functionToCall = eval(formObj.functionToCall.value);
if(functionToCall) {
functionToCall();
}
}
}
</script>
<form method="post" name="form1">
<input type="hidden" name="functionToCall" value="form1Function"/>
<input type="button" onclick="callMyFunction('form1')"/>
</form>