Deactivating form elements using jQuery

I am attempting to utilize jQuery in order to disable a form element once a checkbox is clicked, but for some reason it's not working properly. Can someone help me identify the issue?

$('name="globallyAddTime"').click(function() {
    if ($(this).attr('checked')) {
       $('name="addedQuantity[]"').attr('disabled', true);
    } else {
        $('name="addedQuantity[]"').removeAttr('disabled');
    }
});

For those who want to check out the jsfiddle, here is the link:

http://jsfiddle.net/pocockn/bwmv7/4/

Answer №1

To create an attribute selector, use the format [attr=value]

$('[name="globallyAddTime"]').change(function() {
if ($(this).prop('checked')) {
       $('[name="addedQuantity[]"]').attr('disabled', true);
    } else {
        $('[name="addedQuantity[]"]').removeAttr('disabled');
    }
});

Check out the Fiddle Demo for reference.

You can simplify the code as shown below:

$('[name="globallyAddTime"]').change(function() {
     $('[name="addedQuantity[]"]').prop('disabled', this.checked);
});

View the simplified version in the Fiddle Demo here.

Answer №2

Give this a shot (utilize prop instead of attr)

$('name="globallyAddTime"').click(function() {
if ($(this).prop('checked')) {
       $('[name="addedQuantity[]"]').attr('disabled', true);
    } else {
        $('[name="addedQuantity[]"]').removeAttr('disabled');
    }
});

Using attr does not provide the current state of the checkbox.

Additionally, there is an error in the name selector. It should be [name="addedQuantity[]"]

Answer №3

To choose a specific attribute, make sure to utilize the square brackets []:

$('[name="globallyAddTime"]').click(function() {
    if ($(this).attr('checked')) {
        $('[name="addedQuantity[]"]').attr('disabled', true);
    } else {
        $('[name="addedQuantity[]"]').removeAttr('disabled');
    }
});

Answer №4

Follow these instructions:

$('[name="globallyAddTime"]').on('click', function() {
     if ($(this).prop('checked')) {
         $('#addedQuantiy_1').attr('disabled', true);
     } else {
         $('#addedQuantiy_1').removeAttr('disabled');
     }
 });

View the working example here

Answer №5

Got it!

<div id="addIngredient">
                        <p>
                            <input type="text" id="ingredient_1" name="ingredient[]" value="" placeholder="Ingredient" />
                            <input type="text" id="quantity_1" name="quantity[]" value="" placeholder="Quantity" />
                            <select id="selectQuantity_1" name="quantityType[]">
                                <option value="grams">Grams</option>
                                <option value="ounces">Ounces</option>
                                <option value="Pounds">Pounds</option>
                            </select>
                            <input type="text" id="alternative_1" name="alternative[]" value="" placeholder="Alternative Ingredient" />
                            <input type="text" id="addedQuantiy_1" name="addedQuantity" value="" placeholder="Add Quantity per Person" />

                            <a href="#" id="addNewIngredient">Include New Ingredient</a>
                        </p>
                    </div>


<h2>Added Time</h2>
                     <input type="checkbox" name="globallyAddTime" id="global" value="Global" />
                    <label>Adjust Quantities Based on Helpings</label>
                </div>



<script type="text/javascript" src="scripts/jquery-1.11.0.min.js"></script>
<script>
$('#global').change(function() {
        if($(this).is(":checked")) {
           $('input[name=addedQuantity]').attr('disabled', true);
    } else {
        inputs.removeAttr('disabled');
    }
    });
</script>

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 transfer a JavaScript object to a VueJS component?

Even though it may seem like a basic question, I'm having trouble figuring out how to accomplish this in VueJS Here's the code I have in HTML: <script> var config = {'cols':4,'color':'red'} </script> ...

Update the class name of an element depending on the URL

Hey there! I'm working on customizing the style of some elements (specifically tds within a table) based on the current URL. Here are the pages I'm targeting: http:\\domain\site\welcome.html http:\\domain\site& ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

Express API developed with the use of Node.js

In the process of creating a weather application API using Express in Node.js, I have decided not to utilize a database since no data needs to be saved. The application enables users to input a city name, and the weather information is fetched directly fro ...

Transferring data through Ajax, Jquery, and PHP: A seamless process

My goal is to develop an attendance button that adds +1 to the total number of people attending when clicked by the user. I am looking for a way to achieve this without having to refresh the page. Ideally, I would like to connect it to a database to upda ...

If checkboxes are found within the table's rows and cells, add the parent row class if none of the

I am attempting to implement a small script within my table under the following conditions: The table contains a checkbox within each tr td, and I want my jQuery script to be applied only if the selector identifies a tr where all td checkboxes are unchecke ...

Unable to stop page refresh following form submission or file upload

Is it possible to upload a photo with Ajax to Express and have the response generate desired HTML? Whenever I submit the form, it redirects me and displays the picture data as an object. Here's the Express code: const storage = multer.diskStorage({ ...

Even though setState is supposed to update the state and trigger a render, it's not showing up in the view for some

My React app consists of a simple word/definition feature. There is an edit box that appears for users to change the definition when they click on "edit". Even though I call getGlossary() to update the new definition in the state, I can see the changes in ...

Not completing the task until the job is finished

My goal is to retrieve the contents of each file in an array using AJAX, analyze them, and then store the results in a new array. But for some reason, my JavaScript code is not properly executing the AJAX calls. I have attempted to use JQuery's when f ...

Ways to choose tags that do not contain a particular tag within them

I am trying to utilize querySelectorAll to select all i elements that do not contain a font tag. The selector I attempted is: document.querySelectorAll('i > *:not(font)') <i> <font color="008000">Here goes some text</fon ...

Determine the number of items (within an array) that were created within the past few days, weeks, and months leading up to the 'current time'

Having an array filled with objects containing timestamps: Here is a glimpse of the data: const dataList = [ { _id: "602102db3acc4515d4b2f687", createdDt: "2021-02-08T09:22:35.000Z", }, { _id: "6021024da706a260d89 ...

"Modifying the height of an SVG <g> element: A step-by

Is there a way to adjust the height of a g element? Trying to set the height using {params} but it's not responding I made some changes in the comments because the svg is quite large (Scene.js) {/* Transformation */} <g transform="trans ...

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it. Here's the current code snippet: <div class="position-sticky bottom-0" ...

JavaScript tri-state toggling

After devising 2 buttons, each intended to toggle a heading or paragraph, I encountered a slight issue. When using the 'Toggle Para' button, the switch occurs between 2 paragraphs upon 2 clicks. However, on the third click, I desire for both para ...

The Express application seems to load forever after a certain period of time

I encountered a peculiar problem with my express application. It was deployed on the server and functioning properly, but after a few hours, when I tried to access the website again, it kept loading indefinitely. Below is my app.js code: const express = r ...

The REST API from React encountered a Cors-related error in the cloudinary response during the upload process

I am attempting to upload an image through a direct REST API call using the following code snippet. The code works perfectly fine from my personal computer (localhost:3000). const cloudinaryUrl = 'https://api.cloudinary.com/v1_1/{my_id}/image/upload&a ...

The children component is not recognizing the function being passed through this.props.children, resulting in an

Looking for a solution that involves passing a function to this.props.children? Check out the code snippet below: updateBarTitle(barTItle){ this.setState({barTItle}); } render(){ const children = React.Children.map(this.props.children, function (chi ...

Enhance your WordPress menu with additional attributes

Currently, I am implementing a lightweight lightbox script on my WordPress website. My goal is to have one of the main navigation buttons open a Vimeo link in the lightbox. According to the lightbox documentation, I need to "Add the 'data-lity' a ...

What could be causing the vertical alignment issue of this logo in its parent container?

I am having an issue with the vertical centering of the logo element within the <header> container on this page. It seems to be more pronounced on mobile devices compared to desktop. However, the second element (#forum-link) is aligning correctly. W ...