2

I am trying to create a function to update CSS based on user input and I have it working except for the CSS property parameter.

$(document).ready(function() {
  $('input').blur(function() {
    var inputName = $(this).attr("name");
    updateCSS(inputName, 'button-style-one', 'background-color');
  })

  // Function to update CSS
  function updateCSS(pInputNameAttribute, pElementClass, pCssProperty) {
    var inputName = '[name=' + pInputNameAttribute + ']',
      elementClass = '.' + pElementClass,
      inputValue = $(inputName).val();

    $(elementClass).css({
      pCssProperty: inputValue
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="submit.php" method="post" id="buttonSettings">
  <input type="text" name="button_background_color" placeholder="Background Color">
</form>

<a href="#" class="button-style-one">Button</a>

This works if I replace pCssProperty: inputValue with 'background-color': inputValue, but I need the CSS property to be a parameter of the function - how can I get this to work property with a variable? JSFiddle: https://jsfiddle.net/frafgdnq/10/

1
  • When you define an object, like the one that jQuery's .css() method takes as an argument, you're allowed to have property names without quotes. Variables normally won't be interpolated on the left side of the colon. So, your code was trying to set a CSS property that was literally named pCssProperty. Commented Mar 26, 2018 at 23:54

1 Answer 1

4

You can access the contents of pCssProperty for your css object by creating the object first and then assigning the key:

var cssObj = {};
cssObj[pCssProperty] = inputValue;
$(elementClass).css(cssObj);

...or use this ES6 shorthand to do the same thing:

$(elementClass).css({[pCssProperty]: inputValue})

$(document).ready(function() {
  $('input').blur(function() {
    var inputName = $(this).attr("name");
    updateCSS(inputName, 'button-style-one', 'background-color');
  })

  // Function to update CSS
  function updateCSS(pInputNameAttribute, pElementClass, pCssProperty) {
    var inputName = '[name=' + pInputNameAttribute + ']',
      elementClass = '.' + pElementClass,
      inputValue = $(inputName).val();

    $(elementClass).css({
      [pCssProperty]: inputValue
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="submit.php" method="post" id="buttonSettings">
  <input type="text" name="button_background_color" placeholder="Background Color">
</form>

<a href="#" class="button-style-one">Button</a>

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

1 Comment

+1 I knew what was happening, but I didn't know you could put a variable in square brackets to get the value in an object definition.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.