cssSelector throwing error in selenium webdriver - javascript

The following lines of code is giving me error:
elem = new Array()
elem = driver.findElements(By.CssSelector('input'));
What's wrong in the above statement?
If I have a HTML form like:
<form role="form" method="post" action="/login_check">
<input type="hidden" value="" name="_csrf_token">
<div class="form-group">
<input id="username" class="form-control input-lg" type="text" placeholder="Email:" required="required" value="sfdgvsgsg" name="_username">
</div>
<div class="form-group">
<input id="password" class="form-control input-lg" type="password" autofocus="autofocus" placeholder="Password:" required="required" name="_password">
</div>
<div class="form-group">
<input id="_submit" class="btn submit" type="submit" value="LOGIN" name="_submit">
</div>
</form>
And I use a script like this:
elem = new Array()
elem = driver.findElements(By.CssSelector('input:required'));
Then also I am getting the same error.
C:\xampp\htdocs\testPhantomJS\node_modules\selenium-webdriver>mocha -t 80000 tes
tMocha/login-as-administrator-mocha.js
TrackRevenue Test
1) Login as Administrator
0 passing (29s)
1 failing
1) TrackRevenue Test Login as Administrator:
TypeError: undefined is not a function
at Array.forEach (native)
EDIT:
As requested, I am presenting my whole code:
var assert = require('assert');
var test = require('selenium-webdriver/testing');
var webdriver = require('selenium-webdriver');
var By = webdriver.By;
var until = webdriver.until;
var equals = webdriver.equals;
/*----login details for Administrator----*/
var userAdmin = '';
var passAdmin = 'DarkPrince2012';
/*---------------------------------------*/
/*-----------extra details---------------*/
var baseUrl = 'http://saswatr3.ouh.co/login';
var expectedTitle = "Track Revenue";
var successMessage = "Welcome to the admin page!";
/*---------------------------------------*/
test.describe('TrackRevenue Test', function()
{
test.it('Login as Administrator', function()
{
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.firefox())
.build();
var loginFlag = 0;
driver.get(baseUrl);
driver.getTitle().then(function(title)
{
if(expectedTitle === title)
{
driver.findElement(By.id('username')).sendKeys(userAdmin);
driver.findElement(By.id('password')).sendKeys(passAdmin);
driver.findElement(By.id('_submit')).click();
driver.findElements(By.cssSelector("input:required")).then(function(elem){
console.log(elem.length);
});
driver.findElements(By.xpath("//a[contains(text(), 'Log out')]")).then(function(elements_arr)
{
if(elements_arr.length > 0)
{
loginFlag = 1;
driver.findElement(By.xpath("//a[contains(#class, 'user-name m-r-sm text-muted welcome-message')]")).getAttribute("innerText").then(function(text){
console.log("Logged in as : " + text);
});
}
else
{
driver.findElements(By.xpath("//div[contains(text(), 'Invalid credentials.')]")).then(function(elements_arr2)
{
if(elements_arr2.length > 0)
console.log("Login Unsuccessful, div invalid credentials found");
else
console.log("Login Unsuccessful, div invalid credentials not found");
});
}
if(loginFlag == 1)
console.log("Login Successful");
else
console.log("Login Unsuccessful");
});
}
else
{
console.log("Verification Failed - An incorrect title is displayed on the web page.");
}
});
driver.quit();
});
});
What I want to achieve:
See this section:
driver.findElement(By.id('username')).sendKeys(userAdmin);
driver.findElement(By.id('password')).sendKeys(passAdmin);
driver.findElement(By.id('_submit')).click();
driver.findElements(By.cssSelector("input:required")).then(function(elem){
console.log(elem.length);
});
As you can compare with the HTML form, when the submit button is clicked, the HTML5 validation is checked. If any of the two inputs are blank, then the HTML% validation throws a message.
I want to check that HTML5 validation message in the selenium script. If no validation message is thrown, the form is presumed submitted.
The problem I am facing is, neither I can detect the HTML5 validation, and after the
driver.findElement(By.id('_submit')).click();
the form is getting submitted.

You are getting type error because you are using invalid locator tag. Change CssSelector to cssSelector in your code above, it should fix your problem.
elem = new Array()
elem = driver.findElements(By.cssSelector('input'));
Hope this helps.

What are you trying to accomplish with this CSS Selector?
"input:required"
Are you trying to get the INPUTs with the required attribute? If so, try this
driver.findElements(By.cssSelector("input[required]"))
If not, please explain more clearly what you are trying to do.

Related

405 Method Not Allowed - The method is not allowed for the requested URL

I am going to get input from a message form (HTML) in js, but it shows The method is not allowed for the requested URL. Can anyone help me find where is the issue? Thanks!
js code:
var socket = io.connect("http://" + document.domain + ":" + location.port);
socket.on("connect", async function () {
var usr_name = await load_name();
if (usr_name != "") {
socket.emit("event", {
message: usr_name + " just connected to the server!",
connect: true,
});
}
var form = $("form#msgForm").on("submit", async function (e) {
e.preventDefault();
// get input from message box
let msg_input = document.getElementById("msg");
let user_input = msg_input.value;
let user_name = await load_name();
// clear msg box value
msg_input.value = "";
// send message to other users
socket.emit("event", {
message: user_input,
name: user_name,
});
});
});
HTML form:
<form id="msgForm" action="" method="POST" style="bottom:0; margin: 0% 0% 0% 0%;">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Message" aria-label="Message" id="msg">
<div class="input-group-append">
<button class="btn btn-success" type="submit" id="sendBtn">Send</button>
</div>
</div>
</form>
Well, this is quite simple and is basic JavaScript.
Fetch the input using querySelector or get it by its ID.
Take the input and use .value
const input = document.querySelector("#msgForm");
console.log(input.value);

Validate form using Flask, Ajax and jQuery to check data from back-end before submitting the form

I have recently started learning Python and jQuery. I am doing a small exercise for validating the form from back-end. I do not want to submit the form if the validation fails.
Here, I want to print the message, user already exists if user record is present in the backend. The code I wrote for validation works but by form is always getting submitted. Much appreciate guidance from this forum on how to handle this form submission.
Here's a snippet of my code:
HTML:
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" id="user" placeholder="Username*" type="text" required>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password*" type="password" required>
</div>
$('form').on('submit', function(e) {
let user = document.querySelector("#user").value;
$.get('/validate?q=' + user, function(users) {
let text = '';
if (users.length != 0) {
document.querySelector("#error").innerHTML = "Username already exists";
return false;
}
});
});
application.py
#app.route("/validate")
def validate():
user = request.args.get("q")
row = db.execute("SELECT username FROM users WHERE username = ?", user)
print(row)
return jsonify(row)
You need to validate that outside your "get" function, preferably using a variable.
$('form').on('submit', function(e) {
var chkUser = 0;
let user = document.querySelector("#user").value;
$.get('/validate?q=' + user, function(users) {
let text = '';
chkUser = users.length;
if (users.length != 0) {
document.querySelector("#error").innerHTML = "Username already exists";
return false;
}
});
if (chkUser > 0)
return false;
});
I haven't tested this code. Also you should mention how are you subtmitting your form. The easiest way is just to have an <input type='submit'> element.

Implementing jQuery AJAX from within Javascript

I used a tutorial from css-tricks to help me with HTML5 Constraint Validation for my application's client-side validation. I would like to introduce an AJAX script that submits the form to prevent reloading the page (as the form is displayed in a modal pop-up that I don't want closing on submit.)
From what I have gathered online, it seems the best way to do this is to use jQuery. However, the validation script is written in regular ol' Javascript.
I'm kind of confused as to how to implement this within my validation script so that I don't need to make another http request to a separate js file (not even sure if that's an option, as I kind of need it to work seamlessly with the existing script). Do I just call jQuery inside the existing script to prevent conflicts (as shown below?) Do I need to wrap the entire script in the ready event?
Currently, I'm not sure why this isn't working. The form still submits and reloads the page, so it seems to be ignoring the Ajax submit function.
The following includes the form markup from its PHP class and the form.validate.js file used for validation and ajax:
function copyTxtVal(bf) {
if(bf.samecheck.checked == true) {
bf.contact_name_first.value = bf.cpap_sup_name_first.value;
bf.contact_name_last.value = bf.cpap_sup_name_last.value;
} else {
bf.contact_name_first.value = '';
bf.contact_name_last.value = '';
}
}
// Add the novalidate attribute when the JS loads
var forms = document.querySelectorAll('.validate');
for (var i = 0; i < forms.length; i++) {
forms[i].setAttribute('novalidate', true);
}
// Validate the field
var hasError = function (field) {
// Don't validate submits, buttons, file and reset inputs, and disabled fields
if(field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') return;
// Get Validity
var validity = field.validity;
// Get valid, return null
if(validity.valid) return;
// If field is required and empty
if (validity.valueMissing) return 'Please fill out this field.';
// If not the right type
if (validity.typeMismatch) {
if(field.type === 'email') return 'Please enter an email address.';
if(field.type === 'url') return 'Please enter a URL.';
}
// If too short
if (validity.tooShort) return 'Please lengthen this text to ' + field.getAttribute('minLength') + ' characters or more. You are currently using ' + field.value.length + ' characters.';
// If too long
if (validity.tooLong) return 'Please short this text to no more than ' + field.getAttribute('maxLength') + ' characters. You are currently using ' + field.value.length + ' characters.';
// If number input isn't a number
if (validity.badInput) return 'Please enter a number.';
// If a number value doesn't match the step interval
if (validity.stepMismatch) return 'Please select a valid value.';
// If a number field is over the max
if (validity.rangeOverflow) return 'Please select a smaller value.';
// If a number field is below the min
if (validity.rangeUnderflow) return 'Please select a larger value.';
// If pattern doesn't match
if (validity.patternMismatch) {
// If pattern info is included, return custom error
if (field.hasAttribute('title')) return field.getAttribute('title');
// Otherwise, generic error
return 'Please match the requested format.';
}
// If all else fails, return a generic catchall error
return 'The value you entered for this field is invalid.';
};
var showError = function(field, error){
// Add error class to field
field.classList.add('error');
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if error message field already exists
// If not, create one
var message = field.form.querySelector('.error-message#error-for-' + id );
if (!message) {
message = document.createElement('div');
message.className = 'error-message';
message.id = 'error-for-' + id;
field.parentNode.insertBefore( message, field.nextSibling );
}
// Add ARIA role to the field
field.setAttribute('aria-describedby', 'error-for-' + id);
// Update error message
message.innerHTML = error;
// Show error message
message.style.display = 'block';
message.style.visibility = 'visible';
}
var removeError = function(field) {
// Remove the error message
// Remove error class to field
field.classList.remove('error');
// Remove ARIA role from the field
field.removeAttribute('aria-describedby');
// Get field id or name
var id = field.id || field.name;
if (!id) return;
// Check if an error message is in the DOM
var message = field.form.querySelector('.error-message#error-for-' + id + '');
if (!message) return;
// If so, hide it
message.innerHTML = '';
message.style.display = 'none';
message.style.visibility = 'hidden';
};
//Listen to all blur events
document.addEventListener('blur', function (event) {
// Only run if field is in a form to be validated by our custom script
if (!event.target.form.classList.contains('validate')) return;
// Validate field
var error = hasError(event.target);
// If there's an error, show it
if(error){
showError(event.target, error);
return;
}
//Otherwise, remove any existing error msg
removeError(event.target);
}, true);
// Check all fields on submit
document.addEventListener('submit', function (event) {
// Only run on forms flagged for validation
if (!event.target.classList.contains('validate')) return;
// Get all of the form elements
var fields = event.target.elements;
// Validate each field
// Store the first field with an error to a variable so we can bring it into focus later
var error, hasErrors;
for (var i = 0; i < fields.length; i++) {
error = hasError(fields[i]);
if (error) {
showError(fields[i], error);
if (!hasErrors) {
hasErrors = fields[i];
}
}
}
// If there are errors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
}
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else {
(function($){
var form = $('#cpapsupform');
var formMessages = $('#cpap-form-messages');
// Is this line below necessary if I've done this in the normal js above?
$(form).submit(function(event){
event.preventDefault();
// Serialize Form Data
var formData = $(form).serialize();
//Submit the form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#cpap_sup_name_first').val('');
$('#cpap_sup_name_last').val('');
$('#contact_name_first').val('');
$('#contact_name_last').val('');
$('#cpap_contact_email').val('');
$('#cpap_contact_phone').val('');
$('#cpap_patient_dob').val('');
$('#cpap_patient_zip').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('An error occured and your message could not be sent.');
}
});
});
})(jQuery);
}
}, false);
Here is the form markup (excerpted from the php form class I am using):
<?php
<div id="cpap-form-area">
<div id="cpap-form-messages"></div>
<div class="cpap-form-greet">
<p>Some text goes here.</p>
</div>
<form method="POST" action="" id="cpapsupform" class="validate" enctype="multipart/form-data" >
<fieldset>
<legend>Patient Name</legend>
<div class="p-firstname">
<label for="cpap_sup_name_first">First Name:</label>
<input type="text" size="50" name="cpap_sup_name_first" id="cpap_sup_name_first" value="<?php echo $display['cpap_sup_name_first']; ?>" required />
</div>
<div class="p-lastname">
<label for="cpap_sup_name_last">Last Name:</label>
<input type="text" size="50" name="cpap_sup_name_last" id="cpap_sup_name_last" value="<?php echo $display['cpap_sup_name_last']; ?>" required />
</div>
</fieldset>
<fieldset>
<legend>Point of Contact</legend>
<div class="samename">
<div class="cpap_input_alt">
<input id="samecheck" type="checkbox" name="samecheck" onchange="copyTxtVal(this.form);">
</div>
<label for="samecheck">Use same as above</label>
</div>
<div class="c-firstname">
<label for="contact_name_first">First Name:</label>
<input type="text" size="50" name="contact_name_first" id="contact_name_first" value="<?php echo $display['contact_name_first']; ?>" required />
</div>
<div class="c-lastname">
<label for="contact_name_last">Last Name:</label>
<input type="text" size="50" name="contact_name_last" id="contact_name_last" value="<?php echo $display['contact_name_last']; ?>" required />
</div>
</fieldset>
<fieldset>
<legend>Contact Details</legend>
<div class="cpap-email-contact">
<label for="cpap_contact_email">Email:</label>
<input type="email" name="cpap_contact_email" id="cpap_contact_email" value="<?php echo $display['cpap_contact_email']; ?>" title="The domain portion of the email after '#' is invalid." pattern="^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*(\.\w{2,})+$" required />
</div>
<div class="cpap-tel-contact">
<label for="cpap_contact_phone">Phone:<br /><span class="tiny-txt">(10 digits; no spaces)</span></label>
<input type="text" maxlength="10" name="cpap_contact_phone" id="cpap_contact_phone" value="<?php echo $display['cpap_contact_phone']; ?>" pattern="\d{10}" required />
</div>
</fieldset>
<fieldset>
<legend>Patient Date of Birth</legend>
<div class="cpap-dob">
<label for="cpap_patient_dob">Birthdate: <br /><span class="tiny-txt">(MM/DD/YYYY)</span></label>
<input type="text" name="cpap_patient_dob" id="cpap_patient_dob" value="<?php echo $display['cpap_patient_dob']; ?>" title="Your date looks incorrect, or it doesn't match the required format." max-length="10" pattern="((0[1-9])|(1[0-2]))/(([0-2]\d)|([3][01]))/((19|20)\d{2})" required ></input>
</div>
</fieldset>
<fieldset>
<legend>Address Info</legend>
<div class="cpap-zip">
<label for="cpap_patient_zip">Patient Zipcode:<br /><span class="tiny-txt">(first 5 digits only)</span></label>
<input type="text" maxlength="5" name="cpap_patient_zip" id="cpap_patient_zip" value="<?php echo $display['cpap_patient_zip']; ?>" required ></input>
</div>
</fieldset>
<button type="submit" id="cpapAjaxButton" name="cpapAjaxButton">Submit Request</button>
<p class="form-msg">All fields must be completed</p>
<div class="clearfix"></div>
<?php wp_nonce_field('submit_cpap_form','nonce_field_for_submit_cpap_form'); ?>
</form>
</div>
First, you do have a syntax error in that you are missing the opening curly brace of your else branch right here:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else (function($){
It should be:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else { (function($){
And, to avoid these kinds of errors, good indentation and formatting of code goes a long way, so really, this would be the best way to write it:
// Call self invoking jQuery function to handle form submit by Ajax if validation passes
else {
(function($) {
Now, to you main point. As long as you have referenced the JQuery library prior to your code needing to use it, you just go ahead and use JQuery when and where you need to. If you need some page initialization work done, then yes, a "document ready" function should be passed into the JQuery object. But, apart from that, you can leverage JQuery whenever you need to so the self-invoking function you have inside of your else branch is redundant - - if code execution enters that branch, you don't invoke JQuery again, you just use it.
Also, you start off with:
document.addEventListener('submit', function (event) {
But, the document object doesn't have a submit event. The event listener should be set up on the form element that is going to be submitted.
You also have some unnecessary variables and in a couple of cases, you set your variables equal to JQuery objects, but then passed those objects into the JQuery object again later as if they were regular DOM objects.
Here is your cleaned up code. Check the comments carefully for what changes were made and why. Also, this is the best we can do with answers since you didn't provide the hasError and showError functions and your HTML as well.
// The document object doesn't get submitted, the form does.
// Also this sytax finds every form that has the "validate" class,
// so there is no need to test for that in the callback function
$("form.validate").on('submit', function (event) {
// Get all of the form elements
var fields = event.target.elements;
// Always initialize your variables. Set them to null if you don't know the value to use yet
// Also, the "error" and "hasError" variables are not needed. You'll see why in a couple of lines down.
var hasErrors = null;
for (var i = 0; i < fields.length; i++) {
// I'm assuming you have a working "hasError" function that returns a boolean
// So, just take that return value and make that the basis for the if condition -- no
// need to store it just to test it on the next line.
if (hasError(fields[i])) {
// I'm assuming you have a working "showError" function. If we've entered into this
// branch of the code, we know that "hasError" returned true, so we can just pass that
// directly into the "showError" function instead of the "error" variable that we've
// now gotten rid of.
showError(fields[i], true);
// No need to test here. There is an error.
hasErrors = fields[i];
}
}
// If there are errors, don't submit form and focus on first element with error
if (hasErrors) {
event.preventDefault();
hasErrors.focus();
} else {
// You don't need a self-invoking function here. Just write the code that should execute
// It is a common convention to name variables that store references to JQuery objects
// with a leading $ to distinguish them as such and not regular DOM objects
var $form = $('#cpapsupform');
var $formMessages = $('#cpap-form-messages');
// Submit the form via AJAX
$.ajax({
type: 'POST',
url: $form.attr('action'), // $form is already a JQuery object, don't pass it to JQuery again
data: $form.serialize() // <-- You had semi-colon here, which you shouldn't have
}).done(function(response) {
// $formMessages is already a JQuery object, don't pass it to JQuery again
$formMessages.removeClass('error');
$formMessages.addClass('success');
// Set the message text.
$formMessages.text(response);
// Just use the DOM form.reset() method here instead of resetting each form field
$form[0].reset();
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$formMessages.removeClass('success');
$formMessages.addClass('error');
// Set the message text.
if (data.responseText !== '') {
$formMessages.text(data.responseText);
} else {
$formMessages.text('An error occured and your message could not be sent.');
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" class="validate">
<input type="text" id="name">
<input type="submit">
</form>
<form action="#" method="GET">
<input type="text" id="name">
<input type="submit">
</form>
jQuery IS Javascript, so of course you can use them together. I think your problem might lie in you not properly bracketing your else statement:
else { (function($){ // was missing brace after 'else'
var form = $('#cpapsupform');
var formMessages = $('#cpap-form-messages');
....
})(jQuery);
}//closing else brace

javascript errors in html

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);

Checkbox always return true value irrespective of status of checkbox

I am using a checkbox inside a of meteor framework. Whether I checked it or unchecked it, it always returns true value. I have already tried many options available on net.
The code is as below:-
Below is the code of the form:-
<template name="subscribedKeyword">
<div class="issue" >
<div class="issue-content">
<h3>
{{category}}
<input id='pp' class="checktype" name="mark" type="checkbox" value="1" {{{done}}} />Get Notifications
<input type="hidden" name="mark" value="0" />
</h3>
</div>
</div>
</template>
Below is the code of .js file
$('input[type="checkbox"]').on('change', function(e){
if($(this).prop('checked'))
{
$(this).next().val(1);
alert('$(this).next().val(1); '+$(this).next().val(1));
// Adding the loggedin user to the collection on checking the checkbox
Subscribed.update(id, {$addToSet: {categorySubscribedUsers : Meteor.user()}});
alert('value added to the subscribed collection');
var msg = "Hello "+ managerName +",\n\n"+ userName";
var subOfSubscribedDomain = 'Notification of Subscribed Domain';
//Send mail to Manager
alert('mail to mgr regarding subscription by user of domain');
Meteor.call('sendEmail',
managerEmailId,
senderEmail,
msg,
id,
subOfSubscribedDomain);
}
else
{
$(this).next().val(0);
alert('pulling of data from subscribed collection');
var subscribedPersons = Subscribed.findOne({category: issueManagerCategory}).categorySubscribedUsers;
if(subscribedPersons && subscribedPersons.length)
{
var j;
for(j= 0;j< subscribedPersons.length;j++)
{
if(subscribedPersons[j].username === Meteor.user().username)
{
var personId=subscribedPersons[j]._id;
Subscribed.update(id,{$pull:{categorySubscribedUsers:{_id:personId}}});
var msg = "Hello "+ managerName
var subOfUnSubscribedDomain = 'Notification of UnSubscribed Domain';
// Send mail to manager
Meteor.call('sendEmail',
managerEmailId,
senderEmail,
msg,
id,
subOfUnSubscribedDomain);
break;
}
}
}
}
});
I have tried:-
document.getElementById()
$('').is(':checked')
Everything that could be possible. But still clueless, any pointer what to do ??``
Try this..
if(document.getElementById('checkbox1').checked==true)
{
}
That's because you have this opening quotation mark:
var msg = "Hello "+ managerName +",\n\n"+ userName";
^
Everything from that " right up until the }); at the end is being treated as a string, and your JavaScript is throwing:
Uncaught SyntaxError: Unexpected token ILLEGAL

Categories

Resources