1

I have the following 3 actions that essentially check a radio button when a label is clicked. is there a way to write these as one function as opposed to 3 individual ones?

$("input[name='customOrder-qty']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);  
 });

$("input[name='customOrder-price']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);  
 });

$("input[name='customOrder-name']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);  
 });

thank you

2
  • Remember, jQuery selectors are just like CSS selectors.
    – elclanrs
    Commented Jun 5, 2013 at 21:50
  • I would go with Sushanth's answer below. The "starts with" selector that he demonstrates is very useful since all your input name values start with customOrder-
    – cssyphus
    Commented Jun 5, 2013 at 22:22

3 Answers 3

2

A few ways you can do it:

One is to combine your selectors for the event so that you would have

$("input[name='customOrder-qty'], input[name='customOrder-price'], input[name='customOrder-name']").on('click', function() {
    $('#qtyPackage-custom').prop('checked', true);
});

The other is to define the bound code as an actual function, and call the function from each event binding

$("input[name='customOrder-qty']").on('click', doStuff);

$("input[name='customOrder-price']").on('click', doStuff);

$("input[name='customOrder-name']").on('click', doStuff);

function doStuff()
{
    $('#qtyPackage-custom').prop('checked', true);
}

Or you can combine both methods to have the following

$("input[name='customOrder-qty'], input[name='customOrder-price'], input[name='customOrder-name']").on('click', doStuff);

function doStuff()
{
    $('#qtyPackage-custom').prop('checked', true);
}
2

use selectors separated by commas

$("input[name='customOrder-qty'], input[name='customOrder-price'] 
                  ,input[name='customOrder-name'] ").on('click', function() { 
      $('#qtyPackage-custom').prop('checked', true);
});

or better use Attribute contains or starts with selector

$("input[name*='customOrder']").on('click', function() { 
      $('#qtyPackage-custom').prop('checked', true);
});

contains selector - *

starts with - ^

1

Add a common class name to each of the inputs. This makes it a lot easier to scale the logic.

HTML

<input class="myClass" />

JS

$(".myClass").on('click', function() { $('#qtyPackage-custom').prop('checked', true);});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.