JQuery val() returning empty - javascript

I'm stuck on what seems like a trivial issue and I'm probably gonna kick myself for missing this..Anyway, my issue is I'm failing to get the value from a text field.
HTML:
<form>
<label for="">Enter Username:</label>
<input id="usernameText" type="text" size="30" />
<input type="button" value="Generate" onclick="generateQuery(); return false;" />
</form>
Javascript:
<script type="text/javascript">
var username = $("#usernameText").val();
function generateQuery(){
alert(username);
}
</script>
I did the following if (jQuery) {.. and made sure JQuery is loaded.
In the alert it displays an empty dialog box.
If I included the $(document).ready(); into my script the function generateQuery does not get called. Any idea why..?
<script type="text/javascript">
$(document).ready(function(){
var username = $("#usernameText").val();
function generateQuery(){
alert(username);
}
});
</script>

Assign your variable within the function.
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
As for your other question, "If I included the $(document).ready(); into my script the function generate does not get called. Any idea why..?"
This happens because of scope. You wrap generateQuery inside an anonymous function when you add a document.ready handler, and therefore it's not visible to your button onclick="generateQuery()" code.

Here it will call while the page is loading.So whenever the page is loading the text box is empty.Try to write within a function.
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
When you write in document.ready it will cal;l while the page is loading.If you need the value of username then call explicitly.

The value is being derived the first time through. So when the page is first loaded.
<script type="text/javascript">
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
</script>

Here you are defining the function you have to call the function in order to get it run use this generateQuery(); line to call your function.

where are you calling the function????
i think you need:
<script type="text/javascript">
$(document).ready(function(){
generateQuery();
});
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
</script>

Related

How to call a javascript function from a textbox when the textbox is not null / some value is passed into the textbox

I have a situation where I have a textbox which will be updated with some value and as soon as the textbox gets its value a javascript function will be called. I have tried something but this not working
if (validSubmission) {
User user = new User();
String StatusMessage=user.executeUserTask("_create_","",userBusinessEmailId,userPassword,cityOfBirth,userFirstName,userLastName,userCompanyName,userCompanyAddress,userPhone,"");
if(StatusMessage.equalsIgnoreCase("OK")) {
response.sendRedirect("login.jsp?retMessage="+"Account created sucessfully");
}
else {
//response.sendRedirect("login.jsp?retMessage="+StatusMessage);
responseMsg = "Invalid Domain Entry";
{%>
Redirect();
<%}
}
}
This is the text box where I am getting the value
<input type="text" id="keyToShowInvalidDomain" name="keyToShowInvalidDomain" value="<%=responseMsg%>" onchange="Redirect()">
This is the function which I am trying to call
<script type="text/javascript">
function Redirect() {
alert($("#keyToShowInvalidDomain").val());
}
</script>
Can anyone help, please?
For input type text onchange event will not work try to use onkeyup or onkeydown
<input type="text" id="keyToShowInvalidDomain" name="keyToShowInvalidDomain" value="<%=responseMsg%>" onkeyup="Redirect()">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function Redirect() {
alert($("#keyToShowInvalidDomain").val());
}
</script>
</head>
<body>
<input type="text" id="keyToShowInvalidDomain" name="keyToShowInvalidDomain" value="<%=responseMsg%>" onchange="Redirect()">
</body>
</html>
You are using selectors based on jQuery so you need to add jQuery library to your page. Please try this.
$(document).ready(function() {
$('#keyToShowInvalidDomain').change(function(){
// Call redirect function
});
}
Above code should work with JQuery.

Why window.onload works in body and not in head tag in javascript?

I have tried to call the function using window.onload but it works only when I place it body tag as below but when I place it in the head tag (commented out) it doesn't work though the function gets called (I have put an alert and checked.)
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
//window.onload = onl();
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<script>
window.onload = onl();
</script>
<div id = "txt">
</div>
</body>
</html>
It doesn't run in the head because the brackets used after the assignment cause the function to immediately be run. That mean it causes an error because the document hasn't loaded yet and so causes the form elements to be undefined.
In the head, if you change
window.onload = onl();
to
window.onload = onl;
Then it will work.
You must pass the handler function to document.load (or window.load), not the return of your function. So use document.onload = onl; instead of document.onload = onl(); (see more here : https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)
So in result :
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
document.onload = onl;
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<div id = "txt">
</div>
</body>
</html>
Regards,
Julien Q.
Edit : Sorry I misread before ;)
When you assign a function like that, you need to be sure not to invoke it. When you put parentheses on the end of a function name, it will be invoked immediately even if it's being assigned to something like the window's load event.
So, you simply have to replace onl() with onl:
window.onload = onl;
As for why it works in the body, it's because the document has pretty much finished loading when it gets to the end of the body.
Assigning onl() to the window's onload property isn't erroneous because you're assigning the return value of onl(), which is undefined, to window.onload.
Also, I'd recommend not using window.onload but document.onload, because document.onload is fired when the DOM is ready, not when the files requested are ready.

innerhtml cannot be chage (keeps resetting)

im trying to change the innerhtml of an element but it keeps reseting back to "ddd" on every click of the button
<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>
<script type="text/javascript">
document.getElementById("submit").onclick = function(){changeit()};
function changeit()
{
pError = document.getElementById("passError");
pError.innerHTML = ("wrong password");
</script>
First you are missing the } on the function and then with the submit you are submitting the form which you have to prevent. You don't need a wrapper function for the changeit function you may pass it directly to the onclick variable.
<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>
<script type="text/javascript">
document.getElementById("submit").onclick = changeit;
function changeit(event)
{
event.preventDefault();
pError = document.getElementById("passError");
pError.innerHTML = "wrong password";
}
</script>
You forgot one thing and have another typo mistake:
you forgot the closing curly bracket } at the end of your function changeit() as mentionned by #antyrat;
you want to put directly the string in the innerHTML assignation, not using parenthesis. (see the innerHTML documentation from MDN)
Moreover, you can also pass directly your changeit function instead of using an anonymous function and put your pError in a proper declarated variable. :)
As you are using a <form>, you also need to prevent the default behavior of the submit button by calling the preventDefault() function on the click event in your function.
The following code is working. I corrected these elements and just add some indentation and spacing to have a code more user-friendly.
<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>
<script type="text/javascript">
document.getElementById("submit").onclick = changeit;
function changeit(evt) {
evt.preventDefault();
var pError = document.getElementById("passError");
pError.innerHTML = "wrong password";
}
</script>

Pass script tag value to input tag in html

I am trying to pass a particular variable value from the script tag to an input tag. But somehow it is not working.
I am trying to pass variable1 value from the below code from script tag to input tag.
So suppose variable1 value is John then this line in my code will look like this-
<input ONCLICK="window.location.href='some_url&textId=John'">
Below is the code
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
// some more code
</script>
<input ONCLICK="window.location.href='some_url&textId=variable1'">
</body>
</html>
Can anyone explain me what wrong I am doing?
Try it that way:
var variable1 = getUrlVars()["parameter1"];
variable1 = unescape(variable1);
document.getElementById('Apply').onclick = function() {
window.location.href = 'some_url&textID=' + variable1;
};
That attaches a function to the onclick event that exactly does what you want. For the initial input element simply remove the onclick attribute:
<input name="Apply" type="button" id="Apply" value="Apply" />
If you wish to perform inline functions, you need to wrap the code in an executable closure:
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="(function() {window.location.href='your_data'})();">
As this can be largely unmaintainable, I recommend you abstract this functionality into a more organized place in your application.
(function(window, $, undefined) {
// assuming you use jQuery
$('#Apply').click(function() {
window.location.href = '';// your code
})
})(window, $);
I may be totally misunderstanding what you want to do, but I hope this helps.
The whole url parameters bit is surely unnecessary.
You can just set the value attribute in the field:
var field = document.getElementById('textfield');
var value = 'Some text';
field.addEventListener("click", function () {
this.setAttribute('value', value);
});
Here's a jsfiddle example: http://jsfiddle.net/LMpb2/
You have it inside the ' ' you need to add it into the string. So try
"window.location.href='some_url&textId='+variable1+';'"
I would change it to the following if your trying to bind the click handler to this input element:
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
document.getElementById("Apply").onclick = function() {
window.location.href='some_url&textId=' + variable1;
}
// some more code
</script>
<input name="Apply" type="button" id="Apply" value="Apply" >
</body>
</html>
I haven't tested it yet but it should work.
at onclick call a function, inside that function set window.locatio.href !
a sample
<script>
var url="www.google.com";
function myfunc(){
alert(url);
}
</script>
<input type="button" onclick="myfunc()" value="btn" >
http://jsfiddle.net/CgKHN/

Variable not sent to other function

I have a number of links, that when clicked on, passes a variable thru to another portion of the page.
Yet, for some reason, I can’t figure it out! What am I missing?
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
return myid;
}
</script>
</head>
<body>
Click Me<br />
<script type="text/javascript">
document.write(myid);
</script>
</body>
You are getting a little mixed up here. Even though the function returns a value, it has nothing to return it to. Try this:
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
document.getElementById("debug").innerHTML = myid;
}
</script>
</head>
<body>
Click Me<br />
<div id="debug"></div>
</body>
if you want to use it later you need to declare myid as a global variable. its scope is currently only within myFunction. also the document.write() function will only execute at runtime so you need to have another function the executes that with every click, or just combine the two.
When you click the link all that happens is that the myFunction() is called which returns the string. The line document.write(myid); is not executed anymore so nothing is visible.
<script>
// This is global
var myid = ''
myfunc = function(a){
myid = "Hi There!" + a;
alert(myid);
}
test_global = function(){
alert(myid);
}
</script>
Set MYID
<input type="button" onclick="test_global();" value="Test MYID" />
Here is a simple example of some similar stuff:
clickme or ClickMeAlso
<input id='other' type='text'/>
<script>
function myfunc(a) {
return a + " howdy";
};
</script>
You can see this in action here:http://jsfiddle.net/5Sbn2/

Categories

Resources