Reputation: 29
So, here is my problem: I have a div:
<div id="square"></div>
And an input:
<input type="number" id="width">
And this is my script:
var x;
$("button").click(function(){
x = $("#width").val();
$("#square").attr("width", x);
}
What i want to do is when the user enters a number inside the input, and then clicks a button, div's width is set to the number inside input. Thanks! P.S. Sorry for bad English.
Upvotes: 2
Views: 1681
Reputation: 687
we can set an element width in jQuery in 2 ways
1. using css method i.e jQelement.css("width",'100px');
2. using width method i.e jQelement.width(100);
Upvotes: 0
Reputation: 4463
Check out this fiddle.
You need to use .css()
to change the style of any element.
Here is the snippet.
var x;
$("button").click(function() {
x = $("#width").val();
$("#square").css("width", x);
});
#square {
position: absolute;
width: 20px;
height: 20px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="square"></div>
<br>
<br>
<input type="number" id="width" />
<button>Click</button>
Upvotes: 1
Reputation: 4828
YOu can try this code
var x;
$("#button").click(function(){
x = $("#width").val();
$("#square").css("width", x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="square" style="border:1px solid;width:10px;;height:10px"></div>
<input type="number" id="width">
<button type="button" id="button">Click</button>
Upvotes: 2
Reputation: 5466
hi you need to set width in css. So try:
var x;
$("button").click(function(){
x = $("#width").val();
$("#square").css("width", x);
}
Upvotes: 0