0

I am trying to use jQuery / javascript to remove a class from a named input element if a checkbox is ticked.

I have several checkboxes, each with a accompanying hidden (on page load) text input field.

The checkbox and text input field are named "question_X" and "question_X_description" respectively. (where X is a number 0 to 100, say)

As such I'm trying to define a variable in my code that is defined as "this element's name"+"_description", and then use that to define the suitable element to remove the class from.

Here is what I've tried:

$('input:checkbox').change(function(){

var x = $(this).attr('name').'_description';

if($(this).is(":checked")) {
    $('input[name="x"]').removeClass("hidden");
} else {
     $('input[name="x"]').addClass("hidden");
}
});

However, nothing happens when the any checkbox is checked. Am I referencing my variable correctly?

3 Answers 3

3

Use your console, It will have error messages.

First issue

var x = $(this).attr('name').'_description';
                           ^^^

That is not how you build a string in JavaScript. JavaScript does not use . to join strings. It uses +

var x = $(this).attr('name') + '_description';

Second issue

$('input[name="x"]').

You are not looking for the string you built, you are looking for an element with the name x

Needs to be

$('input[name="' + x + '"]').
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks kind viking man: I am not good at javascript :) Thanks for teaching me how to reference my variables properly and concatenate! I'll accept once the time limit runs down.
0
$('input[name="x"]').removeClass("hidden");

Will be looking for:

<input name="x" />

Try

$(name="'+x+'").removeClass("hidden");

Comments

0

Use document.getElementById('element_name')

Example of HTML element: <input type="text" id="element_name">

Comments

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.