Unable to retrieve a value after deactivating a Div element

I have created a web page using MVC Razor. On this page, I included a div element with the following structure:

 <div class="row" id="DivDisableForView">
            <div class="col-md-4">
                <label for="" class="control-label">
                    Product
                </label>
                <br />
                @Html.DropDownListFor(m => m.ProductSeq, Model.products.ToSelectListItems(x => x.ProductName, x => x.Id.ToString(), "", true, "", "Select"), new { @class = "form-control" }).DisableIf(() => Model.IsReadOnly == true || !Model.IsAdd)
                @Html.HiddenFor(m => m.ProductSeq)
            </div>
            <div class="col-md-4" runat="server">
                <b>Exception Type</b>
                <br />
                @Html.EnumRadioButtonFor(m => m.enumExceptionType, true).DisableIf(() => Model.IsReadOnly == true || !Model.IsAdd)
                @Html.HiddenFor(m => m.enumExceptionType)
            </div>
            <div class="col-md-4" id="divTranMode">
                <b>Transaction Mode</b>
                <br />
                @Html.EnumRadioButtonFor(m => m.enumTransactionMode, true).DisableIf(() => Model.IsReadOnly == true || !Model.IsAdd)
                @Html.HiddenFor(m => m.enumTransactionMode)
            </div>
        </div>

        if (Model.IsAdd)
        {
            <div class="row" id="ViewButton">
                <button id="btnView" name="Submit" class="btn btn-default">
                    View
                </button>
            </div>
        }
    ...
    ...
    ...

When the view button is clicked, a grid populates based on the data from the fields above and those fields are disabled as shown below:

  $("#DivDisableForView").prop('disabled', true);

However, when submitting the form, the data from the disabled fields becomes null. How can I prevent this or disable a div without clearing its value? Any assistance would be greatly appreciated.

Answer №1

When using the disabled="true" attribute for HTML elements, they will not be included in form data submission. To still send the data for processing while hiding the div, you can simply use:

$("#DivDisableForView").hide();

UPDATE

If you prefer to display the fields on screen...

If you want the fields to remain visible, one option is to set them as readonly.

Here's an example:

$('#DivDisableForView input').attr('readonly', 'readonly');
//you may also change the color to gray
$('#DivDisableForView input').css("background-color", "#eee");

Fields with a readonly attribute are still submitted in form data.

UPDATE 2

Dealing with select fields:

The following JavaScript code addresses the select field issue:

$('#DivDisableForView input, #DivDisableForView select').attr('readonly', 'readonly');
//you may also change the color to gray
$('#DivDisableForView input, #DivDisableForView select').css("background-color", "#eee"); 
//selects
$('#DivDisableForView select').attr('onfocus', 'this.defaultIndex=this.selectedIndex;');
$('#DivDisableForView select').attr('onchange', 'this.selectedIndex=this.defaultIndex');

Check out this JSFiddle demo: https://jsfiddle.net/ddan/W4Km8/5340/

Hope this information proves useful.

UPDATE 3

Handling radio and checkbox inputs:

$('#DivDisableForView :radio, #DivDisableForView :checkbox').click(function()        {
    return false;
});

Take a look at the updated example on JSFiddle: https://jsfiddle.net/ddan/W4Km8/5341/

Answer №2

Instead of disabling, it is recommended to hide your div.

Here is a simple way to do it:

$("#DivDisableForView").css('display', 'none');

You can also use the following code:

$("#DivDisableForView").hide();

Answer №3

To disable a div, you can either use the .hide() method or set its display property to 'none' with .css('display','none'). If you only want to disable it, you can first retrieve the value of the div and store it in a variable before disabling it.

var content = $("#contentToDisable").val();
$("#contentToDisable").prop('disabled', true);

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 process of uploading files using Ajax?

Can anyone help me with submitting a form using ajax that contains images? I have this code snippet which logs an object called "FormData" in the console, but I'm not sure how to properly use it or retrieve it. Is this the correct approach? $("#form_ ...

Place a div image on top of a form div

Currently, I have a simple form set up with the following HTML code: <div class="card mb-5 card-central-responsive" style="min-height: 579px;"> <div class="card-body"> <form #apkCreationForm="ngForm" class="mt-2" novalidate (ngSubmit ...

AJAX is delivering a unique random hash instead of the expected text

I am in the process of developing a live notification script, and I have encountered an issue. Instead of receiving plain text from the external file, the script is returning a random hash... Here is the function responsible for fetching data from test.ph ...

Sending an Ajax request to the MVC Controller results in a response of "NOT FOUND"

Trying to use AJAX to call a MVC Controller action with certain parameters has been successful in the past within this application. However, for some reason, THIS SPECIFIC ONE is not functioning properly. function deleteDetail(button, tab) { var i ...

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

Limit the maximum column gap on the grid and stop it from expanding further

I'm currently facing an issue with some columns/rows on my website that are keeping content locked in the top left corner, reminiscent of early 00's web design. The site was originally designed for smaller screens like 1024x764, so when viewed on ...

Retrieving Data from a Promise - { AsyncStorage } React-Native

Currently, I am grappling with figuring out how to retrieve the outcome of a promise. My journey led me to delve into the React Native documentation on AsyncStorage available here: https://facebook.github.io/react-native/docs/asyncstorage I decided to uti ...

converting an entire HTML layout into a PDF using JavaScript

I am attempting to convert an HTML design to PDF using the following script: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>. I have designed a table to my liking, here is how it looks in HTML: https://i. ...

The table's width exceeds the appropriate size

Take a look at the code snippet below <%-- Document : index Created on : Feb 7, 2014, 1:03:15 PM --%> <%@page import="java.util.Map"%> <%@page import="java.util.Iterator"%> <%@page import="analyzer.DataHolder"%> <%@p ...

Troubleshooting node modules for browser compatibility

Looking for assistance with running a specific node module in a browser. The module in question is called fury.js. I attempted to use browserify, however, encountered an error stating "ReferenceError: fury is not defined" when trying to utilize it. In th ...

Is it possible to access the span element through its parent div?

Is there a way to access a specific <span> using its parent <div> as demonstrated below: <div> <!--parent div--> <div> <span>...</span> <span>...</span> </div> <div> <span> ...

Combining Components in NextJs Without Using Functional Components

I created a module, then split it into components and now I'm trying to piece it back together. The individual components are functioning correctly. Some components are nested inside the div of another component. I attempted to group them within a d ...

Tracking locations in real time with the AR.js framework

Is it possible to utilize the AR.js web framework for creating an Augmented Reality web app that helps users navigate from their current location to a specific destination with coordinates (lat, long)? I am looking to have it compatible with Chrome/Safari ...

Within the mobile view, a button with accompanying description will be discreetly concealed

Working on an ASP.NET Core MVC project, with a FAQ section in the view displayed as follows: <div class="container"> <div class="row "> <div class="col-xl-2 mx-auto d-none d-sm-block"> ...

Verification of user input field

For this mini deposit app, I needed to implement validation for the input field to check for three different conditions: no blank entries, only numerical values, and no negative numbers. Despite having the functionality, my attempts at implementing validat ...

The functionality of triggers is not applicable to content that is dynamically loaded through ajax requests

I encountered a problem recently that required me to rewrite some functions. The original code looked like this: $('#type_of').on('change', function () { However, due to issues with manipulating the DOM and loading content via ajax, I ...

Vue JS: dynamic reactive structure

As I delved into understanding the basics of reactivity and its syntax, I encountered an interesting problem. Take a look at this code snippet: const app = Vue.createApp({ data: dataFunction, methods: {method1: methodImpl} }) var dataObj = { tit ...

The server is unable to process the request with parameters for the specified URL

I've been encountering an error every time I try to post something. articlesRouter.post('articles/:target', async (req, res) => { const target = req.params.target.replaceAll("_", " ") const article = await Arti ...

Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs. The data is successfully passed to the template component, but it shows up as undefined in the controller! See below for my code snippets. The controller angular.module(&a ...

What is the best way to implement a side navigation bar with 100 tabs using Angular 4?

I am new to learning AngularJS and could use some guidance. Currently, I am working on an Angular 4 SPA project that consists of a sidebar with 100 tabs, each containing different content. Here is an image of the sidebar. I have tried a simple approach by ...