NicoF
NicoF

Reputation: 135

How to change an attribute of a variable in Jquery?

I'm struggeling with something basic and I can't seem to work it out.

The following works perfectly:

switch (url_param) {
    case '80':
        $('input[name=power][value=80]').prop('checked', true);
        break;
    case '90':
        $('input[name=power][value=90]').prop('checked', true);
        break;
    case '99':
        $('input[name=power][value=99]').prop('checked', true);
        break;
}

However, I have to interact with many different inputs on the page so I would like to store them into variables first, for example

$input_power = $('input[name=power]');

How can I achieve the same result, using a variable?

Upvotes: 0

Views: 40

Answers (3)

Ansh Takalkar
Ansh Takalkar

Reputation: 119

Remove switch case statements and use only one line this

$('input[name=power][value='+ url_param +']').prop('checked', true);

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use filter() method to filter out the matched element.

Reduce the set of matched elements to those that match the selector or pass the function's test.

var $input_power = $('input[name=power]');
switch (url_param) {
    case '80':
    case '90':
    case '99':
        $input_power.filter(function(){
            return parseInt(this.value, 10) == parseInt(url_param, 10);
        }).prop('checked', true);
        break;
}

In the above example I have improved the code and used parseInt(str, radix) for integer.

Upvotes: 2

Furhan S.
Furhan S.

Reputation: 1524

Try this:

var myInput = $('input[name=power][value=80]');

Somewhere later in your code:

$(myInput).prop('checked', true);

Hope this helps.

Upvotes: 0

Related Questions