2

This question is related to How to pass multiple variables from function to function

So in the link above you might have seen how you can pass a variable(or mutiple) from function to function, but what if you want to pass it from a regular js function into the jquery .attr() value?

That might sound strange as a statement, that's why I'll include an example.

$(function() {

  function definingVars() {
    var Value = "Sucess with the value";
    var Id = successWithTheId;
    var Class = sucessWithTheClass;
    return [Value, Id, Class];
  }

  $("input").attr({
    //  var df = definingVars();  Incorrect syntax!!!
    value: df.Value,
    id: df.Id,
    class: df.Class
  })

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="noSucessWithTheId" class="noSucessWithTheClass" value="No sucess with the value">

But as you can see the line that should aloud the attr jquery function to capture the values from definingVars() is clearly commented as that is not the correct syntax.

But how can you still pass on those variables?

That is my question

Community
  • 1
  • 1
Julian Avar
  • 476
  • 1
  • 5
  • 24

2 Answers2

4

What you are trying to do is to pass multiple properties to .attr(), for which we uses an object with key/value pair.

So what you can do is to return an object from definingVars and pass the value returned by definingVars as the argument to attr() like

$(function() {

  function definingVars() {
    var Value = "Sucess with the value";
    var Id = successWithTheId;
    var Class = sucessWithTheClass;
    
    return {
      value: Value,
      id: Id,
      class: Class
    };
  }

  $("input").attr(definingVars())

});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

If you wanna stick with the current structure of definingVars(), then Just call directly the function if you wanted :

$("input").attr({
 value: definingVars()[0],
 id: definingVars()[1],
 class: definingVars()[2]
})

DEMO

Norlihazmey Ghazali
  • 9,000
  • 1
  • 23
  • 40