Click on the hidden input to assign a value

To enhance the design, I wish for a <li> element to be clickable when selecting an option to view data. Hence, I have embedded hidden inputs inside it and am contemplating whether I can assign a value to the clicked hidden input using onclick event, and then retrieve this value on my AJAX page with

var getVal = Request.Form["clickedInput"];
. This way, the value will be sent via post since it triggers on click as well.

My goal is for only the currently clicked item to hold the value. If another tab within the same <li> is clicked, then the initial value should be removed from the first tab and assigned to the newly clicked tab instead. Does this make sense?

Below is the code snippet containing the form that includes the <li>.

        <form method="post" action="~/AJAXcalls/repinintAJAX.cshtml" name="form">
            <div class="reportDateDiv">

                <a class="blackColor fSize18 RPtxt">Reporting Period</a>

                <input type="text" name="inputDate" spellcheck="false" class="datepicker metricDateTextbox capitalFirst"
                       onchange="mySubmit(this.form)" value="@inputDate" autocomplete="off" placeholder="@placeholderStartDate.ToString("MMM d, yyyy")" readonly="readonly" />

                <a class="blackColor fSize16 RPtxt RPtxtTo">to</a>

                <input type="text" name="endDate" spellcheck="false" class="datepicker metricDateTextbox capitalFirst"
                       onchange="mySubmit(this.form)" value="@endDate" autocomplete="off" placeholder="@noEndDate.ToString("MMM d, yyyy")" readonly="readonly" />

                <select name="NormOrAvg" class="dwmViewSelect" onchange="mySubmit(this.form)">
                    <option selected=@(Request.Form["NormOrAvg"] == "1") value="1">Rep Per Set</option>
                    <option selected=@(Request.Form["NormOrAvg"] == "2") value="2">Average Rep Per Set</option>
                </select>
            </div>
            <div class="holdLiftMenu">
                <ul class="holdLiftMenuUL">
                    <li class="holdLiftMenuLI">
                        <a class="holdLiftMenuA total current">Total
                            <input type="hidden" name="hid4" id="hid4" value="" />
                        </a>
                    </li>
                    <li class="holdLiftMenuLI">
                        <a class="holdLiftMenuA squat">Squat
                            <input type="hidden" name="hid1" id="hid1" value="" />
                        </a>
                    </li>
                    <li class="holdLiftMenuLI">
                        <a class="holdLiftMenuA benchpress">Benchpress
                            <input type="hidden" name="hid2" id="hid2" value="" />
                        </a>
                    </li>
                    <li class="holdLiftMenuLI">
                        <a class="holdLiftMenuA deadlift">Deadlift
                            <input type="hidden" name="hid3" id="hid3" value="" />
                        </a>
                    </li>
                </ul>
            </div>
        </form>

The following script linked to the <li> elements merely toggles their visibility based on clicks. I also aim to include value assignment/removal in the same click event if feasible.

        $(document).ready(function () {
            $(".total").click(function () {
                $("#piechart").show();
                $("#piechartS").hide();
                $("#piechartB").hide();
                $("#piechartD").hide();
            });
            $(".squat").click(function () {
                $("#piechart").hide();
                $("#piechartS").show();
                $("#piechartB").hide();
                $("#piechartD").hide();
            });
            $(".benchpress").click(function () {
                $("#piechart").hide();
                $("#piechartS").hide();
                $("#piechartB").show();
                $("#piechartD").hide();
            });
            $(".deadlift").click(function () {
                $("#piechart").hide();
                $("#piechartS").hide();
                $("#piechartB").hide();
                $("#piechartD").show();
            });
        });

I lack proficiency in JavaScript and jQuery; any guidance on modifying the script to enable value manipulation upon clicking would be greatly appreciated.

Please note that I utilize cshtml and it does not involve MVC!

Answer №1

When it comes to jQuery, the documentation is a valuable resource: http://api.jquery.com/val/

The val() function has various uses:

var hiddenvalue = $("input[name=hid1]").val(); // retrieves input value
$("input[name=hid1]").val("NewVal"); // sets input value

To implement

$("input[name=hid1]").val("NewVal");
, simply add it at the end of an anonymous function triggered by click();

$(".total").click(function () {
    $("#piechart").show()
    $("#piechartS").hide();
    $("#piechartB").hide();
    $("#piechartD").hide();
    $("input[name=hid1]").val("NewVal");
});

Answer №2

I made changes to your code so that the text field can be updated later on. Take a look at the code below, which will activate the text field when clicked. I hope this solution works for you:

$(document).ready(function () {

$('#prentUL li').click(function(){
$('#prentUL li input').val('');
 $(this).find('input').val('active');
});
            
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="~/AJAXcalls/repinintAJAX.cshtml" name="form">
            <div class="reportDateDiv">

                <a class="blackColor fSize18 RPtxt">Reporting Period</a>

...

                    <li class="holdLiftMenuLI">
                        <a class="holdLiftMenuA deadlift">Deadlift
                            <input type="text" name="hid3" id="hid3" value="" />
                        </a>
                    </li>
                </ul>
            </div>
        </form>

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

What is the best way to create rotational movement for an object in a-frame?

Is there a way to have my entity rotate/spin on the Y-axis? I attempted the following: <a-entity position="-1 0.5 3" animation="property: rotation; to: 0 0 0 ; loop: true; elasticity:1000; dur: 10000" rotation="90 0 0"> <a-box position="1 0 ...

Retrieve image data from the file on the client and adjust its dimensions

I am currently working on a project that involves a gallery manager and a drop area specifically for gallery images. When files are dropped into the drop area, I am using a FileReader to read and obtain the base64 data of the image. My main objective is ...

The namespace does not have any exported object named 'LocationState'

I encountered the following issue while attempting to execute my TypeScript application: Namespace '"C:/DevTools/git/motor.ui/node_modules/history/index"' has no exported member 'LocationState'. Here is a snippet from my pack ...

Having trouble with word wrap and pattern attributes on my website

I'm currently in the process of developing a website and I've implemented the jQuery autocomplete feature. My main goal is to ensure that long words, longer than the input field itself, either break into the next line or allow users to manually b ...

Searching for the value of a JavaScript variable in a PHP DOMDocument

How can I retrieve a JavaScript value in PHP using the DOM? $dom = new DOMDocument(); $html ='<html> <body>Hello <b id="test">Hello World</b>.</body> <script> document.getElementById('test').innerHTML = ...

Modifying the color of a specific node in jstree

I am attempting to modify the background color of the node I have selected in jstree. $('#syncrep').jstree({ 'core' : { 'data' : repository ...

Searching for the desktop location using Node.js

As discussed in the Node.js - Find home directory in a platform-agnostic way question, we can locate the home directory using the following code: const homedir = require('os').homedir(); However, how can I locate the desktop folder in Windows r ...

Leveraging JQuery to retrieve JSON data from a local file

I am currently working on retrieving a list of JSON objects (products) from a local file using Jquery and then storing all of these objects in a single array named allItems. The file is located in the same directory as the code, and it is named "allItems.j ...

Problem: Both select lists are moving all items

The code below pertains to a dual select list, as depicted in the image at this link: https://i.sstatic.net/edd21.png It is functioning as intended. The only issue is that when I click on the last subject in the right-hand side list box (select Subject l ...

checkbox options based on user input

I'm currently working on converting a piece of code into a dynamic checkbox and could use some assistance. Any takers? <select id="genre" name="genre"> <option value="">-Select-</option> <sele ...

Utilize the power of MagicSuggest in combination with CodeIgniter to generate a post output surrounded by square

I have successfully integrated magicsuggest with JSON on CodeIgniter. The current challenge I am facing is that when I post, the values are wrapped in square brackets like ["1"]. Is there a way to remove everything except the number or string without using ...

Ways to refresh the DOM while making an asynchronous request

Consider the following async function: async function predict_from_model() { $("#loading").html("first update") const model = await tf.loadModel('model.json'); $("#loading").html("second update") //delayed for (var i = 0; i < 100; i++ ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

Trouble with Fetching JSON Data using AJAX

Having trouble retrieving JSON data from an acronym finder API using a simple GET request. Here is the code I'm using: $.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD', { crossDomain:true, dataType: "jsonp ...

Having issues with the sidebar malfunctioning and unsure of the cause

<html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> I've been working on creating a sidebar for my website, but it's not functioning as expect ...

Icons on the dropzone are displayed outside of the designated dropzone area

After using dropzone to upload multiple files, I noticed that the icons are displaying outside of the designated box. In the image below, the dropzone form is highlighted in yellow, but when I select numerous files, they overflow and appear outside the for ...

Struggling to properly render JSON data

Having trouble accessing specific elements in a script that merges local JSON files using AJAX? The script works fine in Chrome Console, but you can't reach certain elements like 'object.country'. Any suggestions on how to tackle this issue? ...

Centered vertically: Enhancing buttons with Bootstrap 3

I am struggling to vertically center a group of buttons within a column (as seen in the image). The height of the row is variable and I have tried numerous approaches without success. Screenshot: <div class="row question even"> <div class=" ...

The error with Bootstrap4 alpha6 modal is in the process of transitioning

Currently, I am facing an issue with the bootstrap4 alpha 6 modal. The error message I am receiving is: Error: Modal is transitioning This occurs when attempting to re-trigger the same modal with dynamic data using a JavaScript function like this: funct ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...