Mattlinux1
Mattlinux1

Reputation: 807

How do you modify the CSS using an input box in JQuery

This is the code i am trying to get to work, i could not work out why JQ will not pick up the #cols1 var from the inputbox.

This is a basic example of the code i am using.

<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-2.1.0.min.js'>
</script>
<script type='text/javascript'>

function changeCon()
{
var cols1 = $('#col1').value;
$('#div1').html('Random text');
$('#div1').css({ backgroundColor: "#cols1" });
}

function startup()
{
$('#bt1').click(changeCon);
}
$(startup);

</script>
</head>
<body>
<input id='col1' type='text' /> <br />
<div id="div1">text div.</div>
<input type="button" id="bt1" value="Submit" />
</body>
</html>

If anyone know's why, it would be great cheers.

Upvotes: 0

Views: 53

Answers (3)

ddlab
ddlab

Reputation: 930

  1. Quentin is right.
  2. JS is not PHP, you have to use $('#div1').css({ backgroundColor: '#'+cols1 }); instead of "#cols1".

Upvotes: 1

mildog8
mildog8

Reputation: 2154

Do it like this

var cols1 = $('#col1').val();
$('#div1').html('Random text');
$('#div1').css({ backgroundColor: "#" + cols1 });

or

var cols1 = $('#col1')[0].value;
$('#div1').html('Random text');
$('#div1').css({ backgroundColor: "#" + cols1 });

Upvotes: 4

Quentin
Quentin

Reputation: 943579

jQuery objects do not have a value property (DOM elements representing HTML form controls do). jQuery objects have a val() method.

Upvotes: 2

Related Questions