0

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.

3 Answers 3

4

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 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this has worked. it is a big difference between using: var bcol = document.getElementById("bcols").value; and document.getElementById('div1').style.backgroundColor=bcol; but still learning JQ.
2

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

Comments

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

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.