External Js file does not validate my html form - html

I did a code in html linked to an external Js file but it the JS code doesn't validate the form fields. Can anyone spot the problem please. I tried everything i could to get the JS to validate the form but it just wouldn't work. Below is the JS code:
<script>
function validateMyForm() {
var fname = document["myform"]["firstname"].value;
var lname = document["myform"]["lastname"].value;
var email = document["myform"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
var pass = document["myform"]["password"].value;
var passlen = pass.length;
var confpass = document["myform"]["ConfirmPassword"].value;
if (fname == null || fname == "") {
alert("Please enter your First Name!");
return false;
} else if (lname == null || lname == "") {
alert("Please enter a your Last Name!");
return false;
} else if (email == null || email == "") {
alert("Please enter an email!");
return false;
} else if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Please enter a valid email address!");
return false;
} else if (pass == null || pass == "") {
alert("Please enter a Password!");
return false;
} else if (passlen < 4 || passlen > 15) {
alert("Password needs to be to have a length of 4-15 characters");
return false;
} else if (pass != confpass) {
alert("Passwords do not match!");
return false;
}
}
</script>

Due to the fact that you did not post your HTML, I am going to assume that you are not triggering your function.
In order for your function to work you need to trigger the form validation function. In order to do this, you will need to add onsubmit="return validateMyForm()" to your form tag. Make sure to include return before calling your function. As shown here
If there are problems with your code you see the errors using the inspector that is built into all web browsers. If you are using chrome you can access the inspector by pressing Control+Shift+C

Related

AngularJS Selects Empty Option Even Valid Option is Avaliable

I'm using AngularJS ver. 1.2.15 on my project. And, I have a select element on one of my views as per below:
<select class="select-white form-control form-select" id="cat2_{{feed.id}}" ng-model="feed.operationstatusid" ng-change="updateCategoryAndStatus(feed, true)"></select>
And, I'm feeding this element like this:
function SetCategory2(cat1Id, feed) {
var feedId = feed.id;
var fromRuleOpStatusId = -1;
$('#cat2_' + feedId).find('option').remove();
if (cat1Id > -1) {
$('#cat2_' + feedId).append($('<option></option>').text(lang.SelectSubCategory).val(0));
$.each($scope.category2, function (index, cat2Item) {
$('#cat2_' + feedId).append($('<option></option>').text(cat2Item.statusdescription).val(cat2Item.id));
});
var isselected = false;
$.each($scope.category2, function (index, cat2Item) {
if (feed.operationstatusid == cat2Item.id) {
$('#cat2_' + feedId).val(cat2Item.id);
fromRuleOpStatusId = -1;
isselected = true;
}
else {
var feedStr = "";
if (feed.title != undefined && feed.title != null) {
feedStr = feed.title.toLowerCase();
}
if ($scope.catTitleRulesTwo) {
$.each($scope.catTitleRulesTwo, function (r_index, r_item) {
if (cat2Item.id == r_item.titleCode && !isselected) {
if (feedStr != undefined && feedStr != null && r_item != undefined && r_item != null) {
String.prototype.contains = function (str) { return this.toLowerCase().indexOf(str) !== -1; };
var text = feedStr;
if (eval(r_item.ruleexpression)) {
$('#cat2_' + feedId).val(cat2Item.id);
fromRuleOpStatusId = cat2Item.id;
isselected = true;
}
}
}
});
}
}
});
if (fromRuleOpStatusId != -1) {
feed.operationstatusid = fromRuleOpStatusId;
}
}
else {
$('#cat2_' + feedId).append($('<option></option>').text(lang.SelectSubCategory).val(0));
}
}
I am aware of the facts about eval function, but the project I'm working on is quite old, so does the code. Anyway, this is about business logic and quite irrelevant with the thing I'm going to ask (or so I was thinking).
As you can see I'm appending all the options before I set the value of the selectbox with using .val(...). I have also checked that values do match along with the data types. But, when I observe this function step by step, I saw that selected value does show up without flaw. After the code finish with my above mentioned function (SetCategory2), code goes through on of the function located on AngularJS file, named xhr.onreadystatechange. It's not a long function, so I'm sharing it also on below.
xhr.onreadystatechange = function() {
if (xhr && xhr.readyState == 4) {
var responseHeaders = null,
response = null;
if(status !== ABORTED) {
responseHeaders = xhr.getAllResponseHeaders();
response = ('response' in xhr) ? xhr.response : xhr.responseText;
}
completeRequest(callback,
status || xhr.status,
response,
responseHeaders);
}
};
After the code released from this function, respective selectbox's value is pointed at the empty option.
I have run into topics which talks about this behaviour might due to invalid option-value match, but as I described above, I append all my options before deciding the value. So, I can't figure out what I'm missing.
Thank you in advance.

using condition in jquery onclick button

Im trying to confirm if the password strength is strong or weak and is the password is strong and when I submit it should have alert message like "You Have Strong Password" and when its weak "Invalid Password"
This is what I am now.
function checkPasswordStrength() {
var passwordStrength = false;
var number = /([0-9])/;
var alphabets = /([a-zA-Z])/;
var special_characters = /([~,!,#,#,$,%,^,&,*,-,_,+,=,?,>,<])/;
if ($('#password').val().length < 8) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('weak-password');
$('#password-strength-status').html("Weak (should be atleast 8 characters.)");
} else {
if ($('#password').val().match(number) && $('#password').val().match(alphabets) && $('#password').val().match(special_characters)) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('strong-password');
$('#password-strength-status').html("Strong");
return passwordStrength = true;
} else {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('medium-password');
$('#password-strength-status').html("Medium (should include alphabets, numbers and special characters.)");
}
}
}
$('#btn-submit').click(function () {
if (passwordStrength == false) {
alert("INVALID PASSWORD");
} else {
alert("You have Strong PASSWORD");
}
</script>
its for Educational Purpose only im just starting jquery..
thank you in advance..
You need to call the function instead of just checking your variable. So rather do
$('#btn-submit').click(function () {
if (checkPasswordStrength() === false) {
instead of
$('#btn-submit').click(function () {
if (passwordStrength == false) {
Then, instead of return passwordStrength = true; you should do just passwordStrength = true and add a return passwordStrength to the very end of your function so it will return either false or true.
It looks like the variable scope is incorrect. var passwordStrength should be put outside of the checkPasswordStrength function.
var passwordStrength
function checkPasswordStrength() {
....

Issue in set value of input field of google forms?

I've made a Chrome extension in which user saves their important links in extension and pastes that link by click on contextmenu of Chrome, but there is a bug: it is not working for Google forms .
When I do click on submit button, the site is giving me an error that you missed the field.
What's the reason for this bug ?
Full content script code from my extension :
var element = null ;
document.addEventListener("contextmenu", function(event){
element = event.target;
});
var types = [
"text",
"url",
"search",
"tel",
"password",
"email",
"number",
"textarea"
];
function getCaretPosition(element){
var caretPos = 0;
/* Chrome and Firefox support */
if(!document.selection && $.inArray(element.type, types) >= 0){
/* element.selectionStart for type email give error because their is a bug in chrome */
if( element.type == 'email' || element.type == 'number' ){
caretPos = 0 ;
}else{
caretPos = element.selectionStart;
}
}
else {
/* IE support */
if(document.selection){
element.focus();
var sel = document.selection.createRange();
sel.moveStart('character', -element.value.length);
caretPos = sel.text.length;
}
}
return caretPos;
}
$(document).ready(function (){
chrome.runtime.onMessage.addListener( function (response , sender , sendResponse) {
var caretposition = getCaretPosition(element);
var initvalue = element.value ;
var first_part = initvalue.substr(0, caretposition);
var last_part = initvalue.substr(caretposition);
if(element.type == 'email' || element.type =='number'){
element.value = response.requested_link + initvalue;
} else {
var selected_text = element.value.substring(element.selectionStart, element.selectionEnd);
if ( selected_text != ''){
last_part = initvalue.substr(caretposition + selected_text.length);
}
element.value = first_part + response.requested_link + last_part;
}
});
});
Bug : I am not sending keypress event when my extension pastes something in the input/Textarea field .
Soultion : I solved this bug by using sendkeyevent , you can read about how to trigger sendkey event here . .

how can i change the html code in crm form?

I used dynamics CRM 2015 and i want to change the OptionSet type to checkboxs.
Just like this:
enter image description here
My solution is use JQuery get the td tag in crm form,and use html() change the td html code.
Like this $("#ubg_note_d").html().But question comes that i can't get the td tag which i want to display the checkbox.Only after i used the browser DEVELOPER TOOLS and select the element,then i can get the tag......i have blocked by this for 1 day,any helps?;)
note:i tried the js and jquery,both can't get the td tag.My code is run in the form Onload event,and i tried the filed Onchange event,trouble still there...
Thing you are trying to achieve is unsupported. Instead you can achieve the same using supported way by creating html web resource, which can be added on form on later.
Code for web resource is as below.
<html><head>
<title></title>
<script type="text/javascript" src="new_jquery_1.10.2.js"></script>
<script type="text/javascript">
// function will be called when web resource is loaded on Form.
$(document).ready(function () {
ConvertDropDownToCheckBoxList();
});
//Coverts option list to checkbox list.
function ConvertDropDownToCheckBoxList() {
var dropdownOptions = parent.Xrm.Page.getAttribute("new_makeyear").getOptions();
var selectedValue = parent.Xrm.Page.getAttribute("new_selectedyears").getValue();
$(dropdownOptions).each(function (i, e) {
var rText = $(this)[0].text;
var rvalue = $(this)[0].value;
var isChecked = false;
if (rText != '') {
if (selectedValue != null && selectedValue.indexOf(rvalue) != -1)
isChecked = true;
var checkbox = "< input type='checkbox' name='r' / >" + rText + ""
$(checkbox)
.attr("value", rvalue)
.attr("checked", isChecked)
.attr("id", "id" + rvalue)
.click(function () {
//To Set Picklist Select Values
var selectedOption = parent.Xrm.Page.getAttribute("new_selectedyears").getValue();
if (this.checked) {
if (selectedOption == null)
selectedOption = rvalue;
else
selectedOption = selectedOption + "," + rvalue
}
else {
var tempSelected = rvalue + ",";
if (selectedOption.indexOf(tempSelected) != -1)
selectedOption = selectedOption.replace(tempSelected, "");
else
selectedOption = selectedOption.replace(rvalue, "");
}
parent.Xrm.Page.getAttribute("new_selectedyears").setValue(selectedOption);
//To Set Picklist Select Text
var selectedYear = parent.Xrm.Page.getAttribute("new_selectedyeartext").getValue();
if (this.checked) {
if (selectedYear == null)
selectedYear = rText;
else
selectedYear = selectedYear + "," + rText
}
else {
var tempSelectedtext = rText + ",";
if (selectedYear.indexOf(tempSelectedtext) != -1)
selectedYear = selectedYear.replace(tempSelectedtext, "");
else
selectedYear = selectedYear.replace(rText, "");
}
parent.Xrm.Page.getAttribute("new_selectedyeartext").setValue(selectedYear);
})
.appendTo(checkboxList);
}
});
}
</script>
<meta charset="utf-8">
</head><body>
<div id="checkboxList">
</div>
</body></html>
Refer below given link for
enter link description here
No code needed for that. It's just configuration on CRM to change the display format : checkbox.

input type=“file” is not working with phonegap

I have to implement file upload feature in my phonegap project. User should be able to upload any type of file from the phone memory or sd card. The application screens I designed using jQuery Mobile framework. I used the below code to invoke the file browser and for the selection of the file.
<input type="file" />
When I run the app, its showing the 'Choose File' button. But nothing happens when I click on this button. I tested it in different android devices but facing the same issue. The LogCat window is not showing any error or warning messages. Is input type="file" supported in mobile browser? Is there any alternative way to implement the same?
input file does work with phonegap, but there is a bug on some android versions (4.4-4.4.2)
HTML file input in android webview (android 4.4, kitkat)
For android you can use this plugin: https://github.com/cdibened/filechooser
You need to include necessary files for JQuery, JQuery Mobile and PhoneGap in your project or main file (that invokes File Chooser). Then create a button in the calling page to launch the browser.
<a href="fileBrowser.html" id="browseBtn" data-role="button"
data-inline="true">Browse</a>
Then set parameters for the file chooser just before displaying it. You can do that by handling click event for ‘browseBtn’
var currPath = "";
var currEntry = null;
if (typeof file_Browser_params == 'undefined')
file_Browser_params = new Object();
if (typeof file_Browser_params.directory_browser != 'boolean')
file_Browser_params.directory_browser = false;
if (typeof file_Browser_params.on_folder_select != 'function')
file_Browser_params.on_folder_select = null;
if (typeof file_Browser_params.on_file_select != 'function')
file_Browser_params.on_file_select = null;
if (typeof file_Browser_params.on_ok != 'function')
file_Browser_params.on_ok = null;
if (typeof file_Browser_params.new_file_btn == 'undefined')
file_Browser_params.new_file_btn = true;
if (typeof file_Browser_params.new_folder_btn == 'undefined')
file_Browser_params.new_folder_btn = true;
function init()
{
if (!file_Browser_params.new_file_btn)
$("#new_file_btn").hide();
if (!file_Browser_params.new_folder_btn)
$("#new_dir_btn").hide();
$("#new_file_btn").click(function(){
if (currEntry == null)
return;
var fileName = prompt("Enter File Name","untitled.txt");
if (fileName == null || fileName == '')
return;
currEntry.getFile(fileName,{create:false},function(){
alert("File already exists");
},
function(){
currEntry.getFile(fileName,{create:true}, function(){
//refresh current folder
getEntries(currEntry);
}, function(){
alert("Error creating file " + fileName);
});
});
});
$("#new_dir_btn").click(function(){
if (currEntry == null)
return;
var fileName = prompt("Enter Folder Name","untitled");
if (fileName == null || fileName == '')
return;
currEntry.getDirectory(fileName,{create:false},function(){
alert("Folder already exists");
},
function(){
currEntry.getDirectory(fileName,{create:true}, function(){
//refresh current folder
getEntries(currEntry);
}, function(){
alert("Error creating file " + fileName);
});
});
});
$("#file_browser_ok").click(function(){
if (file_Browser_params.on_ok == null)
return;
file_Browser_params.on_ok(currEntry);
});
if (typeof file_Browser_params.initial_folder == 'undefined' ||
file_Browser_params.initial_folder == null)
{
file_Browser_params.initial_folder = null;
getRootAndDisplay();
}
else
{
getEntries(file_Browser_params.initial_folder);
}
}
function getRootAndDisplay()
{
getRoot(function(dirEntry){
try {
getEntries(dirEntry);
} catch (err)
{
alertError(err);
}
});
}
function getRoot(onGetRoot)
{
if (typeof window.requestFileSystem != 'undefined') {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
if (typeof onGetRoot != 'undefined')
onGetRoot(fileSystem.root);
}, function(){
log("Error accessing local file system");
});
}
return null;
}
function upOneLevel()
{
if (currEntry == null)
return;
currEntry.getParent(function(parentArg){
getEntries(parentArg);
}, function(error){
alert("Error getting parent folder");
})
}
function getEntries(dirEntry)
{
if (dirEntry == null)
return;
currPath = dirEntry.fullPath;
currEntry = dirEntry;
$("#curr_folder").html(currPath);
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries){
displayEntries(entries);
}, function(err){
if (typeof err.message != 'undefined')
err = err.message;
alert(err);
});
}
function displayEntries(entriesArray)
{
entriesArray.sort(function(a,b){
var str1 = a.name.toLowerCase();
var str2 = b.name.toLowerCase();
if (str1 < str2)
return -1;
if (str1 > str2)
return 1;
return 0;
});
$("#fileBrowser_entries").empty();
var table = $("<table id='file_entry_table'></table>").appendTo("#fileBrowser_entries");
var row = $("<tr class='file_list_row'><td class='file_icon'>D</td><td>..</td></tr>").appendTo(table);
$(row).click(function(event){
upOneLevel();
});
for (var i in entriesArray)
{
var isFolder = entriesArray[i].isDirectory;
var name = entriesArray[i].name;
if (file_Browser_params.directory_browser && !isFolder)
continue;
var row = $("<tr class='file_list_row'></tr>").appendTo(table);
$(row).data("entry", entriesArray[i]);
$("<td class='file_icon'>" + (isFolder ? 'D' : 'F') + "</td>").appendTo(row);
$("<td class='file_name'>" + name + "</td>").appendTo(row);
$(row).click(function(event){
var entryData = $(this).data("entry");
if (entryData.isDirectory) {
if (file_Browser_params.on_folder_select != null)
{
var ret = file_Browser_params.on_folder_select(entryData);
if (ret == false) {
$('.ui-dialog').dialog('close');
return;
}
}
getEntries(entryData);
} else if (file_Browser_params.on_file_select != null)
{
var ret = file_Browser_params.on_file_select(entryData);
if (ret == false) {
$('.ui-dialog').dialog('close');
return;
}
}
});
}
}
function alertError(err){
if (typeof err.message != 'undefined')
err = err.message;
alert(err);
}
init();