$('#name').val() does not work - javascript

I don't understand. I even tried to copy my other webpage's code for the getting of an input's value, and it perfectly works on that page, while here, it still doesn't work. the code for the input field is this:
<input type="text" placeholder="name" name="name" id="name" size="10" style="bottom:570px;left:964px;position: relative">
while for the button,
<button type="button" style="bottom:600px;left:1100px;position: relative" id="addbutt" onclick="addu()">Add Button</button>
I am not sure though if it has something to do with the order, because the button was written before the input field. But I tried to rearrange it, and I still get the same result.
the javascript code is:
alert("helloooooooooooooooooooooooooooooooooo tang---");
var nem = $('#name').val();
alert(nem);
when I press the button, only the alert helloooooooooooooooooooooooooooooooooo tang--- shows up, but the other alert does not. I even tried to remove the first alert, and it still does not show. what seems to be the problem?

Add this code or your lib:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

It is working. Check whether you have included jQuery or not.
Working codepen is here
function addu(){
alert("helloooooooooooooooooooooooooooooooooo tang---");
//var nem = $('#name').val();
var nem=document.getElementById('name').value
alert(nem);
}
this code doesn't require you to include jQuery. If you want your code to run than include jQuery.
JavaScript is faster than using jQuery. See this jsperf
and run test yourself and compare.
Javascript var $el = document.getElementById('hello') can run 27,091,679 ops/sec while jQuery one var $el = $('#hello'); will run only 1,430,757 ops/sec
So using jQuery is 95% slower than using JavaScript.

Related

Why does JQuery .val() method sometimes return undefined when code is valid? [duplicate]

This question already has answers here:
val() vs. text() for textarea
(2 answers)
Closed 4 years ago.
Not a duplicate question; so please consider the content closely before presumption.
I've been using JQuery for years and have never seen this type of behavior before. Consider the following:
<html>
<div class="order-form-group">
<label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
<textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
</div>
<div class="order-form-group">
<label class="order-form-label" for="guestReason">Reason:</label>
<textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
</div>
<div class="button-container">
<input class="order-form-submit" type="submit" value="Submit">
</div>
</html>
I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as
having the incorrect selector, having more than 1 id on the page and etc.
<script>
var specInstr = $("#guestSpecialInstructions").val();
var guestReason = $("#guestReason").val();
</script>
I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.
The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.
After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:
<script>
var specInstr = $("#guestSpecialInstructions")[0].value;
var guestReason = $("#guestReason")[0].value;
</script>
Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.
Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.
If I need to change the wording of the title, let me know.
You can only use text() on a <textarea> if it is pre-populated and to return the original content
Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content
Always use val() to get and set
var $txt = $('textarea')
console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())
$txt.val( 'Some new content')
console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
Original text
</textarea>

Script is not running when added dynamically

{include file="head.tpl" title="Combate"}
{include file="navBar.tpl" dir=$dir}
<table id="CombatLister">
</table>
Nombre: <input type="text" id="nombrePJ">
AC <input type="number" id="ACPJ">
Iniciativa <input type="number" id="Init">
<button id="aƱadirParty" onclick="addPJButt()">AƱadir</button>
<script>
function addPJButt(){
var name=document.getElementById("nombrePJ").value;
var ac=document.getElementById("ACPJ").value;
var iniciativa=parseInt(document.getElementById("Init").value);
addPJ(name,ac,iniciativa);
}
function addPJ(nombre,ac,init){
var table=document.getElementById("CombatLister");
var row=table.insertRow(0);
var cellNombre=row.insertCell(0);
var cellInit=row.insertCell(1);
var cellAc=row.insertCell(2);
cellNombre.innerHTML=nombre;
cellInit.innerHtml=init;
cellAc.innerHtml=ac;
}
</script>
<script>
{$x=0}
{foreach $party as $pj}
addPJ({$pj.nombre},{$pj.ac},{$pj.init})
{/foreach}
</script>
I have a smarty template that using an array from another page, adds it to the "CombatLister" table. however, for some reason, the addPJ() Script does not run. Im just learning the ropes of Javascript, so maybe im skipping something, but so far, i've got no answers on why it does not work.
I tried to check if the addPJ() script was wrong, using the addPJButt(), but the script is working: When i put data on the input types up there, they add the name correctly.
I dont think its a problem of Smarty. checking the source code of the page its similar, writting this where i call $pj:
<script>
addPJ(Galahad,14,5);
</script>
PS: As an extra problem, but not so important, on the insertCell methods of addPJ only the first cell is added.
addPJ(Galahad,14,5); is looking for an undefined variable Galahad.
you need to quote it so it gets printed as javascript string
Try
addPJ('{$pj.nombre}',{$pj.ac},{$pj.init})
Note: I haven't worked with smarty in years and assume the quotes will be literals

vbscript - displaying a message box when an OnClick event fires

I feel a bit silly asking this question, since most of the questions people ask on here are way beyond my level as a programmer, but at least I know I'm in good hands as far as asking goes. I used to know how to make simple vbscript and javascript programs, but I'm a bit rusty. I'm trying to refresh myself, and despite repeated google/other searches, can't recall how to make it so that when a button is clicked, a msgbox appears. Also, I'd like to know how to modify the .value attribute of a textbox. I'm attempting this in vbscript for now, but I'll try javascript if anyone knows a way to do it in that instead. My ultimate goal is a text based type game where you can click buttons labeled, "north,south,west,east", and make it like an rpg. The textbox would display the current room description.
Here's the code I have so far, which isn't displaying the msgbox.
<html>
<title>Explor-o-Rama!</title>
<body>
<form name = frmMain>
<textarea name = "txtDisp" rows = "10" cols = "50"></textarea><br>
<input type = "button" name = cmdTest value = "test">
</form>
<script language = "vbscript">
sub cmdTest_OnClick
msgbox "test"
end sub
<script>
</body>
</html>
You have:
msgbox "test"
The correct command is:
MsgBox("test")
OR
X=MsgBox("test")
This SHOULD DO IT.
also, <html><body><script language=vbscript>msgbox "" </script></body></html> not works.
but this code works OK:
<html><body><script>alert('Test');</script></body></html>
<html>
<body>
<script>
function test()
{
alert('Test');
}
</script>
<input type = 'button'; onclick='test()'>
</body>
</html>
Probably, it's a IE internal bug.

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

Is it possible to duplicate the native behavior of JavaScript's prompt()?

I'm rolling my own version of prompt() for aesthetic purposes; it's come along quite nicely as far as visuals go, but I have run into a slight hitch: the native version of the function causes code execution to cease completely until the prompt has been dealt with.
This is positively lovely and it's why the below works the way it does:
<script>
var c = prompt('Name?', '');
alert(c); // displays whatever the user entered
</script>
With my method, however, things do not go as smoothly. I am using a dialog, an input box, and an OK button to gather the data from the user; to my knowledge, data collection works perfectly; that is, I know for sure that after the user presses the OK button, I have access to the data they just put into the prompt.
I cannot, however, find a way to get my version to work as the native one does. My question, then, is this: is it at all possible to tell JavaScript to halt executing until you've told it to resume?
Thanks in advance for any and all assistance.
No, it is not possible to duplicate this behavior. The way to achieve the same effect is to use a callback in your code, so you can do something like:
myPrompt('Hello, mate, whats yer name?', function(answer) {
alert(answer);
});
EDIT: Based on your code, why not do this?
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(prompt, callback) {
$('prompt').style.display = '';
$('q').value = '';
$('ok').onclick = function() {
callback($('q').value);
}
}
_prompt('Name?', function(answer) {
alert(answer);
});
</script>
</body>
If you change alert(answer); to say... gAnswer = answer; (notice no var declaration) you would be creating a global variable named gAnswer that you could access anywhere else in the javascript code, assuming the prompt was already answered. If you're concerned of global variables polluting your space you could wrap it all in a closure, but it should be fine otherwise.
#Paolo:
This is the code I am currently working with:
<body>
<div id="prompt" style="display: none;">
<input type="text" id="q" /> <input type="button" value="OK" id="ok" />
</div>
<script>
$ = function(i) {return document.getElementById(i);}
_prompt = function(q, e)
{
$('prompt').style.display = '';
$('q').value = '';
$('ok').setAttribute('onclick', e + ' $("prompt").style.display = "none";');
}
var c; _prompt('Name?', 'c = $("q").value;');
alert(c);
</script>
</body>
Now, as would be expected, that alert() fires as soon as the page is loaded, which is most definitely not what I want; ideally, I'd like for the rest of the code to wait for the prompt to get handled, but I'm strongly doubting this is possible outside of the native implementation. Reckon I'll just have to settle for designing my algorithm so that the prompt gets used immediately?

Categories