0

I've been trying couple of approaches on this problem. Basically I have to modify the content of several dropdowns on the exact same way. So I though I could use an each or a while to be more DRY but I dont have that much experience in coffeeScript.

Here is 'working' undry code to refactor:

$('#someId').val('someVal')
$('#someOtherId').val('someVal')

Here is my first attempt:

arr = ['someId', 'someOtherId']
$.each arr, (i, el) =>
  $('#'+el).val('someVal')

Here is my second attempt:

arr = ['someId', 'someOtherId']
length = arr.length
counter = 0
while counter < length
 $('#' + arr[counter]).val('someVal')
 counter ++

For some reasons, I have been trying multiple variations on each approch, I can assert that I can console.log the selector and it returns the correct value, but when it comes to change the value, the code just seems not to work as expected.

Any help is appreciated.

2
  • 1
    If you have access to the HTML you could add a class to each element and use a single call: $('.foo').val('someval'); Commented Sep 26, 2016 at 10:43
  • Definitly smart. I will go with this solution. Thanks a lot Rory Commented Sep 26, 2016 at 12:02

2 Answers 2

1

Try:

arr = ['someId', 'someOtherId']
for value, index in arr
    $("##{value}").val('someVal')

Or if you don't care about index just:

arr = ['someId', 'someOtherId']
for value in arr
    $("##{value}").val('someVal')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your advice, but I'm getting a Uncaught Error: Syntax error, unrecognized expression: ##{value} here.
My fault, should be "##{value}" instead of '##{value}'
Worked! Thanks a lot for this interpolation I didn't know it was possible that way.
0

I'm not a coffee script user,. But looking at your code it looks like your using jquery to iterate an array. I assume you mean to use Array.forEach instead.. eg.

arr = ['someId', 'someOtherId']
arr.forEach (el) =>
    $('#'+el).val('someVal')

3 Comments

Thanks for your help, I just gave it a try and it doesn't work aswell. I'll keep you updated as soon as I find a solution. So far I'm going with Rory's solution.
I assume you have 2 html elements of type INPUT? + are you also running this code on DomReady?..
I do have two HTML elements of type <select>. This code is wrapped into a function called by another function on backbone + Marionette well known pattern 'onShow'.

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.