0

In an attempt to abbreviate code and perhaps make it run a touch faster, I tried this code for getting the value if an input whose name is key is a radio button:

var elem = $(':input[name^="'+key+'"]');
currVal = (elem.prop('type') == 'radio' ? 
  ':input[name^="'+key+'"]:checked').val() : elem.val());

I've tried various ways to abbreviate the instruction

':input[name^="'+key+'"]:checked')

but nothing works.

Is there a way of using elem in this situation?

4
  • What exactly is the desired result? You are selecting things to get what? Commented Jun 13, 2019 at 18:10
  • Not sure having a leading : is correct. That's normally used for pseudo attributes. Try removing it Commented Jun 13, 2019 at 18:11
  • @freefaller :input will match multiple things, such as input, select, textarea Commented Jun 13, 2019 at 18:12
  • @Taplar everyday's a school day! Commented Jun 13, 2019 at 18:13

3 Answers 3

2

Well you already have the element with

var elem = $(':input[name^="'+key+'"]');

So instead of looking up all the elements again, use filter

elem.filter(":checked").val()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That's exactly what I was hoping for.
0

My guess is $("input[name='+key+'][type='radio']:checked").val(); should work for you.

Comments

0

Here's a working fiddle using your code: https://jsfiddle.net/wvbxmgpe/

var elem = $(':input[name^="'+key+'"]'),
currVal = elem.prop('type') == 'radio'
  ? $(':input[name^="'+key+'"]:checked').val()
  : elem.val();

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.