Jquery val () or getting text field value by id

I want to set my variable to the value of my num1 text box. What am I doing wrong with this?

aa = $("#num1").val(); alert(aa); //var bb = document.getElementById('num1').value; //alert(bb); 

here is the whole code http://jsfiddle.net/EmRLE/

 <!DOCTYPE html> <html> <head> <style> #box { font-family:Arial; float:right; background: blue; color: orange; width:200px; height: 200px; padding:10px; margin: 10px; border : 10px solid gray; } </style> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(document).ready(function(){ $("#a").click(function(){ alert("Background color = " + $("div").css("background-color") + " " + "\nfont is " + $("div").css("font-family") + " \nFloat property is " + $("div").css("float") + " " + " \ncolor of the text is " + $("div").css("color") + " " + "\nthe width is " + $("div").css("width") + " " + + $("div").css("width") + " " + " \nthe height is " + $("div").css("height") + " " + "\nthe margin is " + $("div").css("margin") + " " + "\n the padding is " + $("div").css("padding") + "."); }); $("#b").click(function(){ aa = $("#num1").val(); alert(aa); //var bb = document.getElementById('num1').value; //alert(bb); if ( isNaN(aa) || aa < 0 || aa > 500) { alert("please enter number between 0 and 500"); } else { $("div").css("height",aa); } }); $("#c").click(function(){ var bb = $("num2").val(); alert(bb); if ( !/^[A-Za-z]+$/.test(bb) ) { alert("please enter a color that is a letter"); } else { $("div").css("background-color",bb); } }); }); </script> </head> <body> <div id="box">My Div</div> <button id = "a" >Display CSS Values </button><br><br><br> <button id = "b" >Enter height value: </button><input type="text" name="num1" /> <br><br><br> <button id = "c" >Enter background color: </button><input type="text" name="num2" /> </body> </html> 
+4
source share
3 answers

$ ("# num1") searches for the field with identifier num1. Your field is defined with the name num1:

 <input type="text" name="num1" /> 

Try this instead:

 <input type="text" id="num1" name="num1" /> 
+7
source

As an alternative, I will answer SteveP, if for some reason you do not want "num1" as an identifier, you can select the name attribute with $('[name="num1"]') . Keep in mind that pull ALL items with name="num1" .

+3
source

Since with this selector $("#num1").val(); you search for an element with id num1 , but your input field has a name attribute.

Try changing it:

 <input type="text" id="num1" name="num1" /> 

Here is a working fiddle: http://jsfiddle.net/IrvinDominin/EmRLE/2/ (I set jQuery in the no-wrap header to make it work)

+1
source

All Articles