Implementing a Jquery Switcher: A Step-by-Step Guide

I always strive to provide clear and specific details about my question.

My goal is to create an Alert Box for different types of inputs, where all inputs will trigger the same alert message in the box instead of separate alerts. I attempted to implement a switch function for the message, but it seems there is an issue. After adding the switch function to the code, the ADD button no longer functions as intended.

I have shared my complete code here including HTML, jQuery, and CSS. You can identify the section marked with /* ---- */ where the problem occurs.

The table works correctly because I left the Switcher in place. If you move the message above in the blockade area and keep the switcher on, you'll notice that the add button stops working.

I would greatly appreciate any help in resolving this issue. Thank you for your assistance :)

(JavaScript code snippet included)

I also want to display specific messages for each input. For example:

Task Select: You haven't selected any task yet :)

Thank you in advance for your help!

I am available to provide any additional information needed to assist me further.

Answer №1

I don't see any issue here. Once your switch is activated, it functions properly.

Take a look at the code snippet provided below.

$(document).ready(function () {

    $('.buttons').on('click', 'button.hide', function () {
        console.log('hide');
        $('form').hide();
    });

    $('.buttons').on('click', 'button.add', function () {
        console.log('add');
        var edit = $('#edit');
        editRow = $('#editRow');

        edit.show();
        if (!($('#addNew').length)) {
            edit.append('<input type="button" id="addNew" onclick="addNewTr()" value="Add" name="submit" />');
        }

        if (editRow) {
            editRow.remove();
        }

        for (var x = 1; x < $('input').length; x++) {
            $('#btd' + x).val('');
        }
    });

    $('#show').click(function () {
        //$('form').show();
        //$('#btd1').val('Vlad');
        //$('#btd2').val('Andrei');
        //$('#btd3').val('vTask');
        //  $('#btd4').val('Ceva');
        //$('#btd5').val('Alceva');
    });
});

function edit(a) {
    var edit = $('#edit');
        addNew = $('#addNew');
        editRow = $('#editRow');

    edit.show();
    if (addNew) {
        addNew.remove();
    }

    if (editRow.length) {
        editRow.replaceWith('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
    } else  {
        edit.append('<input type="button" id="editRow" onclick="save(' + a + ')" value="Edit" name="submit" />');
    }

    $.each($('.tr-' + a).find('td'), function (key, val) {
        $('form#edit input[type=text]').eq(key).val($(val).text());
    });
}

function save(a) {
    var tr = $('tr');
    valid = true;
    message = '';

    $('form#edit input, select').each(function () {
        var $this = $(this);

        if (!$this.val()) {
            var inputName = $this.attr('name');
            valid = false;
            message += 'Please complete all the columns' + inputName + '\n';
        }
    });

    if (!valid) {
        alert(message);
    } else {
        for (var q = 1; q < $('.tr-' + a + ' td').length; q++) {
            $('.tr-' + a + ' td:nth-child(' + q + ')').html($('#btd' + q).val());
        }
        for (var x = 1; x < $('input').length; x++) {
            $('#btd' + x).val('');
        }
        $('#editRow').remove();
    }
}

function addNewTr() {
    var tr = $('tr');
    valid = true;
    message = '';

    $('form#edit input, select').each(function () {
        var $this = $(this);

        if (!$this.val()) {
            var inputName = $this.attr('name');
            valid = false;
        switch (inputName) {
    case 'Project Name':
          message += 'Please enter the ' + inputName + '\n';
          break;
    case 'Task Select':
          message += 'enter task ' + inputName + '\n';
          break;
    case 'Volume':
          message += 'please volume ' + inputName + '\n';
          break;
    case 'Units':
          message += 'lorem ipsum ' + inputName + '\n';
          break;
    case 'Work Hours':
          message += 'pony ' + inputName + '\n';
          break;

    }
        }
    });

    if (!valid) {
        alert(message);
    } else {
        $('table tbody').append('' +
            '<tr class="tr-' + tr.length + '">' +
            '<td>' + $('#btd1').val() + '</td>' +
            '<td>' + $('#btd2').val() + '</td>' +
            '<td>' + $('#btd3').val() + '</td>' +
            '<td>' + $('#btd4').val() + '</td>' +
            '<td>' + $('#btd5').val() + '</td>' +
            '<td>' + $('#btd6').val() + '</td>' +
            '<td class="buttons">' +
            '<button class="removeThis" onclick="removeThis(' + tr.length + ')">Delete</button >' +
            '<button class="edit" onclick="edit(' + tr.length + ')">Edit</button >' +
            '</td >' +
            '</tr>' +
            '');
        for (var x = 1; x < $('input').length; x++) {
            $('#btd' + x).val('');
        }
    }
}

function removeThis(a) {
    $('.tr-' + a).remove();
}
/* CSS Code */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using Angular $http.post, encountering issues with the 'Access-Control-Allow-Origin' header

I have developed two applications using nodejs and angularjs. The nodejs app contains the following code: require('http').createServer(function(req, res) { req.setEncoding('utf8'); var body = ''; var result = '&a ...

Whenever I try to access pages from the Menu, I keep getting a frustrating "Page not Found" error message due to the Handlebars rendering

I am currently working on a Menu website using nodeJS, and I prefer not to have all my html.handlebars in one file. I am facing an issue where my rendering is giving me a page not found error. What could be causing this? Let me share my project structure ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

"Instead of opening the page in a popup window, use window.open to open it in a new tab

I am attempting to open a new popup window using this JavaScript code: window.open(myUrl, ""); However, some users are experiencing the page opening in a new tab instead of a popup window. Does anyone know why this may be happening? ...

Ways to verify if information is being added to a JSON file or not

JSON Here is the JSON structure where I am adding data with a button click event. var myData = { "info" : [] }; JavaScript Function I have written this function to add data to the JSON object: myData.info.push({ "Name" :name, ...

Display Binary Image in HTML Table using Server-side Code

I am currently working on creating a table that will retrieve binary image data from a database and display it in an HTML table. Here is the markup I have used: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml1 ...

Troubleshooting problem with displaying child component in Vue's nested routes

I am facing an issue with vue-router nested routes. https://router.vuejs.org/guide/essentials/nested-routes.html I created a parent route User and a child route UserQuotes, but the child route is not rendering. There are no error messages or warnings in ...

What could be the reason for XMLHttpRequest to freeze with no error until it reaches the default browser timeout limit

As a front end developer, I have some gaps in my understanding of how networks operate. When a Javascript XMLHttpRequest times out, the ontimeout handler gets triggered. In case the XMLHttpRequest.timeout property is not set (which is supported in modern b ...

Unable to adjust the height of the border when hovering over a P tag

Why doesn't the P tag text and border height increase work when it is hovered over by a mouse? What could be causing this issue? Here is the HTML code snippet: <body> <div class="cheap"> <p id= "pen">hello hannan .hello ...

Experimenting with javascript through jasmine testing

I am new to Jasmine testing and would appreciate any help. I have an array of data that needs to be checked for existence. //result is an array of data. var availableTags = new Array(); function show(result) { var items = new Array(); ...

AutomatedPostBack wipes out the data stored in my dropdownlist variable

While using javascript and asp.net, I have encountered an issue with the AutoPostBack function clearing a variable called 'callBackReason' that I declared in Javascript from a dropdownlist. Unfortunately, I need to keep this variable in Javascrip ...

Best practices for securing string values in Node.js

Looking to retrieve the IP address with nodejs/express. Check out the code snippet below that accomplishes this: const ipAddress = String(req.ip || "unknown"); Considering that req.ip is pulled from an HTTP header, there's a potential risk ...

Is the menu not appearing in the header section of the HTML/CSS?

Hey there, I'm a new student diving into the world of HTML/CSS. I've been working on creating a page layout, but for some reason my menu links are appearing under the header section instead of within it. I'm a bit confused and could really u ...

Transform the JSON object into a different JSON format

I am in the process of restructuring the JSON data which is currently organized by categories, with each category containing multiple locations. Each location consists of latitude/longitude coordinates and an area code: { "cat1":[ {"location":{ ...

Generate seamless rotation within a specified time frame (+- x%)

I need to rotate a cube in my scene with a specific initial speed within a specified timeframe. The end angle of the cube must match the starting angle. To account for potential variations, I am allowing for a deviation of up to 5% in the timeframe. Cu ...

What is the best way to determine when the context value has been established?

Currently encountering an issue while trying to display a header. To achieve this, I begin by making an API call in InnerList.js and setting a list in context using the data from the API call. Next, in Context.js, I assign the list to a specific data set ...

JavaScript reasoning based on logic

I am working on a webpage titled a.jsp that contains the following elements: --a1-- --a2-- --a3-- <select onChange="cht('1');" id="a1"><option>H263</option><option>H264</option></select> <div class="Text" ...

Why does the control skip the onreadystatechange function for the ajax object?

Just beginning my journey into web-development. Recently, I encountered an issue with a signup page I created that involves asynchronous calls to php. Upon debugging, I noticed that the onreadystatechange function is being completely skipped over. Any assi ...

Implement ajax functionality to update an object within a JSP page

On my JSP page, I have implemented an accordion list (utilizing Bootstrap 3) with text and a Delete button within each node. When the user clicks on the delete button, that specific list item is removed. To construct the accordion list, I bring in an Array ...

Sending a document using the ng-file-upload directive to a Sails.js server

I am working on uploading a file to a sails.js application server using the ng-file-upload directive provided at this link. Here is the client-side code I am using to upload a pre-selected image: $upload.upload({ url:'upload/item-image' ...