0

i have input value = 99.

<input type="text" id="num" value="99" />

so i want use that number for my alert bootstrap. that number is not showing in my alert, it say "undefined"

my javascript :

<script>
var x = document.getElementById("num").value;
    $('#alert').html("<div class='alert alert-danger'>ur number : "+window["x"]+"</div>");
</script>

i have tried using window. but it say "undefined".

4
  • Just use x... Commented Apr 6, 2017 at 6:17
  • Be consistent and also use $("#num").val() and execute AFTER load: $(function() { $('#alert').html("<div class='alert alert-danger'>Your number : "+$("#num").val()+"</div>"); }); Commented Apr 6, 2017 at 6:17
  • @mplungjan, Whats wrong with document.getElementById("num").value? Just because OP tagged jQuery Commented Apr 6, 2017 at 6:18
  • 1
    For consistency's sake - because he on next line uses the jQuery. It makes the code harder to read. If I use jQuery, I only ever use stuff like this.id when I do not use jQuery Commented Apr 6, 2017 at 6:20

1 Answer 1

1

Use jQuery .val() method to be consistent.

<script>
var x = $("#num").val();
$('#alert').html("<div class='alert alert-danger'>ur number : "+ x +"</div>");
</script>

If you want to set value on page load use jQuery .ready method

<script>
$(document).ready(function(){
  var x = $("#num").val();
  $('#alert').html("<div class='alert alert-danger'>ur number : "+ x +"</div>");
});
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

it work sir using $("#num").val(); but not work if im using document.getElementById("num").val(); it will work too using `document.getElementById("num").value; $('#alert').html("<div class='alert alert-danger'>ur number : "+ x +"</div>");
Because .val() is for jquery and document.getElementById("num") is pure javascript

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.