2

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.

4 Answers 4

2

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>

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

1 Comment

OMG!!Thank you soo much! Actually, i had the same code as yours, but i made a syntax mistake! Thank you!
1

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>

Comments

0

hi you need to set width in css. So try:

var x;
$("button").click(function(){
    x = $("#width").val();
    $("#square").css("width", x);
}

Comments

0

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);

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.