Skip to main content

Daily Java Script And jquery Usage

Daily Java Script And jquery Usage 

How to get a query Parameter to an Input Field from client side.

HTML code

Url: http://172.16.1.51:8000/query.html?Business=cafe%20royale

<script>
    let urlParams = new URLSearchParams(location.search);
    document.getElementById('BusinessInput').value=urlParams.get('Business');
</script>


How to trigger clicked event with the Enter button key press for a Form submit button.

problem : The tab navigation hovers the submit button , but clicking enter button doesn't work since it is not a button tag in html.

document.getElementById('submit-button').addEventListener("keyup", function (event) {
            if (event.keyCode === 13) {
            document.getElementById("submit-button").click();
}


Usual JS function

hello=function() {
  return "Hello World!";
}


JS arrow function

hello= () => return "Hello World!";


  
JS arrow function's short form for single return statement functions.

hello = () =>"Hello World!";


Parameter passing

hello = (val)=> "Hello " + val;


Single Parameter passing for JS Arrow function.

hello= val => "Hello"+ val; 

What About this?

In regular functions the  this  keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions the  this  keyword always represents the object that defined the arrow function.



AJAX Request Handling 

The below mentioned code is a failed attempt to create dynamic data form submission.

function generateJSON() {

var products = [];var product = {};var product1 = {};var products1 = [];
for (var i = 0; i <${allProducts.products.size()}; i++) {

if ($('#eligibleProduct' + i).is(":checked")) {
var formData = $('#form' + i);product = getFormData(formData);products.push(product);}
}


for (var j = 0; j <${allProducts.products.size()}; j++) {

if ($('#reward-product' + j).is(":checked")) {
var formData1 = $('#rewardProductForm' + j);product1 = getFormData(formData1);products1.push(product1);console.log(JSON.stringify(products1))
}
}


var eligibleItems = {
milestones: $("input[name='eligibleItems.milestones']").val(),products: products
};var rewardItem = {
count: $('input[name="rewardItems.count"]').val(),groupId: $('input[name="rewardItems.groupId"]').val(),caption: $('input[name="rewardItems.caption"]').val(),products: products1
};
var rewardItems = [];rewardItems.push(rewardItem);

var file = {
name: $('#name').val(),title: $("input[name='title']").val(),bannerImageUrl: $("input[name='bannerImageUrl']").val(),description: $('#description').val(),businessId: '${businessId}',priority: $("input[name='priority']").val(),status: $("input[name='status']").val(),startDate: $("input[name='startDate']").val(),endDate: $("input[name='endDate']").val(),eligibleItems: eligibleItems,rewardItems: rewardItems

};

function getFormData(form) {
var unIndexedArray = form.serializeArray();var indexed_array = {};
$.map(unIndexedArray, function (n, i) {
indexed_array[n['name']] = n['value'];});return indexed_array;}

$.ajax({
type: "POST",contentType: "application/json",url: "/admin/product/plugin/stamp-card.json",data: JSON.stringify(file),dataType: "json",success: function (data) {
console.log(JSON.stringify(data));
$('#generated-json-modal').modal('show');$('#json-content').text(JSON.stringify(data, null, 4));},error: function (data) 
});}

Copy to clipboard method with jquery prepending.

$("#copy-to-clipboard").click(function () {
var el = $('#json-content');el.select();document.execCommand('copy');
});var formGroup = 1;
$("#addReward").click(function () {
$("#form-Group").prepend(" <div id=\"rewardGroup\">\n" +
" <button onclick=\"deleteElement()\"><i class=\"fa fa-times\"></i></button>\n" +
" <label>Group Id :</label> <input type=\"number\" name=\"rewardItems[" + formGroup + "].groupId\">\n" +
"\n" +
" <label>Caption :</label> <input type=\"text\" name=\"rewardItems[" + formGroup + "].caption\">\n" +
"\n" +
" <label>Count :</label><input type=\"number\" name=\"rewardItems[" + formGroup + "].count\">\n" +
" </div>");$('#rewardGroup').attr("id", 'rewardGroup' + formGroup);formGroup = formGroup + 1;});



After  some time I changed the way approached the problem. And found the way to use beans and modelAttributes.
There are set of functions which helped creating dynamic form content and checkbox selection and deselection.

function escapeCharacterAdder(id) {
    return id.replace(/\./g, "\\.").replace(/]/g, "\\]").replace(/\[/g, "\\[");}

function selectAllReward(productChkBoxId) {
    productChkBoxId = escapeCharacterAdder(productChkBoxId);    var varianChkBoxId = productChkBoxId.replace(/\.name/g, "\.checkboxes");    $('#' + varianChkBoxId).find('input[type=checkbox]').each(function () {
        this.checked = $('#' + productChkBoxId).prop("checked");    });}

function reverseDeselectReward(name) {
    var productId = escapeCharacterAdder(name.substring(0, 35).replace(/variants/, "name"));    var checkboxId = escapeCharacterAdder(name.substring(0, 35).replace(/variants/, "checkboxes"));    if ($('#' + checkboxId).find('input:checked').length > 0) {
        $('#' + productId).prop('checked', true);    } else {
        $('#' + productId).prop('checked', false);    }
}

function selectAllEligible(loopIndex) {
    $('#selectbox' + loopIndex).find('input[type=checkbox]').each(function () {
        this.checked = $('#eligibleProduct' + loopIndex).prop("checked");    });}

function reverseDeselectEligible(loopIndex) {
    if ($('#selectbox' + loopIndex).find('input:checked').length === 0) {
        $('#eligibleProduct' + loopIndex).prop('checked', false);    } else if ($('#selectbox' + loopIndex).find('input:checked').length > 0) {
        $('#eligibleProduct' + loopIndex).prop('checked', true);    }
}

var regexName = /(rewardItems\[)\d(]\.\w+)(\[\d\]\.\w+)?(.\w+\[\d]\.\w+)?(.name)?/i; //name matching regexvar regexId = /(rewardItems\[)\d(]\.\w+\[\d]\.checkboxes)/i;                         //id matching regexvar cloneIndex = $(".clonedInput").length;
function clone() {
    $(this).parents(".clonedInput").find('div.margin-top-10.hiding-content').each(function () {
        $(this).css("display", 'none');    });    $(this).parents(".clonedInput").clone()
        .appendTo("#form-group")
        .find("*")
        .each(function () {
            var name = this.name || "";            var match = name.match(regexName) || [];            var id = this.id || "";            var match1 = id.match(regexId) || [];            if (match1.length > 0) {
                // console.log(match1);                this.id = match1[1] + (cloneIndex) + match1[2];                // console.log(this.id);            }
            if ((match.length === 6) && match[3] === undefined) {
                this.name = match[1] + (cloneIndex) + match[2];                // groupId,caption,count replacer            } else if (match[5] === ".name" && match[4] === undefined) {
                this.name = match[1] + (cloneIndex) + match[2] + match[3] + match[5];                // variant.name replacer            } else if (match[4] === undefined && match.length > 0) {
                this.name = match[1] + (cloneIndex) + match[2] + match[3];                this.id = (this.name); //id :rewardItems1products1name                //id :rewardItems[1].products[1].name setting            }
            else {
                this.name = match[1] + (cloneIndex) + match[2] + match[3] + match[4];                // type.name type.sku replacer            }
        })
        .on('click', 'button.clone', clone)
        .on('click', 'button.togglebtn', toggleDiv)
        .on('click', 'button.remove', removeDiv).find("button.remove").attr('disabled', false);
    cloneIndex++;}

function removeDiv() {
    $(this).parents(".clonedInput").remove();}

function toggleDiv() {
    $(this).parents(".clonedInput").find('div.margin-top-10.hiding-content').each(function () {
        $(this).toggle();    });}

$("button.clone").on("click", clone);
$("button.remove").on("click", removeDiv);
$("button.togglebtn").on("click", toggleDiv);
$('#addReward').click(function () {
    console.log("clicked");    $(".clone.btn.btn-danger").first().click();});


Comments

Popular posts from this blog

Hackerank Q&A

HACKERANK SQL PROBLEMS. Question: Generate the following two result sets: Query an  alphabetically ordered  list of all names in  OCCUPATIONS , immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example:  AnActorName(A) ,  ADoctorName(D) ,  AProfessorName(P) , and  ASingerName(S) . Query the number of ocurrences of each occupation in  OCCUPATIONS . Sort the occurrences in  ascending order , and output them in the following format: There are a total of [occupation_count] [occupation]s. where  [occupation_count]  is the number of occurrences of an occupation in  OCCUPATIONS  and  [occupation]  is the  lowercase  occupation name. If more than one  Occupation  has the same  [occupation_count] , they should be ordered alphabetically Answer:   select ( case when occupation= "Doctor" then concat( name ...

Research Project: AutoComplete Business Places Search Form

RESEARCH PROJECT  AUTOCOMPLETE BUSINESS PLACES SUGGESTING DROP DOWN LIST Date: 09/08/2019 The research is on how to use google powered auto suggest input form to search businesses and show its address too. And a thread has been found on auto completing drop down list on google maps platform. A look alike project on autocomplete for addresses and search terms is there in google Maps Platform for developers. The Steps taken. First of all you need the example code in your PC. Create a test Project in google Console. Autofill-inputbox Then the relevant API enabled in That project console. In this case the "Places API" An API key for a particular project. Tried running with the acquired API in the code and putting the file on tomcat server as a jsp file. Still the billing_error comes. The problem was maps API was not enabled. So that the page didn't load. But when it's enabled the website worked for a several seconds. Returning the ...

Check Form Validity

Applova Home page Form Validation. This weeks task was to validate the data that is entered to the Autocomplete business Search Form I created previously. And the second form needed the same modifications. The user was to be restricted from submitting the following: Spaces  Words less than 2 characters Invalid emails The submit button has to be disabled if the three fields were not filled. Using minimal changes in the code this had to be done. And new libraries cannot be used. In that case jquery validation plugin was not an option. But it was the easiest one we had in mind. A small coding for form validation and the plugin script was to be added to solve this matter. But without using that plugin the form was validated and compromised of the invalid inputs as shown below. function getDemoHomeSectionClick () { var user_input = document. forms [ 'form' ][ 'SingleLine1' ]. value ; if ((user_input. trim ()). length < 2 ) { ...