Merge logic togther? - javascript

I have the code below, completely new to programming and JavaScript. I need to merge the code, together, i.e. have 1 $(document).ready(function () please advise how to merge/organise code together in 1 file, so all logic carries out its jobs?
//Hide show the sub-cat field
$(document).ready(function () {
//Set field visibility for category
$("#test_category").change(SetFieldsVisibility);
$("#test_category").change();
});
function SetFieldsVisibility() {
var selectedValue = $("#test_category").val();
if (selectedValue === "") {
$("#test_subcategory").closest("tr").hide();
//$("#test_subcategory_name").attr("value","");
$("#test_subcategory_name").val("");
//$("#test_subcategory").attr("value","");
$("#test_subcategory").val("");
$("#test_subcategory_entityname").attr("value", "subcategory");
}
else {
$("#test_subcategory").closest("tr").show();
//$("#test_subcategory_name").attr("value","");
$("#test_subcategory_name").val("");
//$("#test_subcategory").attr("value","");
$("#test_subcategory").val("");
//$("#test_subcategory_entityname").attr("value","");
$("#test_subcategory_entityname").val("");
}
}
//MERGE BELOW CODE WITH TOP
$(document).ready(function () {
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
function selectdepartmentonChange() {
let primaryValue = $("#test_category option:selected").val();
let departmentValue = $("#test_selectdepartment option:selected").val();
if (departmentValue != null) {
primaryValue = departmentValue;
}
setSubCategory(primaryValue);
}
function onPrimaryChange() {
// get id of selected primary field
// this will work only if you render primary field as dropdown
let primaryValue = $("#test_category option:selected").val();
if (primaryValue == "281a04bf-84f4-eb11-94ef-000d3adae0c8" || primaryValue == "3ad4e7db-4533-ec11-b6e6-0022489a108f" || primaryValue == "7b7e1b08-62f4-eb11-94ef-000d3adae0c8") {
$("#test_selectdepartment").empty();
$("#test_selectdepartment").show();
$("#test_selectdepartment_label").show();
//get department category drop down
const query = "/fetchxml-subcategory-portal-lookup/?id=" + primaryValue;
fetch(query, {
method: "GET"
})
.then(response => response.json())
.then(data =>
Object(data.results)
.forEach(item => {
let option = document.createElement("option");
option.value = item.categoryid;
option.innerText = item.title;
$("#test_selectdepartment").append(option);
}))
.catch((error) => {
console.error('Error:', error);
});
// let the control load, then set....
setTimeout(function () {
let departmentValue = $("#test_selectdepartment option:selected").val();
if (departmentValue != null) primaryValue = departmentValue;
setSubCategory(primaryValue);
}, 500);
} else {
$("#test_selectdepartment").hide();
$("#test_selectdepartment_label").hide();
$("#test_selectdepartment").empty();
setSubCategory(primaryValue);
}
}
function setSubCategory(primaryValue) {
// remove all option from dependent field
$("#test_subcategory").empty();
const query = "/fetchxml-subcategory-portal-lookup/?id=" + primaryValue;
fetch(query, {
method: "GET"
})
.then(response => response.json())
.then(data =>
Object(data.results)
.forEach(item => {
let option = document.createElement("option");
option.value = item.categoryid;
option.innerText = item.title;
$("#test_subcategory").append(option);
}))
.catch((error) => {
console.error('Error:', error);
});
}

Sure. Just cut and paste your code from the second $(document).ready call into the first call.
$(document).ready(function () {
// First call:
// Set field visibility for category
$("#test_category").change(SetFieldsVisibility);
$("#test_category").change();
// Second call:
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
// the rest of your code stays down here

You can just put all the code into one function like this.
$(document).ready(function () {
//Hide show the sub-cat field
$("#test_category").change(SetFieldsVisibility); //Set field visibility for category
$("#test_category").change();
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});

Related

JavaScript call function after alert box

In the code, the user composes an email by filling out an html form that takes in recipients, subject and body as inputs. I want to display an alert box if the the user didn't provide any recipients. But after clicking OK in the alert box, the inbox.js file re-loads and the user is presented with the "Inbox" mailbox. However, I want them to stay on the compose-mail view instead. I tried to run compose_email function after the alert box but it didn't work. How might I accomplish that?
inbox.js:
document.addEventListener('DOMContentLoaded', function() {
// Use buttons to toggle between views
document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
document.querySelector('#compose').addEventListener('click', compose_email);
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#display-email').style.display = 'none';
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
// Send an Email
document.querySelector("#compose-form").onsubmit = function(){
const recipients = document.querySelector("#compose-recipients").value;
const subject = document.querySelector("#compose-subject").value;
const body = document.querySelector("#compose-body").value;
if(recipients.length === 0){
alert(`At least one recipient is required`);
compose_email();
}
else{
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
if(result[`error`]){
alert(`User does not exist`)
}
else{
load_mailbox("sent");
}
})
return false;
}
}
}
change your submit function to this and use preventDefault
document.querySelector("#compose-form").onsubmit = function(e){
e.preventDefault();
...
}

insert check function inside submit function to check if there missing inputs before send data to the backend server in Vue JS

I want to add function to prevent submit button from submit data to server if there are empty inputs.
I wrote a checkform function to check if all inputs not empty but i do not how can i insert this function inside createReport function
checkForm: function (e) {
if (this.tops && this.bottoms && this.build && this.wallNumber &&this.authors ) {
return true;
} else {
return false
}
};
My HTML
<v-btn width="100%" class="primary" :loading="isbuildGenerating" #submit="createReport(true)">Generate</v-btn>
java script
createReport: function (isCraft=true) {
this.$refs.form.validate()
this.$emit('buildGenerated', null)
this.isbuildGenerated = true
this.isbuildGenerated = false
let jsonData = {
build:this.build,
wallNumber:this.wallNumber,
time:this.time,
bottoms:this.bottoms
tops:this.tops
authors:this.authors
}
this.$axios.post(this.$backendUrl + '/buildoperations', jsonData)
.then(response => {
this.pdfData = { data: response.data }
this.$emit('pdfGenerated', this.pdfData)
this.isbuildGenerated = true
this.isbuildGenerating = false
})
}

How to successfully call the submit when all validations are true

I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});

How we can use USER ROLE in jQuery?

I am using the functions below for showing project info in popup which is working fine.The 2nd function is used to delete only the Document files for that particular project.I want to disable this function for Users with role "Manager".
function openShowProjectModal(id) {
$.post("/get-project-info", {ID: id}, function (res) {
var project = JSON.parse(res);
$("#job-name-show").text(project.JobName);
$("#job-number-show").text(project.JobNumber);
$("#location-show").text(project.Location);
var files = "";
for (var i = 0; i < project.Docs.length; i++) {
var filename = project.Docs[i].Document;
var id = project.Docs[i].ID;
// I want to disable the Delete function or to hide this Trash icon.
files += i+1 + ". " +(''+filename+'' ) +" " + '</i> <br/>';
$("#project-files").html(files);
}
});
}
function deleteDoc(id) {
if(confirm("Are you sure to delete?")){
$.post("/remove-doc",
{
ID :id
}, function (res) {
if (res == "removed") {
window.location.href = '/projects';
} else {
console.log("not removed");
}
});
}
}
I do not know where do you store roles. Maybe something like this will work:
function deleteDoc(id) {
if(user.role === "Manager") return;
if(confirm("Are you sure to delete?")){
$.post("/remove-doc",
{
ID :id
}, function (res) {
if (res == "removed") {
window.location.href = '/projects';
} else {
console.log("not removed");
}
});
}

Placing the errors in its respective div

Here i am getting my Error Messages from a separate page and i am displaying it in a a div called #stage_error
$('#stage_error').html(error_string);
So, the errors will be displayed like this
The bus no field is required.
The comp id field is required.
The total seats field is required.
But what i want is to display the errors in its respective div's
i.e., the Bus no should be displayed near the div <div id='busno'> like this.
How can i do that ?
Json :
{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
Update :
Script for request and showing error :
<script>
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
});
$('#stage_error').html(error_string);
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
</script>
Laravel Controller :
public function managebusregister()
{
$BusNo = Input::get('BusNo');
$CompID = Input::get('CompID');
$TotalSeats = Input::get('TotalSeats');
$data = Input::except(array('_token')) ;
$rule = array(
'BusNo' => 'required|unique:company_bus',
'CompID' => 'required',
'TotalSeats' => 'required|max:50'
) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return json_encode($validator->messages()); //php encoded value
}
else
{
DB::insert('insert into company_bus (BusNo, CompID, TotalSeats) values (?, ?, ?)',
array($BusNo, $CompID, $TotalSeats));
return '';
}
}
Html Code :
<div id="stage_error" style="color:red;font-size:15px"></div>
<div id="stage_success" style="color:green;font-size:20px"></div>
and beyond that i have each field input boxes,
<input type="text" id="BusNo" name="BusNo"/>
<input type="text" id="CompID" name="CompID"/>
How can i throw error messages near the respective fields
Below is the approach: Observe I've added spans with error after text boxes.
CSS
<style>
.error { color:red; font-size:15px; }
</style>
Html
<input type="text" id="BusNo" name="BusNo" /><span class="error"></span>
<input type="text" id="CompID" name="CompID" /><span class="error"></span>
JavaScript I did some changes as per the jQuery standard, it should work well, if you're not interested then you can ignore all the changes but can take only below mentioned if logic block.
The error display added in if (!data) {...}
$(function () {
$(document).on("click", "#driver", function (event) {
var BusNo = $("#BusNo").val(),
CompID = $("#CompID").val(),
TotalSeats = $("#TotalSeats").val(),
_token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
}).done(function (data) {
$("span.error").empty();//All previous error messages cleared here.
if (!data) {
var obj = JSON.parse(data);
//obj = {"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
$.each(obj, function (entry) {
var targetSelector='';
if (entry == "busno") {
targetSelector = "#BusNo";
}
if (entry == "Comp Id") {
targetSelector = "#CompID";
}
if(targetSelector) //Here we're setting error message for respective field
$(targetSelector).next("span.error").html(obj[entry]);
});
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
you can try like this:
var json = JSON.parse('{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}');
// alert(json['busno']);
$("#busno").html(json.busno);// like this for others also.
change here:
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
if(entry == 'busno'){
$("#busno").html(obj[entry]);// like this for others also.
}
if(entry == 'Comp Id'){
$("#compid").html(obj[entry]);// like this for others also.
}
});
$('#stage_error').html(error_string);

Categories

Resources