Meteor template won't reference event or method - javascript

In meteor.js, I've having trouble connecting the HTML and the JS. There's no reaction on the button click, and I don't see why not. Therefore the meteor method in server isn't called, and no email is sent.
HTML:
<template name='confirmation'>
<div class = "container" >
<form role = "form" id = "email-form">
<div class = "form-group">
<label for="inputEmail">Email address</label>
<input type= "email" class = "form-control" id = "inputEmail" placeholder = "Enter email">
</div>
<button type = "submit" class = "btn btn-primary"> Send mail</button>
</form>
</div>
</template>
This code runs on the client:
Template.confirmation.events({
'submit #confirmation-form': function (e,t) {
e.preventDefault();
var toAddr=t.find('#inputEmail').value;
var subject = ("Booked");
var body = ("Thanks for booking")
Meteor.call('sendEmail', toAddr, subj, text)
}
})
This code runs on the server:
if (Meteor.isServer){
Meteor.startup(function(){
process.env.MAIL_URL = "mailgun"
Accounts.config({
sendVerificationEmail: true
})
})
Meteor.methods({
'sendEmail': function(toAddr,subj,text){
this.unblock();
Email.Send({
from: "booking#timesharewebapp.com",
to:Meteor.toAddr,
subject : subj,
text: text
})
}
})
}
The problem is that nothing will react when I press the button. Nothing comes up in the console, or in the cmd prompt. I don't know if it's the way I'm calling my events, or if it's the email function.

You are using the wrong selector on the event. Try the below code.
Template.confirmation.events({
'submit #email-form': function (e,t) {
e.preventDefault();
var toAddr=t.find('#inputEmail').value;
var subject = ("Booked");
var body = ("Thanks for booking")
Meteor.call('sendEmail', toAddr, subj, text)
}
})

Related

How to send POST requests from dynamic fields?

I'm creating a quiz form to pass into a JSON file, but I'm having trouble sending the POST requests. I'm not sure which fields I can access, or how.
This is the form: https://i.imgur.com/6xtmt3a.png
<script>
// input field
$(document).ready(function() {
var wrapper = $(".div1");
var newbutton = $(".add_form_field");
var fields = 1;
$(newbutton).click(function(e) {
e.preventDefault();
$(wrapper).append(' <div class="input-group"> <input type="text" value = "Question" class="form-control" placeholder="Recipients username" <div class="input-group-append" id="button-addon4"><button class="btn btn-outline-secondary" id ="delete" type="button">Delete</button><button class="btn btn-outline-secondary" id ="add" type="button">Add</button></div></div></div>'); //add input box
//$(wrapper).append('<button type="button" id ="test1" class="btn btn-primary">Primary</button>'); //add input box
//$(wrapper).append('<div><input type="text" value = "Question"name="mytext[]"/> Delete add </div> '); //add input box
var d = $(this).parent('form').serialize();
console.log(d);
});
//delete buttons
$(wrapper).on("click", "#delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
fields--;
})
// remove div
$(wrapper).on("click", '#s1', function(e) {
//$(this).parent('div').parent('div').remove();
var q= $(this).parent().serialize();
console.log(q);
})
//add answer
$(wrapper).on("click", "#add", function(e) {
e.preventDefault();
$(this).parent('div').append('\n <div class="input-group flex-nowrap"><div class="input-group-prepend"><span class="input-group-text" id="addon-wrapping">-</span></div><input type="text" class="form-control" placeholder="Answer" aria-label="Username" aria-describedby="addon-wrapping"></div> ' );
var d = $(this).parent('form').serialize();
console.log(d);
//$(this).parent('div').parent('div').append('<div class="input-group mb-3"><input type="text" class="form-control" placeholder="Recipients username" aria-label="Recipients username" aria-describedby="button-addon2"><div class="input-group-append"><button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button></div></div>' );
fields--;
})
});
$( "#quizForm" ).submit(function( event ) {
var $form = $( this ),
path = $form.attr( "action" );
payload = {"testKey":"test"};
var posting = $.ajax({
url: path,
method: "POST",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: payload,
dataType: "application-json",
});
console.log(payload);
posting.done(function() {
console.log("posted");
});
});
</script>
I need to have a JSON file output on submit that contains the questions and answers to each question (right or wrong for now) Thanks!
I would suggest adding an attribute contains the object's key on each question - let's say it will be the "question ID".
we will have something like that:
<div class="question-container" question-id="01"></div>
Assuming that answers are an .answer div with an input inside we will have something like that on form submit:
let formObject = new Object();
$('.question-container')
.each(function () {
const questionID = this.attr('question-id');
const answersArray = new Array();
this.find('.answer input')
.each(function () { // assuming answer is a div contains an input tag
answersArray.push(this.value());
})
formObject[questionID] = answersArray;
})
/// here formObject contains the formatted form as json

Javascript window.location.href in chrome doesn't work after POST method

I have change password html form. When user submits that form, I write another <p> </p> element to tell user changed his password or did not and add link to Login page. Both link to Login and Cancel button does the same - redirect to login page. However, after POST method when I click Cancel/redirect to login buttons the screen just keeps loading and never really redirects you there. If I click submit button once again, it sends POST request again so this button works fine no matter how many requests I send. What's wrong with redirection? I can't seem to figure that out. I checked that in Firefox and it seems to work there fine. My code is below:
document.getElementById("btn_cancel").onclick = function(event) {
window.location.href = "/login";
};
var token = window.location.href.substring(window.location.href.lastIndexOf("/") + 1);
function validate() {
var responseText = document.getElementById('error_id');
var password = document.forms["reset-pasword"]["new_password"].value;
var confirmPassword = document.forms["reset-pasword"]["repeat_password"].value;
if (password !== confirmPassword) {
error = "Passwords do not match";
responseText.innerHTML = error;
responseText.className = "error_text";
return false;
}
return true;
}
document.getElementById("btn_change").onclick = function(event) {
event.preventDefault();
var responseText = document.getElementById('error_id');
if (validate() != true)
return;
var password = document.getElementById("new_password").value;
var request = {
token: token,
password: password
};
var xhr = new XMLHttpRequest();
xhr.open('POST', '/update', true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = (res) => {
response = res['target']['response'];
if (response) {
response = JSON.parse(response);
responseText.innerHTML = response.message;
responseText.className = "error_text";
} else {
responseText.innerHTML = "Password changed succesfully. Login";
responseText.className = "success_text";
}
};
xhr.send(JSON.stringify(request));
};
<body onload="document.getElementById('reset-pasword').focus();">
<div class="box" id="change_password_panel">
<form name="reset-pasword" id="reset-pasword">
<label for="password">New password</label>
<input type="password" placeholder="New Password" id="new_password" name="new_password" required />
<label for="password">Repeat new password</label>
<input type="password" placeholder="Repeat Password" id="repeat_password" name="repeat_password" required />
<div style="width: 100%; display: inline-block;margin-top: 10px;">
<div style="float: left;"><button id="btn_change" class="button">Change password</button>
</div>
<div style="float: right;"><button id="btn_cancel" type="button" class="button">Cancel</button></div>
</div>
<p id="error_id"></p>
</form>
</div>
</body>
Also, if I click Cancel button first, before clicking Submit, redirection works fine.
If I put window.location.href = "/login"; inside xhr.onload in if and else statements it doesn't work either. So the problem is could be with POST method? I'm really lost with this one..
This is network when I click 'Cancel' before submitting form:
and this is after:
It doesn't even have 'login' in it...
I also tried
document.getElementById("btn_cancel").onclick = function (event) {
event.preventDefault();
fetch('/login/default.html')
.then(window.location.href = "default.html");
};
but it seems it just goes inside window.location.href and never goes out there
I had similar problem once and still I don't know what was wrong, but I solved this problem adding <a> tag agin adding event to the button.
document.getElementById("btn_cancel").innerHTML = "<a href='/login'>Cancel</a>";
Can you try
setTimeout(function(){document.location.href = "/login;"},500);
or
window.location.assign("/login");

focusout handler also fires on focusin

I have jQuery code that executes an AJAX request every time the text input is focused out. The thing I don't understand is when I focus back in the AJAX request gets executed. There's no focusin function defined. Code snippet below:
$(function() {
// some other functions here but no focusin function defined.
$( "#additem" ).click(function(e) {
e.preventDefault();
var _id = "new_pn", _holder = "Enter part number here", btnId = "post", btnIcon = "fa fa-save", btnText = " Add Serial", formId = "new-sn";
openModal(_id, _holder, btnId, btnIcon, btnText, formId);
});
var openModal = function(a,b,c,d,e, f) {
var txtInput = $("#myModal form input")[1], btn = $("#myModal form button")[0], icon = $("#myModal form i")[0], form = $("#myModal form")[0];
txtInput.id = a;
txtInput.placeholder = b;
btn.id = c;
icon.className = d;
form.id = f;
$($("#myModal form span")[1]).text(e);
$("#myModal").attr('style', 'display:block');
};
//Check serial before saving when text field is focusout. 2nd argument, #new-sn is a dynamically created form id.
$('#myModal').on('focusout', $('#new-sn input')[0], function() {
var sn = $("#serial").val();
if (sn) {
Promise.resolve(GetDocumentItems(serialsDb, sn)).then(function() {
console.log(sn.toUpperCase() + " already exists in the database");
}).catch(function() {
console.log(sn.toUpperCase() + " is cleared to save in database.");
});
}
});
});
What am I doing wrong here? Cheers
Added HTML code below:
<div id="myModal" class="modal">
<div class="modal-content">
<!--variable form id (depends on the caller)-->
<form>
<div class="container">
<span class="close">×</span>
<input id="serial" type="text" placeholder="Enter serial number here">
<!--2nd text box, variable id and placeholder (depends on the caller)-->
<input type="text">
<!--button variable id and i variable class (invoker dependent).-->
<button class="green"><i></i> <span></span></button>
</div>
</form>
</div>
</div>

How to get viewbag data in jquery?

Hi I am developing web application in mvc5. I have login form with username and password fields as below.
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid",
#class = "form-control validate[requiredInLogin] text-input "})
#Html.Password("txtPassword", null, new { #maxlength = "15", id =
"txtPassword", #class = "form-control validate[requiredOutLogin] text-input" })
<input type="submit" class="btn btn-primary btnLogin red"
value="SIGN IN" name="submit" />
}
I have below action method,
[HttpPost]
public ActionResult ClickAction()
{
//Some logic
//When 3 unsuccessful attempts made to login then i set
//ViewBag.captcha = true;
return View();
}
I will make 3 unsuccessful attempts to login then i will set ViewBag.captcha to true. Once i set ViewBag.captcha to true i want to access the ViewBag.captcha value in View and i want to display captcha. May i know how can i access Viewbag value in view? any help would be appreciated. Thanks,
Meanwhile i tried below options,
#{
var message = ViewBag.captcha;
}
Then in JS
var message = '#message';
if (message)
{
alert(message);
}
Below is my login view.
<html>
<head></head>
<body>
<div id="formID">
#*<form id="formID">*#
<div class="loginContainer">
<div class="loginContentArea">
<div class="loginLogo"><img src="~/images/c3card.png" alt="C3 Card" align="middle" /></div>
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
<div class="loginUsernamePassword">
<i class="fa fa-user"></i>
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid", #class = "form-control validate[requiredInLogin] text-input ", placeholder = "Username", autocomplete = "off" })
</div>
<div class="loginUsernamePassword">
<i class="fa fa-lock"></i>
#Html.Password("txtPassword", null, new { #maxlength = "15", id = "txtPassword", #class = "form-control validate[requiredOutLogin] text-input", placeholder = "Password", autocomplete = "off", Style = "background:#FFFFFF;" })
</div>
<div class="errormessage">#TempData["Message"]</div>
<div class="captcha" id="captcha">
<div class="g-recaptcha" data-badge="inline" data-sitekey=#System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>
<br />
</div>
<div class="loginButton">
<input type="submit" class="btn btn-primary btnLogin red" value="SIGN IN" name="submit" />
</div>
<div class="loginLink">#Html.ActionLink("Forgot Your Password?", "Index", "ForgotPassword")#**#</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('input[type=password]').each(function () {
$(this).attr('data-background-color', $(this).css('background-color'));
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
$(this).focus(function () {
$(this).attr('type', 'password');
$(this).css('background-color', $(this).attr('data-background-color'));
});
$(this).blur(function () {
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
});
});
});
jQuery(document).ready(function () {
#{ var message = ViewBag.captcha; }
alert(message);
if (message) { alert(message); }
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});
$("#myinput").rules("add", {
minlength: 2
});
</script>
</body>
</html>
This does not work for me.
May i know proper way to access viewbag value in the above scenario? Any help greatly appreciated. Thank you so much.
Since you are using Razor you could do this:
1. Get your ViewBag value to a variable
<script type="text/javascript">
var message = "#ViewBag.captcha";
</script>
You don't have to set it inside your document ready.
2.The variable is of type string however. In order to use it in a function you will have to do something like that:
If(message.toLowerCase() == "true")
in order to get the desired effect.
To convert it to boolean you could use something like that
message = message.toLowerCase() === "true"
Hope it helps
You can initialize a ViewBag value like this:
ViewBag.captcha = "true";
Then you can access it like this in a view:
var message = #ViewBag.captcha;
From here on you will be able to use message. What you essentially did was the following:
you initialize ViewBag.captcha (note that this part is commented out)
you put that into a variable called message
you try to get #message as a string, but you are not using the Javascript value calculated
Can you change the message variable like below in JS and then try
jQuery(document).ready(function () {
var message = '#ViewBag.captcha'; //change it here
if (message)
{
alert(message);
}
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});

Using the required attribute on a password input

I'm trying to set a password input as required in JavaScript.
I have learnt from this post how to do it but it doesn't seem to work with my password input.
<div class = "login">
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</div>
var p = document.querySelector(".enterPassword");
p.required = true;
p.style.backgroundColor = "gray";
var s = document.querySelector(".submit");
s.addEventListener("click", clickHandler.bind(p));
function clickHandler() {
console.log("Password: " + this.value);
}
jsfiddle
Although I do,
var p = document.querySelector(".enterPassword");
p.required = true;
as you can see, there is no required popup when a user fails to enter a password. Does anyone know why not?
Wrap the elements in a form
<form>
<input type = "password" class = "enterPassword">
<button class = "submit">Submit</button>
</form>
You can also check it without using form
document.querySelector(".enterPassword").validity.valid
this will return a Boolean value , but you wont see the error pop up
JSFIDDLE

Categories