Trying to run google tag onsubmit on form button on wordpress (google tag via form setting is not an option)
JS
jQuery(document).ready(function( $ ){
onsubmit = (event) => {
run();
function run() {
<script async src=“https://www.googletagmanager.com/gtag/js?id=AW-000000000”></script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag(‘js’, new Date());
gtag(‘config’, ‘AW-00000000’);
console.log("worked");
}
};
});
Html
<form class="et_pb_contact_form clearfix" method="post" action="site">
and sumbit button
<button type="submit" name="et_builder_submit_button" class="et_pb_contact_submit et_pb_button et_pb_custom_button_icon" data-icon="=">sumbit</button>
Related
I have my HTML code:
<!DOCTYPE html>
<head>
<script src="../req.js"></script>
</head>
<link rel="stylesheet" href="style.css">
<html>
<body>
<h1> Recipes founder</h1>
<form class="example">
<input id ="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button id="searchRecipe" type="button" onkeydown="handler(e)" onclick="searchFile()"><i></i>Search</button>
</form>
<div id="content"></div>
</body>
</html>
and my js code associated with it:
function searchFile(e) {
// enter must do the same
const q = document.getElementById('query').value;
const total_q = `Title%3A${q}%20OR%20Description%3A${q}%20OR%20web%3A${q}`
fetch(
`http://localhost:8983/solr/recipe/select?indent=true&q.op=OR&q=${total_q}&rows=300`, { mode: 'cors' }
).then((res) => res.json())
// Take actual json
.then(({ response }) => appendData(response))
.catch(function (err) {
console.log(err)
});
}
function appendData(data) {
// clear previous research
document.getElementById("content").innerHTML = "";
let docs = data.docs;
// Take each element of the json file
for (elem of docs) {
var mainContainer = document.getElementById("content");
// title recipe
var a1 = document.createElement("a");
a1.setAttribute("href", elem.url);
var div = document.createElement("div");
div.innerHTML = elem.Title;
a1.appendChild(div);
// insert image of recipe and link for page in website
var a = document.createElement("a");
a.setAttribute("href", elem.Image);
var img = document.createElement("img");
// img.setAttribute("href", elem.url);
img.setAttribute("src", elem.Image);
a.appendChild(img);
// recipe description
var p = document.createElement("p");
p.innerHTML = elem.Description;
// Insert elements in dev
mainContainer.appendChild(a1);
mainContainer.appendChild(p);
mainContainer.appendChild(a);
}
}
function handler(event) {
if (event == "click") {
searchFile();
}
else if ((event.keyCode || event.which) == 13){
event.preventDefault();
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation();
event.preventDefault();
searchFile();
}
else {
console.log("Nothing")
}
}
What searchFile() and appendData() do is not important because they work. The target is when the user clicks on the search button or presses the enter key, searchFile() must be called. Clicking on the search button works, but the problem is when a user clicks enter, it navigates to http://localhost:8000/?search=SOMETHING (depends on what the user inserted) . I think it is the default behaviour of the enter key, I tried to prevent it using different codes but nothing works. I read that instead of using the event onkeypress we have to use onkeydown but I'm still in the same situation. I tried also to wait for the DOM to be loaded but nothing. Does someone have an idea about it?
Remove all the event handlers on the button
Make the button a submit button
Use the submit event on the form (this will trigger if the form submission is trigged by enter in the input or the button being clicked or enter being pressed over the button)
Prevent the default event behaviour (so the form data isn't submitted to a URL which the browser navigates to)
Don't bother doing any tests to try to figure out if it was a click or something else, all that matters if that the form was submitted.
const submitHandler = (event) => {
event.preventDefault();
alert("You can do your ajax search here");
};
document.querySelector('.example').addEventListener('submit', submitHandler);
<form class="example">
<input id="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button>Search</button>
</form>
this is my javascript code the onclick functions do not trigger when i push the button I have tried with an event listener that listen only for the parent of the button aka the form but nothing in that case it fires once and it does not keep listening for further button clicks:
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
document.addEventListener('DOMContentLoaded', () =>{
const room__message = Handlebars.compile(document.querySelector('#room__message').innerHTML);
document.querySelector('#send__button').onclick = () =>{
console.log('hola el boton fue pulsado')
let message = document.querySelector('#message__input').value
let user = localStorage.getItem('user')
let channel = localStorage.getItem('channel')
console.log(message)
socket.emit('send message', {'message':message, 'user':user, 'room':channel})
document.querySelector('#message__input').value = '';
}
socket.on('connect', () =>{
socket.emit('join', { 'channel':localStorage.getItem('channel'), 'user':user })
load__list();
load_messages(localStorage.getItem('channel'))
});
document.querySelector('#add__room').onclick = () => {
let list = JSON.parse(localStorage.getItem('channel__list'));
let name_ = prompt("Please enter you'r new Channel's name", "");
while (name_ in list || name != null){
name_ = prompt("this name is already in the database", "");
}
if (name_ != null){
list.push(name_)
}
socket.emit('new room', {'name':name_})
};
socket.on('broadcast', data =>{
let message = data.message;
let user = data.user;
let timestamp = data.timestamp;
const msj = room__message({'message':message, 'user':user, 'timestamp':timestamp})
document.querySelector('.message__cont').innerHTML += msj;
});
});
the html looks like this:
<body>
<ul id="channel__list">
<li>
<button id="add__room">+</button>
</li>
</ul>
<div id="chanel__container">
<form id="channel__form" action="" >
<input type="text" id="message__input" autocomplete="off" placeholder="message">
<input type="submit" id="send__button" value="send">
</form>
</div>
</body>
it does run in a flask server I dont know if that may be an issue
First of all, there are quite a few syntax errors in your code.
Inside your HTML code
<from> tag is to be changed to <form>
Inside your JS code
ID room__message is not declared hence this will never return anything.
You have opened a function socket.io('connect') function but never closed.
Coming back to why the on click buttons are not getting triggered *
The possible reason this could be happening is that by the time your document readyState is already completed in this case the event DOMContentLoaded will not be fired at any point in time. This can be avoided by providing/checking document ready state.
Below are two sample codes (I am still not sure why you are using on click function inside a listener while you can use JS shorthand and directly use it)
Proper HTML code
<body>
<ul id="channel__list">
<li>
<button id="add__room">+</button>
</li>
</ul>
<div id="chanel__container">
<form id="channel__form">
<input
type="text"
id="message__input"
autocomplete="off"
placeholder="message"
/>
<input type="submit" id="send__button" value="send" />
</form>
</div>
</body>
Your actual JS code (a bit modification)
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", loadDomContent());
} else {
console.log("Current document load state: ", document.readyState);
loadDomContent();
}
function loadDomContent() {
const room__message = Handlebars.compile(
document.querySelector("#room__message").innerHTML
);
document.querySelector("#send__button").onclick = () => {
/* do something */
};
socket.on("connect", () => {
socket.emit("join", {
/* do other stuff }); */
});
});
document.querySelector("#add__room").click = () => {
console.log("I am working");
/* do something else */
};
socket.on("broadcast", data => {
/* send some stuff over */
});
}
Also, you can write something like this
<button onclick="addNewRoom()" id="add__room">+</button>
An declaring that as:
function addNewRoom(){
// do something
}
My Solution
the issue was in deed in the html, because it was changing the position of th ebutton by adding more elements to its container im guessing it changed the address to which the event was pointing at, thanks everybody for their input.
I have this code:
index.html
<!DOCTYPE html>
<html>
<div>
<form id="email_subscribe">
<input type="email" name="email" id="email" placeholder="Enter your email">
<input type="submit" value="Subscribe">
</form>
<span id="thank_you" hidden="true">Thank you!</span>
</div>
<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$( "#email_subscribe" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
$("#email_subscribe").slideUp();
$( "#thank_you" ).show("slow");
console.log(ret);
}).addEmail(this); //"this" is the form element
});
});
</script>
</html>
and this one:
Code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle("Web App 2").setSandboxMode(HtmlService.SandboxMode.NATIVE);
return html;
}
function addEmail(form){
Logger.log(form.email);
return 200;
}
The "Thank you message" is not showing up upon submitting the form. Can you please tell me what am I doing wrong. Thank you.
With IFRAME mode however HTML forms are allowed to submit, and if a
form element has no action attribute specified it will submit to a
blank page.
— Offical Documentation
The solution is to add a return false; or event.preventDefault() at the end of your submit function to tell the browser to cancel the event, your code should look like this:
$( "#email_subscribe" ).submit(function() {
google.script.run.withSuccessHandler(function(ret){
$("#email_subscribe").slideUp();
$( "#thank_you" ).show("slow");
console.log(ret);
}).addEmail(this); //"this" is the form element
return false;
});
You can also implement the solution suggested in the docs, create an EventListener to prevent all form submitions on load with this code:
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
</script>
First of all , I have no idea of javascript, I got this code from a tutorial.
I am developing a website in ruby , and to do that I need to make a form of payment. I'm currently using the API Mango.
I have the following code:
<form id="form" action="/pay" method="POST">
<fieldset>
<div>
<label for="ccv">Código de seguridad</label>
<input type="text" id="ccv" required>
</div>
</fieldset>
<input type="submit" value="Pagar ahora!">
</form>
<div id="errores">
</div>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://js.getmango.com/v1/mango.js"></script>
<script>
var PUBLIC_API_KEY = 'public_test_u3wbj4jctik1k2u8qtnajhvn82h590ue';
Mango.setPublicKey(PUBLIC_API_KEY);
var submission = false;
var $form = $('#form');
$form.on('submit', function(event) {
if (submission) {
return false;
}
submission = true;
var cardInfo = {
'ccv': $('#ccv').val()
};
Mango.token.create(cardInfo, handleResponse);
return false;
});
function handleResponse(err, data) {
submission = false;
//Here I put an error message that's displayed in html
if (err) {
...
}
var token = data.uid;
var $hidden = $('<input type="hidden" name="token">');
$hidden.val(token);
$form.append($hidden);
$form[0].submit();
}
</script>
How I can capture that error and show it in html ?
function handleResponse(err, data) {
submission = false;
//Here I put an error message that's displayed in html
if (err) {
...
}
var token = data.uid;
var $hidden = $('<input type="hidden" name="token">');
$hidden.val(token);
$form.append($hidden);
$form[0].submit();
}
this function - is an event handler for Response,obviously. First param is error and if this will be passed your if(err) code block will be executed.
As i see - you use JQuery, so in this place you can Insert some code, which will show error into your form.
For example $('form').append('<div class="error">Some error occurs</div>');
You could try something like
$('body').append($errorp);
Hey guys I'm trying to work my way through this but am having an issue even getting inside my function for form submit in JQuery, I've set up several console.logs but it never actually
gets inside my first functio, does anyone know what I did wrong?
Code
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<script>
console.log('outside function');
$("form").submit(function() {
console.log('submit happened');
queryJsonServer($(this), "class/");
return false;
});
function queryJsonServer(form, path) {
var inputs = $('input:radio').serializeArray();
var params = createAction("saveFormData", inputs);
var url = path + "json.php";
$.post(url, params, function(data) {
console.log(data);
$.("form").submit();
});
}
</script>
HTML
<form>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
You might try to wrap your function in the jQuery function so that it executes when DOM is ready.
<script>
$(function(){
console.log('outside function');
$("form").submit(function() {
console.log('submit happened');
queryJsonServer($(this), "class/");
return false;
});
function queryJsonServer(form, path) {
var inputs = $('input:radio').serializeArray();
var params = createAction("saveFormData", inputs);
var url = path + "json.php";
$.post(url, params, function(data) {
console.log(data);
$.("form").submit();
});
}
});
</script>
This line:
$("form").submit(function() {
…binds a submit event to every form in the DOM at the time the script runs.
Since the script:
Appears in the <head>
Isn't delayed by being called onready / onload / etc
… there are no form elements when the event handler is bound.
Either move the script so it appears after the form element (e.g. just before </body>), or call the function in your ready event handler.