0

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Remove switch case statements and use only one line this

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

1 Comment

this indeed would work, however I do need the switches to check the values. In addition I have to use a variable for all inputs, as I'm using them multiple times in the code. Thanks for answering!
0

Try this:

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

Somewhere later in your code:

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

Hope this helps.

1 Comment

I don't want to create a new variable for each new value...this was my problem in the first place. Thanks for answering nevertheless!

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.