Hi,
Below is a working code.

1. if($('input[name="test"]').is(":checked"))
   2. {
   3. // my other code
   4. }

I want to remove "test" and put a variable there instead

I tried this way but it does not seem to work. I am not sure where I am going wrong. Any help will be highly appreciated.

1. newData="test";
   2. if($('input[name=$(newData)]').is(":checked"))
   3. {
   4. // my other code
   5. }

Dani AI

Generated

Short note (context: asked how to put a variable into a selector and provided the working approach).

Why the first attempt failed: jQuery selectors are plain strings passed to the selector engine. Putting an expression literally inside that string does not make JavaScript substitute the variable value. The selector must be constructed so the variable value becomes part of the selector string at runtime.

Practical tips and alternatives:

  • For checking checked state prefer reading the boolean property (use prop('checked') in modern jQuery) rather than parsing attributes or string-matching; it returns a true/false directly. See the jQuery prop() docs for details.
  • If performance matters or you only need a single element, native DOM methods (for example document.getElementsByName or querySelector) are often faster than repeated jQuery lookups.
  • Cache the jQuery object when you reuse the same selector instead of querying the DOM repeatedly.
  • Debugging tip: log the final selector string to the console before passing it to jQuery, or paste it into the browser console to verify it matches the expected elements.

Caveats:

  • If the name contains special characters (brackets, spaces, colons, etc.) it must be escaped for the CSS selector. Use CSS.escape() (see MDN) or otherwise escape special chars before building the selector.
  • Be aware of the jQuery version in use: older versions handled checked state differently (use prop on jQuery 1.6+).

Quick checklist: confirm the variable contains the expected value, build/inspect the selector string, escape special characters if needed, then read the checked state via the DOM property or prop('checked').

Recommended Answers

All 3 Replies

newData="test";
if($('input[name="' + newData + '"]').is(":checked"))
{
 // my other code
}

Thanks hielo I cud not figure this out for an entire day. Just to show how weak I am at this.

Glad to help.

Regards,
Hielo

PS: Don't forget to mark the thread as solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.