简体   繁体   中英

Using variables in javascript to reference html elements dynamically

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?

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 + '"]').
$('input[name="x"]').removeClass("hidden");

Will be looking for:

<input name="x" />

Try

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

Use document.getElementById('element_name')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM