How do i turn this jquery into javascript - javascript

Hi I can't use Jquery here. please help me change these 3 selector into javascript.
I already tried document.getElementById('FeedbackLightBox_txtName').value; but i doesn't work.
<script type="text/javascript">
function SetButtonStatus() {
var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5)
makeBtn();
else
$('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(false);
}
function makeBtn() {
$('#FeedbackLightBox_btnSubmit')[0].control.set_enabled(true);
}
function ClearValues(sender, args) {
$('#FeedbackLightBox_txtName').val('');
$('#FeedbackLightBox_txtMessage').val('');
$('#FeedbackLightBox_txtEmail').val('');
args.set_cancel(true);
return false;
}
</script>

Like this?
document.getElementById('FeedbackLightBox_btnSubmit').control.set_enabled(false);
document.getElementById('FeedbackLightBox_txtName').value = '';
JFYI
When you say
$('#FeedbackLightBox_btnSubmit')[0] // it gives you an access to HTML element object which is equivalent to saying `document.getElementById('Feed..)`.

not sure, where .control.set_enabled(false); is defined on the element, but I guess you do know.
function SetButtonStatus() {
var tb1 = document.getElementById('FeedbackLightBox_txtName').value;
var tb2 = document.getElementById('FeedbackLightBox_txtMessage').value;
var tb3 = document.getElementById('FeedbackLightBox_txtEmail').value;
if (tb1.length >= 5 && tb2.length >= 5 && tb3.length >= 5) {
makeBtn();
} else {
document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(false);
}
}
function makeBtn() {
document.getElementById("FeedbackLightBox_btnSubmit").control.set_enabled(true);
}
function ClearValues(sender, args) {
document.getElementById("FeedbackLightBox_txtName").value = '';
document.getElementById("FeedbackLightBox_txtMessage").value = '';
document.getElementById("FeedbackLightBox_txtEmail").value = '';
args.set_cancel(true);
return false;
}

It seems you have a form something like:
<form id="FeedbackLightBox_form" onsubmit="return validate(this)" action="">
Name: <input name="FeedbackLightBox_txtName"><br>
Message: <teaxtArea name="FeedbackLightBox_txtMessage"></textarea><br>
Email: <input name="FeedbackLightBox_txtEmail"><br>
<input type="submit" id="FeedbackLightBox_btnSubmit"> <input type="reset">
</form>
that you want to check something has been entered into each field before submission, so you validate it using:
function validate(form) {
var control, controls = form.controls;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.type != 'submit' && control.value.length < 5) {
return false;
}
}
}
The clearForm function is entlirely unnecessariy if you inlcude a reset button, but anyway:
function clearForm() {
document.getElementById('FeedbackLightBox_form').reset();
}
Similarly, the (inappropriately named) makeBtn function can be:
function makeBtn() {
document.betElementById('FeedbackLightBox_btnSubmit').disabled = false;
}
Maybe it should be called enableBtn?

Looks like jQuery is only used for getting HTML elements so you could define these as global variables before your functions (or pass them as function arguments) to avoid duplication.
var tb1 = document.getElementById('FeedbackLightBox_txtName');
var tb2 = document.getElementById('FeedbackLightBox_txtMessage');
var tb3 = document.getElementById('FeedbackLightBox_txtEmail');
var btn = document.getElementById('FeedbackLightBox_btnSubmit');
function SetButtonStatus() {
if (tb1.value.length >= 5 && tb2.value.length >= 5 && tb3.value.length >= 5)
makeBtn();
else
btn.control.set_enabled(false);
}
function makeBtn() {
btn.control.set_enabled(true);
}
function ClearValues(sender, args) {
tb1.value = '';
tb2.value = '';
tb3.value = '';
args.set_cancel(true);
return false;
}

Related

Why does this form keep on submitting even if it fails the validation?

I am new to javascript. I would like someone to explain to me why this form keeps getting submitted even if it fails the validation? I am not allowed to use any validation plugins hence I wrote several functions for validation.
/* EMAIL VALIDATION */
let validateEmailInput = (anEmail) => {
let emailRegex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (anEmail.value.search(emailRegex) !== -1 || anEmail.value.match(emailRegex)) {
document.getElementById("errorOutput1").innerText = "";
return true;
} else {
document.getElementById("errorOutput1").innerText = "Invalid email!";
anEmail.focus();
return false;
}
}
/* RADIO VALIDATION */
let validateRadioInput = (name) => {
let radios = document.getElementsByName("part1_radio");
let isCheckedRadio = false;
let numRadioChecked = 0;
let radioChosen;
for (let i = 0; i < radios.length && !isCheckedRadio; i++) {
if (radios[i].checked) {
numRadioChecked++;
document.getElementById("errorOutput2").innerText = "";
radioChosen = radios.item(i).id;
isCheckedRadio = true;
}
} //end for
if (numRadioChecked === 0) {
document.getElementById("errorOutput2").innerText = "Please select one season!";
isCheckedRadio = false;
}
return isCheckedRadio;
}
/* CHECKBOX VALIDATION */
let validateCheckboxInput = (name) => {
let checkboxGroup = document.getElementsByName("part1_checkbox");
let isCheckedCheckbox = false;
let numCheckboxChecked = 0;
let checkboxChosen;
for (let i = 0; i < checkboxGroup.length && !isCheckedCheckbox; i++) {
if (checkboxGroup[i].checked) {
numCheckboxChecked++;
document.getElementById("errorOutput3").innerText = "";
checkboxChosen = checkboxGroup[i];
isCheckedCheckbox = true;
} else {
// if (numCheckboxChecked === 0) {
document.getElementById("errorOutput3").innerText = "Please check at least one country!";
isCheckedCheckbox = false;
}
} // end for
return isCheckedCheckbox;
}
/* SELECT/OPTIONS VALIDATION */
let validateSelectInput = (aSelection) => {
let selectGroup = document.getElementsByName("part1_select");
let isCheckedSelect = false;
let numCheckedSelect = 0;
let selectedVar;
if (!selectGroup.value) {
document.getElementById("errorOutput4").innerText = "Please choose one!";
isCheckedSelect = false;
} else {
isCheckedSelect = true;
selectedVar = selectGroup.value;
}
return isCheckedSelect;
}
This function is called inline like this:
<form id="myForm_part1" name="myForm_part1"action="someemailhere" method="post" onsubmit="validateForm(this.form);" novalidate>
I need help understanding why this happens.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function() {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
return false;
}
});
}
There is an issue with the onsubmit handler. Try changing
onsubmit="validateForm(this.form);"
to
onsubmit = "return validateForm(this.form);"
Without the return statement the submit handler, which is a function compiled from the attribute value, returns undefined because it doesn't have a return statement.
Use preventDefault() to stop submission if validation fails.
function validateForm(form) {
let email = document.getElementById("part1_email");
let radioChoice = document.getElementsByName("part1_radio");
let checkboxChoice = document.getElementsByName("part1_checkbox");
let selectChoice = document.getElementById("part1_select");
$('#myForm_part1').submit(function(event) {
if (!validateEmailInput(email) || !validateRadioInput(radioChoice)
|| !validateCheckboxInput(checkboxChoice) || !validateSelectInput(selectChoice)) {
event.preventDefault();
}
});
}

Validating forms with JavaScript not working as expected

I have two problems one I can't get the Regex (for email) I created to fire properly when I add it to my logic. It seems to make the field which was fine (by entering correct input) invalidate when I tab away...
The second problem is the select dropdown. I am not sure what is the best practice but I essentially would like the select dropdown to remain with the error messages until either the user has selected a proper state.
This is my code:
var ValidationChecker = (function validationHndlr() {
'use strict';
var doc = document;
var form;
var emailRegExp;
var formElements;
emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
form = doc.getElementsByTagName('form')[0];
formElements = form.elements;
function addMultipleListeners(element, events, handler, useCapture, args) {
if (!(events instanceof Array)) {
throw 'addMultipleListeners: ' +
'please supply an array of eventstrings ' +
'(like ["click","mouseover"])';
}
//create a wrapper to be able to use additional arguments
var handlerFn = function(e) {
handler.apply(this, args && args instanceof Array ? args : []);
}
for (var i = 0; i < events.length - 1; i += 1) {
element.addEventListener(events[i], handlerFn, useCapture);
}
}
for (let i = 0, l = formElements.length; i < l; i++) {
var elId = doc.getElementById(formElements[i].id);
addMultipleListeners(elId, ['focus', 'blur', 'keyup'], function(e) {
if ((formElements[i].value == '') || (formElements[i].value == null) || ((formElements[i].type == 'email') != emailRegExp) ) {
formElements[i].classList.add('invalid-input');
formElements[i].nextElementSibling.style.display = 'block';
formElements[i].nextElementSibling.innerHTML = 'Not valid!';
}
}, false);
elId.addEventListener('keyup', function(e) {
console.log('keyup working?');
if ((formElements[i].value != '') && (formElements[i].value.length > 2)) {
formElements[i].classList.remove('invalid-input');
if (formElements[i].nextElementSibling.type !== 'submit') {
formElements[i].nextElementSibling.style.display = 'none'
}
}
}, false);
}
})();

How to display the string content of this array all at once using javascript?

I am using this for form validation. I call this function when there is an error and i send it a string as a parameter.
var errList = new Array();
function aerrorList(error){
errList.push(error);
for (var i=0; i < errList.length; i++){
alert(errList[i]);
}
}
here is one of the validation checks:
function lNameValidate() {
var lName = document.getElementById("lastname");
if (lName.value.length < 20 && /^[a-zA-Z0-9- ]*$/.test(lName.value)){
stNumValidate();
} else {
lName.style.border = "red";
errorList("Invalid lName Format");
stNumValidate();
}
}
The current array (using alert) displays the error in a number of popup boxes with only 1 error string each. i want it to display 1 alert which would show all the errors in a list similar to outputting it in a bullet point way.
You can append all the errors to one var and then display it:
function aerrorList(error){
errList.push(error);
var errors = "";
for (var i=0; i < errList.length; i++){
errors += errList[i] + "\n";
}
alert(errors);
}
You could use join method on an array, Here's an example:
errors=['error1','error2','error3']
Here, a is an array of list of your errors, now you can glue them together using whatever you want like this:
error_string=error.join("\n*")
Finally you can make an alert:
alert(error_string)
Try this:
var Errors = {
messages: [],
push: function(message) {
this.messages.push(message);
},
alert: function() {
alert(this.messages.join("\n"));
},
showInElement: function(element) {
element.innerHTML = this.messages.join('<br/>');
},
clear: function() {
this.messages = [];
}
}
var age = 1;
if(age < 18) {
Errors.push("Come back when You 18+");
}
var name = "Jack";
if(name != "John") {
Errors.push("You're not John!");
}
Errors.alert();
var element = document.getElementById('content');
Errors.showInElement(element);
Errors.clear();
<div id="content"></div>
So I ended up using this:
var errList = new Array();
function errorList(error){
errList.push(error);
}
function showErrors() {
alert(errList.join("\n"));
}
where i just call showErrors on the very last validation check if the errList length is > 1 as such:
function emailRestrict() {
var eVal = document.getElementById("email").value;
var atPos = eVal.indexOf("#");
var dotPos = eVal.lastIndexOf(".");
if (atPos < 1 || dotPos < atPos || dotPos >= eVal.length) {
errorList("not valid email");
if (errList.length > 1){
showErrors();
}
return false;
}
else {
if (errList.length > 1){
showErrors();
}
return true;
}
}

javascript function return "undefine" from jsp page

i have a jsp page and call a JS function which is in some abc.js file from this JSP page.
i have included this js file to jsp page.
JSP JavaScript Code:-
function doFinish(tableId, col, field)
{
var oldselectedCells = "";
var selItemHandle = "";
var selRightItemHandle = "";
var left = -1;
var right = -1;
// Get the table (tBody) section
var tBody = document.getElementById(tableId);
// get field in which selected columns are stored
var selectedCellsFld = document.getElementById(tableId + datatableSelectedCells);
selectedCellsFld.value = oldselectedCells;
for (var r = 0; r < tBody.rows.length; r++)
{
var row = tBody.rows[r];
if (row.cells[col].childNodes[0].checked == true)
{
selectedCellsFld.value = oldselectedCells +
row.cells[col].childNodes[0].id;
selItemHandle = row.cells[col].childNodes[0].value
oldselectedCells = selectedCellsFld.value + datatableOnLoadDivider;
left = selItemHandle.indexOf("=");
right = selItemHandle.length;
selRightItemHandle = selItemHandle.substring(left+1,right);
var index=getColumnIndex(tBody,"Name");
if(index!=null)
{
if(field == 1)
{
window.opener.document.TemplateForm.eds_asbactionscfg_item_handle_child_physpart.value = selRightItemHandle;
window.opener.document.TemplateForm.ChildPhysicalPart.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 2)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 3)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
}
}
}
window.close();
}
JS Code:-
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggest some solution.
getColumnIndex(tBody,columnName) function works fine.
as if it matches this if condition
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
so that it returns something.
but when you replace this
var index=getColumnIndex(tBody,"Name"); so that coulmnName would be "Name" in String.
And it doesn't match with any columnName so that your condition going to be wrong and function doesn't return anything.
var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggestion is put some else condition on that and return some error message like this :
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
} else{
// put some error message
// return null
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine
From this, I'm assuming that there isn't anything wrong with the implementation of your getColumnIndex function, so your issue with getting an undefined value must have to do with when this function is returning a value.
but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
This leads me to assume that your tBody variable is not being set correctly, given that the "function works fine".
I'm assuming there is a case in your code where the conditions of your getColumnIndex function is not met.
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
// If your code reaches this point, then the prior conditions have not been met
// You can choose to do something else here for return false/undefined etc.
return undefined;
}

Retrieving rich text box sharepoint in javascript

I have CustomNewForm for inserting items in the sharepoint list.
The fields are "Reason" and "Reason OverView"; both Multiple Line Rich Text fields. I need to copy some text from "Reason" to "Reason Overview".(A substring)
I tried to get this done with workflow but couldn't find a solution to get a substring of a form field.
I am trying to get the value from "Reason" field in javascript; but unable to do so.
MY CODE :: (not working)
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
alert('Hi');
Original.innerHTML=Reason.innerHTML;
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>
Any way to get this done??
I solved it using this
<script type="text/javascript">
function PreSaveAction()
{
var Reason = getTagFromIdentifierAndTitle("textarea","TextField","Reason");
var Original = getTagFromIdentifierAndTitle("textarea","TextField","Reason Overview");
var reasonText = RTE_GetEditorDocument(Reason.id);
var reasonOverviewText = reasonText.body.innerText;
if(reasonOverviewText.length>=20)
{
reasonOverviewText = reasonOverviewText.substring(0,20)+'......';
Original.innerText = reasonOverviewText;
}
else
{
Original.innerText = reasonOverviewText;
}
return true;
}
function getTagFromIdentifierAndTitle(tagName, identifier, title)
{
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++)
{
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len))
{
return tags[i];
}
}
return null;
}
</script>

Categories

Resources